Switching between windows 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.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration; import java.util.Set; public class WindowSwitchTest { 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 { driver.get("https://example.com/mainpage"); String originalWindow = driver.getWindowHandle(); // Click the link that opens a new window driver.findElement(By.id("open-new-window")).click(); // Wait for the new window or tab wait.until(driver1 -> driver1.getWindowHandles().size() > 1); Set<String> allWindows = driver.getWindowHandles(); String newWindow = null; for (String windowHandle : allWindows) { if (!windowHandle.equals(originalWindow)) { newWindow = windowHandle; break; } } // Switch to new window driver.switchTo().window(newWindow); // Verify the title of the new window String expectedNewTitle = "New Window Title"; String actualNewTitle = driver.getTitle(); if (!actualNewTitle.equals(expectedNewTitle)) { throw new AssertionError("New window title mismatch. Expected: " + expectedNewTitle + ", but got: " + actualNewTitle); } // Close the new window driver.close(); // Switch back to original window driver.switchTo().window(originalWindow); // Verify the title of the original window String expectedOriginalTitle = "Main Page Title"; String actualOriginalTitle = driver.getTitle(); if (!actualOriginalTitle.equals(expectedOriginalTitle)) { throw new AssertionError("Original window title mismatch. Expected: " + expectedOriginalTitle + ", but got: " + actualOriginalTitle); } System.out.println("Test passed: Window switching works correctly."); } finally { driver.quit(); } } }
This code uses Selenium WebDriver with Java to automate switching between browser windows.
First, it opens the main page and stores the original window handle.
Then it clicks a button that opens a new window and waits until the new window appears.
It finds the new window handle by comparing all handles to the original one.
Next, it switches to the new window and asserts the title matches the expected title.
After verification, it closes the new window and switches back to the original window.
Finally, it asserts the original window's title to confirm focus is back.
The try-finally block ensures the browser closes even if assertions fail.
Now add data-driven testing with 3 different links that open different new windows and verify their titles accordingly.