Window / Tabs

Open a new window or tab and practice switching between handles.

Open blank tab
How to test
// Java
String original = driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(original)) {
        driver.switchTo().window(handle);
        break;
    }
}
// Optionally verify title or close
// driver.close();
// driver.switchTo().window(original);

# Python
original = driver.current_window_handle
for handle in driver.window_handles:
    if handle != original:
        driver.switch_to.window(handle)
        break
# driver.close()
# driver.switch_to.window(original)

// Java - Full Test
String original = driver.getWindowHandle();
int originalCount = driver.getWindowHandles().size();
driver.findElement(By.id("open_win")).click();
new WebDriverWait(driver, Duration.ofSeconds(5)).until(
    ExpectedConditions.numberOfWindowsToBe(originalCount + 1)
);
for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(original)) {
        driver.switchTo().window(handle);
        break;
    }
}
assert driver.getTitle().equals("Child Window");
driver.close();
driver.switchTo().window(original);

# Python - Full Test
original = driver.current_window_handle
original_count = len(driver.window_handles)
driver.find_element(By.ID, "open_win").click()
WebDriverWait(driver, 5).until(EC.number_of_windows_to_be(original_count + 1))
for handle in driver.window_handles:
    if handle != original:
        driver.switch_to.window(handle)
        break
assert driver.title == "Child Window"
driver.close()
driver.switch_to.window(original)

// Java - Alternative Solution
String current = driver.getWindowHandle();
driver.findElement(By.id("open_win")).click();
for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(current)) {
        driver.switchTo().window(handle);
        break;
    }
}
driver.close();
driver.switchTo().window(current);

# Python - Alternative Solution
current = driver.current_window_handle
driver.find_element(By.ID, "open_win").click()
for handle in driver.window_handles:
    if handle != current:
        driver.switch_to.window(handle)
        break
driver.close()
driver.switch_to.window(current)


Tester Task
  1. Store the current browser window handle.
  2. Click the button with id open_win.
  3. Wait for a new window handle to appear.
  4. Switch to the new window.
  5. Verify the child window title is Child Window.
  6. Close the child window and switch back to the original window.