We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Handle multiple browser windows and tabs within a single WebDriver session.
Modern web apps often open links in new tabs or pop-up windows. Selenium treats each tab or window as a "Window Handle". To interact with a new window, you must explicitly switch to it.
getWindowHandle(): Get ID of current window.getWindowHandles(): Get IDs of ALL open windows.switchTo().window(id): Change focus to specific window.getWindowHandles().Clicking the button opens a popup. You must switch to it to click "Mark as Read"!
123456789101112131415161718192021String mainHandle = driver.getWindowHandle();
WebElement openHelpButton = driver.findElement(By.id("openHelpWindowBtn"));
openHelpButton.click();
Set<String> allHandles = driver.getWindowHandles();
for (String handle : allHandles) {
if (!handle.equals(mainHandle)) {
driver.switchTo().window(handle);
break;
}
}
// Now we are in the popup window
WebElement markHelpReadButton = driver.findElement(By.id("markHelpReadBtn"));
markHelpReadButton.click();
driver.close(); // Close popup
driver.switchTo().window(mainHandle); // Switch back to main
driver.quit();Create a small helper that sets common viewport sizes (mobile, tablet, desktop) so your setSize() calls stay consistent and reusable.
Use close() to close just one tab/window. Use quit() to close everything and end the session.
When switching windows, don’t rely on order—compare each handle to the main handle and switch to the different one.