0
0
Selenium Javatesting~15 mins

Switching between windows in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Verify switching between browser windows
Preconditions (2)
Step 1: Click the link or button that opens a new window
Step 2: Switch the WebDriver focus to the newly opened window
Step 3: Verify the title of the new window matches the expected title
Step 4: Close the new window
Step 5: Switch the WebDriver focus back to the original window
Step 6: Verify the title of the original window matches the expected title
✅ Expected Result: The test should successfully switch to the new window, verify its title, close it, then switch back to the original window and verify its title
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Assert the title of the new window is as expected
Assert the title of the original window is as expected after switching back
Best Practices:
Use explicit waits if needed before switching windows
Store window handles properly to switch between them
Close only the new window before switching back
Use try-finally or proper cleanup to avoid leaving windows open
Automated Solution
Selenium Java
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.

Common Mistakes - 3 Pitfalls
Not waiting for the new window to open before switching
Hardcoding window handles instead of retrieving them dynamically
Closing the original window instead of the new window
Bonus Challenge

Now add data-driven testing with 3 different links that open different new windows and verify their titles accordingly.

Show Hint