Selenium + Java · Lesson 19 of 44

0/44 done

Module 19: Browser Navigation & Windows

19. Multi-Tab & Multi-Window Switching via Window Handles

16 minlesson

Your task

Implement switchToChildWindow:

  1. Accept WebDriver driver and String parentHandle.
  2. Iterate through driver.getWindowHandles() and switch to any handle != parentHandle.
  3. Return true if switched, otherwise false.

Write it in the editor, then press Check answer (Ctrl + Enter).

Window Handle Management

java
String parentWindow = driver.getWindowHandle();

// Click button that opens child tab:
driver.findElement(By.id("open-tab-btn")).click();

// Switch to new tab:
Set<String> allWindows = driver.getWindowHandles();
for (String handle : allWindows) {
    if (!handle.equals(parentWindow)) {
        driver.switchTo().window(handle);
        break;
    }
}

// Perform actions in child tab, then close and return:
driver.close();
driver.switchTo().window(parentWindow);

Key Takeaways & Walkthrough Summary

When users click external links or payment portals that open in a new window, Selenium does not automatically switch focus. In this lesson, you will master getWindowHandle, getWindowHandles, and driver.switchTo().window(). Let's handle multiple windows!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What happens if I close a child window without switching back to parent?

Any subsequent WebDriver command will throw NoSuchWindowException because the driver's target no longer exists.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip