Selenium + Java · Lesson 19 of 44
Module 19: Browser Navigation & Windows
Your task
Implement switchToChildWindow:
Write it in the editor, then press Check answer (Ctrl + Enter).
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);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.
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.
___