Selenium - How to get the number of tabs opened in a window?
Solution 1
Go to Home page and click on a link to open new tab/window. You can follow the steps below:
1. Open a browser and navigate to TestURL
2. Click Login link/button at the top right corner -> It will take you to a new
tab/window.
The followings are the Selenium Java code:
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
System.out.println("No. of tabs: " + tabs.size());
OR,
Set<String> allWindowHandles = driver.getWindowHandles();
ArrayList<String> tabs = new ArrayList<String>(allWindowHandles);
System.out.println("No. of tabs: " + tabs.size());
Solution 2
To get the count of number of tabs open in a window
ArrayList<String> multipleTabs = new ArrayList<String> (robot.getWebDriver().getWindowHandles());
Get the size of the arraylist i.e) count value
System.out.println(multipleTabs.size());
Hence the count of number of tabs opened in a window is nothing but the size of the above array list
sanaku
Updated on June 16, 2022Comments
-
sanaku almost 2 years
My test case :
- Open a browser and visit a URL
- Click on a link on the homepage -> This opens a new window/new tab.
- Go back to the homepage.
- Click another link.
- Ensure new content shows up on previously opened child window/child tab from step 2.
I can check the number of windows open by getting a count of the windowhandles, and assert that it is equal to 2 - to ensure that on clicking the second link, the content refreshes on the same child window and doesn't open another new window.
If in case the links open in new tabs, how can I check this test case ( New tab opened the first time a link is clicked on the homepage. And on further clicking any links on the homepage, content is refreshed on the same new tab)? Is there a way to count the number of tabs in a window?
Or does selenium force new tabs to be opened as new windows instead?
-
Ripon Al Wasim over 6 yearsWhy does it require robot?
-
Freedom almost 6 yearsbest solution is driver.getWindowHandles().size(), FYI all