How to Handle Multiple Windows/Tabs in Selenium WebDriver? Selenium WebDriver Interview Question and Answer

How to Handle Multiple Windows/Tabs in Selenium?

Firstly, We will open three different tabs with different URLs and store unique identifier strings returned by the getWindowHandle() method in tab1, tab2, and tab3 string variables.

Next, we will switch to Tab 2 using the driver.switchTo().window() method.

We will then use the getWindowHandles() method to get the window handles and store them in a set of strings.

We will use iterator object to iterate over the set of window handles stored in the ‘tabs’ variable

Now, let’s run the program. It will open three tabs: the first tab with google.com, the second tab with testautomationcentral.com, and the third tab with the contact page.

Then, it will switch to the tab 2 with testautomationcentral.com.

Finally, it will iterate through all three tabs using the set of strings

package TestAutomationCentral;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.Iterator;
import java.util.Set;

public class HandlingWindows {
public static void main(String[] args) throws InterruptedException {
//TestAutomationCentral.com
System.setProperty("webdriver.chrome.driver", "C:\\temp\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
String tab1 = driver.getWindowHandle();

driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://testautomationcentral.com/");
String tab2 = driver.getWindowHandle();

driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://testautomationcentral.com/contact/");
String tab3 = driver.getWindowHandle();

driver.switchTo().window(tab2);
Thread.sleep(5000);

Set<String> tabs = driver.getWindowHandles();
Iterator<String> iterator = tabs.iterator();
while(iterator.hasNext()){
driver.switchTo().window(iterator.next());
Thread.sleep(5000);
}


}
}
Share

Leave a Reply