Have a question?
Message sent Close
View Categories

Handling Multiple Browsers or Tabs

📄
filename.js
import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import java.util.Set;

public class WindowHandlingExample {

    public static void main(String[] args) throws InterruptedException {

        // 1. Point to your ChromeDriver executable

        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

        // 2. Launch Chrome

        WebDriver driver = new ChromeDriver();

        try {

            // 3. Navigate to the page with a link/button that opens a new window

            driver.get("https://example.com/multiple-windows");

            // 4. Store the handle of the main window

            String mainWindowHandle = driver.getWindowHandle();

            System.out.println("Main window handle: " + mainWindowHandle);

            // 5. Trigger opening a new window (adjust locator as needed)

            WebElement openNewWindowBtn = driver.findElement(

                By.xpath("//button[@id='openWindow']"));

            openNewWindowBtn.click();

            // 6. Wait briefly for the new window to open

            Thread.sleep(2000);

            // 7. Get all window handles

            Set<String> allWindowHandles = driver.getWindowHandles();

            System.out.println("All window handles: " + allWindowHandles);

            // 8. Switch to the newly opened window

            for (String handle : allWindowHandles) {

                if (!handle.equals(mainWindowHandle)) {

                    driver.switchTo().window(handle);

                    System.out.println("Switched to child window: " + handle);

                    break;

                }

            }

            // 9. Perform actions in the child window

            System.out.println("Child window title: " + driver.getTitle());

            // e.g., click something or read some text

            // WebElement childElement = driver.findElement(By.id("someElement"));

            // System.out.println(childElement.getText());

            // 10. Close the child window

            driver.close();

            System.out.println("Child window closed.");

            // 11. Switch back to the main window

            driver.switchTo().window(mainWindowHandle);

            System.out.println("Switched back to main window: " + driver.getTitle());

        } finally {

            // 12. Close all browser windows and end the session

            driver.quit();

        }

    }

}