Selenium · Browser automation foundations
How do you handle multiple windows and tabs?
Short answer
Capture getWindowHandle before opening a new window, use getWindowHandles to find the new handle, switch with switchTo().window(handle), and close and switch back when done. Handle order is not guaranteed.
Each top-level browsing context has a window handle. A click that opens a new tab changes the set of handles. The driver stays on the original window until you switch explicitly.
String original = driver.getWindowHandle();
driver.findElement(By.linkText("Open invoice")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(original)) {
driver.switchTo().window(handle);
break;
}
}
Assert.assertTrue(driver.getTitle().contains("Invoice"));
driver.close();
driver.switchTo().window(original);- getWindowHandle returns the current window; getWindowHandles returns all open handles
- Handle strings are opaque and their order is not guaranteed
- switchTo().newWindow(WindowType.TAB) opens a new tab directly in Selenium 4
- close closes the current window, while quit ends the whole session
- A closed handle becomes invalid; switching to it throws
- Window state such as cookies and local storage is shared within the same browser session
Do not assume the second handle in the set is the new one. Either diff against the handles captured before the action or use the window title or URL to identify the target. If the action can open zero or several windows, encode that expectation instead of silently taking the first handle.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is handle order not reliable?
- 2What is the difference between close and quit here?
- 3How do you open a new tab directly?
- 4What happens if you switch to a closed window handle?
Say it in the interview
I capture the original handle, perform the action, then wait for the handle count to increase. I identify the new window by diffing handles or by its title or URL, never by index, because order is not guaranteed. After asserting, I close it and switch back to the original. Per-test driver isolation prevents leftover windows from affecting later tests.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Selenium mock interview and get scored feedback on depth, clarity and confidence.