How to Handle Multiple Windows in Selenium

  

In Selenium, Window Handle is a unique identifier (a string) for each browser window opened by the WebDriver. You can use window handles to switch between tabs or pop-up windows.


Common Use Cases

  • Handling multiple tabs/windows.

  • Switching control from parent to child window or vice versa.

  • Closing a pop-up and switching back.


Window Handle Methods

MethodDescription
driver.getWindowHandle()Returns the handle (ID) of the current window.
driver.getWindowHandles()Returns a Set<String> of all open windows' handles.
driver.switchTo().window(handle)Switches to the specified window by handle.


Selenium Java Example

Scenario:

Open a site → Click link that opens new window → Switch to it → Do something → Switch back.

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

import java.time.Duration;
import java.util.Set;

public class WindowHandleExample {
    public static void main(String[] args) {
        // Setup WebDriver
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();

        // Maximize window and set timeout
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

        // Open URL
        driver.get("https://demoqa.com/browser-windows");

        // Store the parent window handle
        String parentWindow = driver.getWindowHandle();

        // Click the button to open a new tab/window
        driver.findElement(By.id("windowButton")).click();

        // Get all window handles
        Set<String> allWindows = driver.getWindowHandles();

        // Loop through handles and switch to child
        for (String windowHandle : allWindows) {
            if (!windowHandle.equals(parentWindow)) {
                driver.switchTo().window(windowHandle);
                System.out.println("Switched to new window: " + driver.getTitle());

                // Perform some action in new window
                // (Assume there's a heading element to print)
                String heading = driver.findElement(By.id("sampleHeading")).getText();
                System.out.println("Heading: " + heading);

                // Close child window
                driver.close();
            }
        }

        // Switch back to parent
        driver.switchTo().window(parentWindow);
        System.out.println("Switched back to parent window: " + driver.getTitle());

        // Close everything
        driver.quit();
    }
}


Output

Switched to new window: ToolsQA
Heading: This is a sample page
Switched back to parent window: Browser Windows