Switch tabs using Selenium with Java

In selenium switching tabs is no different from switching browser windows; if you want to have a detailed tutorial you can visit the searching multiple browser windows.https://chercher.tech/java/handle-multiple-windows-tabs-selenium-webdriver

So, in short, let's see how to switch tabs using selenium

Let's say you have two tabs that are opened when you're clicking a button or when you're clicking a link. Now we have to get all the set of tabs present in the browser.

In most cases, when switching you might need to wait for 5 to 10 seconds for the types of browser windows to get generated.

2 Tabs:

If you are sure. Only two Tabs are going to present then it'll be easier for us because we have to subtract only the parent window handle from the set of window handles.

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:

If you have more than two tabs then instead of subtracting the parent ID from the set, you need to hydrate through these SET of window handles. By switching to every window handle you have to see his title or page URL and switch to that particular window based on the title or URL.

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
About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions