πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 32 of 100
Popups & Windows
Intermediate

Switching Between Multiple Browser Windows

πŸͺŸScenario Overview

Switching Between Multiple Browser Windows

Key Takeaways & Cheat Sheet

  • βœ“Track current parent window handle using driver.getWindowHandle()
  • βœ“Retrieve all active window handles using driver.getWindowHandles()
  • βœ“Iterate handle lists and switch using driver.switchTo().window(handle)
  • βœ“Close temporary children handles and switch back to parent context

Short Direct Answer

To switch between multiple open windows or tabs, you must query their unique window handle tokens. Store the parent handle first, call `driver.getWindowHandles()` to fetch all open handles, loop through the handles to switch context to the new handle, perform actions, and explicitly switch back to the parent handle after closing the child tab.

⚠️ Senior Warning (Red Flag)

Never loop over getWindowHandles() and leave the driver focus on a closed window. If you close a child window, you must switch back to the parent window handle immediately, or all subsequent actions will fail.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Each window handle is a unique string token generated by the browser. They do not maintain a index-based array order, so iteration checks are mandatory.

SeleniumAutomation.java
Selenium 4 + Java
// βœ… Store parent window handle reference
String parentWindow = driver.getWindowHandle();

// Click button that opens a new window
driver.findElement(By.id("open-tab-btn")).click();

// βœ… Fetch all available open window handles
Set<String> allWindows = driver.getWindowHandles();

for (String windowHandle : allWindows) {
    if (!windowHandle.equals(parentWindow)) {
        // Switch context to child window
        driver.switchTo().window(windowHandle);
        System.out.println("Child Title: " + driver.getTitle());
        
        // Close child window
        driver.close();
        break;
    }
}

// βœ… Crucial step: Switch back to parent window
driver.switchTo().window(parentWindow);