Junior QASeleniumFree question
How do you handle multiple windows and tabs?
60-second answer
Each window or tab has a unique handle. I store the current handle with getWindowHandle, perform the action that opens the new window, then loop through getWindowHandles and switch to the one that isn't the original. After working in it, I close it and switch back to the original handle. In Selenium 4, I can also open a new tab or window directly with driver.switchTo().newWindow(WindowType.TAB). I wait for the number of windows to become two before switching.
Explanation
getWindowHandle()→ current;getWindowHandles()→Set<String>of all.switchTo().window(handle)to move.close()closes the current one; you must switch back afterwards or the next command fails withNoSuchWindowException.ExpectedConditions.numberOfWindowsToBe(2)avoids timing issues.
Example
Clicking "Terms" opens a new tab. Verify its title, close it, and continue checkout in the original tab.
Sample code
String main = driver.getWindowHandle();
driver.findElement(By.linkText("Terms")).click();
new WebDriverWait(driver, Duration.ofSeconds(5))
.until(ExpectedConditions.numberOfWindowsToBe(2));
for (String h : driver.getWindowHandles()) {
if (!h.equals(main)) { driver.switchTo().window(h); break; }
}
Assert.assertTrue(driver.getTitle().contains("Terms"));
driver.close();
driver.switchTo().window(main);
// Selenium 4: open a new tab yourself
driver.switchTo().newWindow(WindowType.TAB);