Switch tabs in Selenium
- We have to get all the set of tabs present in the browser.
- When switching you might need to wait for 5 to 10 seconds for the types of browser windows to get generated.
2 Tabs:
You can switch between the tabs usingdriver.switchTo().window("handle")
String parentID = driver.getWindowHandle();
ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
if(parentID.equals(tabs2.get(0))) {
driver.switchTo().window(tabs2.get(1));
}else {
driver.switchTo().window(tabs2.get(0));
}
// perform your tasks on the newly created window
More than 2 tabs:
You need to bring the loop once you find the target window
String parentID = driver.getWindowHandle();
ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
for (String handle : tabs2) {
driver.switchTo().window(handle);
if(driver.getTitle().equals("your wish")) {
break;
}
}
// perform your tasks on the newly created window