Handle multiple Window Handles

In real time, we face many scenarios, where an application throws multiple popups. These multiple windows can be handled using Selenium WebDriver which have method Windows Handles. Also, We use ‘Switch To’ method which allows us to switch control from one window to other.

 

import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MultipleWindowHandles{

public static void main(String[] args) {

System.setProperty("webdriver.gecko.driver", "E://Selenium//Selenium_Jars//chromedriver.exe");
WebDriver driver=new FirefoxDriver();

// To maximize browser
driver.manage().window().maximize();

// To open Tequality demo with multiple windows
driver.get("https://demoapp1.tequality.tech//");

// It will return the parent window name as a String
String mainWindow=driver.getWindowHandle();

// It returns no. of windows opened by WebDriver and will return Set of Strings
Set<String> set =driver.getWindowHandles();

// Using Iterator to iterate with in windows
Iterator<String> itr= set.iterator();

while(itr.hasNext()){
String childWindow=itr.next();

// Compare whether the main windows is not equal to child window. If not equal, we will close.
if(!mainWindow.equals(childWindow)){
driver.switchTo().window(childWindow);
System.out.println(driver.switchTo().window(childWindow).getTitle());
driver.close();
}
}

// This is to switch to the main window
driver.switchTo().window(mainWindow);
}
}