Window handles (getWindowHandles) in Selenium Java - Build an Automation Script
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.
Now add data-driven testing with 3 different links that open different new windows and verify their titles.