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);