Selenium Windows And Tabs

Every open browser window or tab has a unique ID string called a window handle. Selenium uses these handles to jump between windows, similar to how a person clicks between open browser tabs.

Diagram: Multiple Windows With Handles

Browser Session
   |
   |-- Window Handle: "CDwindow-A1B2" (Main Page)
   |-- Window Handle: "CDwindow-C3D4" (New Tab from a link)

Getting The Current Window Handle

String mainWindow = driver.getWindowHandle();

This stores the ID of the window currently in focus, useful for returning to it later.

Getting All Window Handles

Set<String> allWindows = driver.getWindowHandles();

This returns every open window handle as a set of strings, including the main window and any new tabs.

Switching Between Windows

for (String handle : allWindows) {
    if (!handle.equals(mainWindow)) {
        driver.switchTo().window(handle);
    }
}

This loop finds the handle that does not match the main window and switches focus to that new window.

A Complete New Tab Example

String mainWindow = driver.getWindowHandle();
driver.findElement(By.linkText("Open in New Tab")).click();

Set<String> windows = driver.getWindowHandles();
for (String handle : windows) {
    if (!handle.equals(mainWindow)) {
        driver.switchTo().window(handle);
        break;
    }
}

System.out.println(driver.getTitle());
driver.close();
driver.switchTo().window(mainWindow);

This script clicks a link that opens a new tab, switches to that tab, reads its title, closes it, and returns focus to the original window.

close() Versus quit()

close() shuts only the window currently in focus, leaving other windows open. quit() shuts every window and ends the browser session completely. Mixing these up often leaves orphaned browser processes running during automated test suites.

Opening A New Tab With Selenium 4

Selenium 4 introduced a direct method for opening tabs without relying on clicking a link.

driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://www.estudy247.com/pricing");

This opens a fresh tab and loads a new URL inside it directly, useful when a test needs to compare content across two pages side by side.

Practical Example

A course website opens payment receipts in a new browser tab after checkout. A test script captures the main window handle before clicking Checkout, switches to the receipt tab once it opens, verifies the order number text, closes the receipt tab, and switches back to continue testing the main site.

Leave a Comment

Your email address will not be published. Required fields are marked *