0
0
Selenium Javatesting~15 mins

Window handles (getWindowHandles) in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Verify switching between multiple browser windows using getWindowHandles
Preconditions (2)
Step 1: Open the main test page URL
Step 2: Click on the link that opens a new browser window
Step 3: Get all window handles using getWindowHandles()
Step 4: Switch to the newly opened window
Step 5: Verify the title of the new window is as expected
Step 6: Close the new window
Step 7: Switch back to the original window
Step 8: Verify the title of the original window is as expected
✅ Expected Result: The test switches correctly between the original and new window, verifies titles, and closes the new window without errors.
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify the new window title matches expected
Verify the original window title matches expected after switching back
Best Practices:
Use explicit waits if needed before switching windows
Store original window handle before opening new window
Use getWindowHandles() to get all open windows
Switch windows using driver.switchTo().window(handle)
Close only the new window, not the original
Use try-finally or proper cleanup to avoid leftover windows
Automated Solution
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.Set;

public class WindowHandlesTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        try {
            // Step 1: Open main page
            driver.get("https://example.com/testpage");
            String originalWindow = driver.getWindowHandle();

            // Step 2: Click link that opens new window
            driver.findElement(By.id("open-new-window")).click();

            // Step 3: Wait for new window
            wait.until(driver1 -> driver1.getWindowHandles().size() > 1);

            // Step 4: Get all window handles
            Set<String> allWindows = driver.getWindowHandles();

            // Step 5: Switch to new window
            for (String windowHandle : allWindows) {
                if (!windowHandle.equals(originalWindow)) {
                    driver.switchTo().window(windowHandle);
                    break;
                }
            }

            // Step 6: Verify new window title
            String newWindowTitle = driver.getTitle();
            if (!newWindowTitle.equals("New Window Title")) {
                throw new AssertionError("New window title mismatch. Expected: 'New Window Title', Found: '" + newWindowTitle + "'");
            }

            // Step 7: Close new window
            driver.close();

            // Step 8: Switch back to original window
            driver.switchTo().window(originalWindow);

            // Step 9: Verify original window title
            String originalTitle = driver.getTitle();
            if (!originalTitle.equals("Original Window Title")) {
                throw new AssertionError("Original window title mismatch. Expected: 'Original Window Title', Found: '" + originalTitle + "'");
            }

            System.out.println("Test passed: Window handles switched and verified successfully.");

        } finally {
            driver.quit();
        }
    }
}

This code starts by opening the main test page and saving the original window handle. It clicks a link that opens a new window. Then it waits until there are more than one window handles available.

It collects all window handles and switches to the one that is not the original. It verifies the new window's title matches the expected value.

After verification, it closes the new window and switches back to the original window. It then verifies the original window's title to confirm the switch back was successful.

Finally, it quits the driver to close all browser windows. The code uses explicit waits and proper window handle management to avoid errors.

Common Mistakes - 4 Pitfalls
Not storing the original window handle before opening the new window
Using Thread.sleep() instead of explicit waits to wait for new window
Closing the original window instead of the new window
Hardcoding window handles or assuming order of handles
Bonus Challenge

Now add data-driven testing with 3 different links that open different new windows and verify their titles.

Show Hint