Switching Tabs in Selenium for Java
Switching Tabs in Selenium for Java
Learn how to switch to a new window or tab in Selenium for Java
In today’s recipe, we’ll look at how to navigate to a new tab within Selenium WebDriver.
Let’s first grab the ID for this button which will trigger the new tab to be opened. It’s “button-the-kitchen-table”.
How to Use Selenium Window Handles to Switch Tabs
We’ll say, driver.findElement(By.id()). We’ll pass it the ID of that button and we’ll .click the button. This will open the new tab.
From here, we have 2 tabs open so we can use the driver.getWindowHandles method within Selenium, and this will give us a set of window handles.
From this set, we can then do a forEach, which will loop through all the window handles.
We’ll call each of those windows a tab. And we’ll say, “Selenium, we want you to switch to this window and we can pass in the tab” using .forEach(tab->driver.switchTo().window(tab)).
Since the set of window handles is arranged in the order that they were opened, we know that the last handle within the set will be the last open tab.
That means this line of code will move us to that last open tab and then from here, we can verify that this table is displayed. We’ll say assertTrue() and we’ll use Selenium to find that table element using driver.findElement(By.id(“fruits-vegetables”). Then we’ll call isDisplayed().
And there you have it, that’s how you navigate to a new tab with Selenium WebDriver.
Resources
- Git Repo – TabTests.java
- Applitools Kitchen – Testing Tab Links
Schedule a free Applitools Demonstration
Request DemoHere’s the code sample from our tutorial on how to switch to a new window or tab in Selenium for Java