Selenium WebDriver provides an alphanumeric ID for each window as soon as the WebDriver object is given instantiated. This unique alphanumeric ID is called window handle id in Selenium. With the help of this unique ID we can switch control between multiple windows. In simple words, each unique window has a unique ID, so that selenium can differentiate when it is switching from one window to another window.
Important commands for handling Multiple Windows
GetWindowHandle() – It helps us to get the window handle of the current window. GetWindowHandles() – It helps us to get the window handle of all the currently open windows. It Stores all currently open windows into String Set. SwitchTo() – WebDriver object supports moving between named windows using this method.
Example of Handle Multiple Windows :
package automationTestingLab;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Handle_Window {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","F:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://rahulshettyacademy.com/AutomationPractice/");
System.out.println("== Before Open new window :- " + driver.getTitle());
// click on open window button to open new window
WebElement newWindowButton = driver.findElement(By.id("openwindow"));
newWindowButton.click();
// Get all the window handles id
Set<String> windowIDs = driver.getWindowHandles();
// Creating a variable which can iterate through all the window ids
Iterator<String> it = windowIDs.iterator();
// Get the parent window id
String parentWindow = it.next();
// Get the Child window id
String childWindow = it.next();
// Switch to webdriver object to child window
driver.switchTo().window(childWindow);
System.out.println("== After open child window:- " + driver.getTitle());
// Switch back to Parent window
driver.switchTo().window(parentWindow);
System.out.println("== After switching back to Parent window:- " + driver.getTitle());
driver.close(); //It will close only focused window
}
}