Testing / Selenium Interview questions
How does Selenium handle multiple windows and tabs?
Selenium tracks open browser windows/tabs by string handles, and driver.getWindowHandle() returns the handle for the currently focused one, while driver.getWindowHandles() returns the handles of all open windows in that session.
String original = driver.getWindowHandle(); driver.findElement(By.linkText("Open new tab")).click(); for (String handle : driver.getWindowHandles()) { if (!handle.equals(original)) { driver.switchTo().window(handle); break; } }
Unlike frameworks with an event-based "new page" notification, Selenium requires manually diffing the handle sets before and after the action that opens the new window, then explicitly calling switchTo().window() to move WebDriver's focus - all subsequent commands target whichever window was last switched to.
Closing a secondary window doesn't automatically return focus to the original one either - after calling driver.close() on the popup, the original handle must still be passed to switchTo().window() explicitly before continuing.
More Related questions...