Q15 of 37 · Selenium

How do you switch between windows and tabs in Selenium?

SeleniumMidseleniumwindowstabsswitchTo

Short answer

Short answer: Track window handles with `getWindowHandles()`, identify the new one by diffing against the original, and switch with `driver.switchTo().window(handle)`. Always switch back when done — nothing does it for you.

Detail

Selenium tracks every browser window or tab as a window handle — an opaque string. Operations only affect the currently focused handle, so anything multi-window means switching handles deliberately.

The standard pattern:

String original = driver.getWindowHandle();      // remember the current
Set<String> before = driver.getWindowHandles();  // snapshot before action

driver.findElement(By.linkText("Open in new tab")).click();

// Wait for a new handle to appear, then switch to it
new WebDriverWait(driver, Duration.ofSeconds(5))
    .until(d -> d.getWindowHandles().size() > before.size());

Set<String> after = driver.getWindowHandles();
after.removeAll(before);
String newHandle = after.iterator().next();

driver.switchTo().window(newHandle);
// ...do work in the new tab...

driver.close();                       // close the new tab
driver.switchTo().window(original);   // switch back

Important details:

  • getWindowHandle() (singular) returns the current; getWindowHandles() (plural) returns all open handles as a Set — order is not guaranteed.
  • Selenium 4 added driver.switchTo().newWindow(WindowType.TAB) and WindowType.WINDOW for opening fresh handles programmatically — the new tab is automatically focused.
  • driver.close() closes the current window; the focus then becomes invalid until you call switchTo().window(...). This is the source of "next assertion silently fails" bugs.

The senior point: always switch back to a known handle at the end of the multi-window section. Tests that leak focus state into the next test are a common form of suite-level flake.

// EXAMPLE

String original = driver.getWindowHandle();

driver.findElement(By.cssSelector("[data-test=open-help]")).click();

// Switch to whichever new window appeared
new WebDriverWait(driver, Duration.ofSeconds(5))
    .until(ExpectedConditions.numberOfWindowsToBe(2));

for (String h : driver.getWindowHandles()) {
    if (!h.equals(original)) {
        driver.switchTo().window(h);
        break;
    }
}

assertEquals("Help — Acme", driver.getTitle());
driver.close();
driver.switchTo().window(original);

// WHAT INTERVIEWERS LOOK FOR

The handle-diffing pattern, awareness that close() leaves focus invalid, and bonus knowledge of Selenium 4's switchTo().newWindow API.

// COMMON PITFALL

Closing a tab and assuming Selenium auto-focuses the previous one — it doesn't. Or relying on handle order from getWindowHandles() (a Set) — order is not guaranteed.