Multiple Windows and Tabs

Window Handles

Each window or tab has a unique id called a window handle. getWindowHandle() returns the current one; getWindowHandles() returns all of them.

String main = driver.getWindowHandle();
driver.findElement(By.linkText("Seller details")).click();   // opens in a new tab (target="_blank")
wait.until(ExpectedConditions.numberOfWindowsToBe(2));

for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(main)) {
        driver.switchTo().window(handle);
        break;
    }
}
System.out.println("New tab: " + driver.getTitle());
driver.close();                      // close only the seller tab
driver.switchTo().window(main);      // must switch back, the closed tab is gone
System.out.println("Back on: " + driver.getTitle());

Example

Output:

Run SellerTabTest.main()

Example output

New tab: SportsHub Retail - Seller on ShopEase
Back on: Nike Revolution 7 - ShopEase

Finding the New Handle

Example

The "which handle is new" logic is a set difference. Handles below are made-up strings like the ones Selenium returns:

import java.util.*;

public class Main {
    static String newHandle(Set<String> before, Set<String> after) {
        Set<String> diff = new LinkedHashSet<>(after);
        diff.removeAll(before);
        if (diff.size() != 1) throw new IllegalStateException("expected 1 new window, found " + diff.size());
        return diff.iterator().next();
    }

    public static void main(String[] args) {
        Set<String> before = new LinkedHashSet<>(List.of("CDwindow-A1F3"));
        Set<String> after = new LinkedHashSet<>(List.of("CDwindow-A1F3", "CDwindow-9B22"));
        System.out.println("Switch to: " + newHandle(before, after));
        try {
            newHandle(before, before);
        } catch (IllegalStateException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output

Switch to: CDwindow-9B22
Error: expected 1 new window, found 0