Handling multiple windows
• WebDriver interface has two predefined methods getWindowHandles()
and switchTo() , which helps us in handling multiple browser windows.
• getWindowHandles() - Used to retrieve all the ids of the currently
opened windows (Windows can be popup-windows, windows opened in
new tabs etc)
package seleDemoPack;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleDemo {
public static void main(String args[]) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("https://iamsandesh23.github.io/selenium.github.io/");
driver.manage().window().maximize();
driver.findElement(By.linkText("Open a popup window")).click();
Thread.sleep(5000);
Set<String> set = driver.getWindowHandles();
Iterator<String> itr = set.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
driver.close();
}
}
• switchTo() - Used to switch between different windows when multiple
windows are opened by using the ids of the currently opened windows
which are returned by getWindowHandles()
package seleDemoPack;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleDemo {
public static void main(String args[]) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("https://iamsandesh23.github.io/selenium.github.io/");
driver.manage().window().maximize();
driver.findElement(By.linkText("Open a popup window")).click();
Thread.sleep(5000);
Set<String> set = driver.getWindowHandles();
Iterator<String> itr = set.iterator();
String mainWindow = itr.next();
String childWindow = itr.next();
driver.switchTo().window(childWindow);
Thread.sleep(5000);
driver.close();
driver.switchTo().window(mainWindow);
Thread.sleep(5000);
driver.close();
}
• Syntax: switchTo().window("Retrieved Window ID");