Handling Multiple Windows in Selenium WebDriver

πŸ”Ή What is Multiple Window Handling in Selenium?

When you click on a link, button, or perform an action, a new window or tab may open. By default, Selenium stays focused on the main window and does not automatically switch to the new one.

βœ” Selenium provides methods to handle multiple windows effectively:

  • getWindowHandle()
  • getWindowHandles()
  • switchTo().window()
  • close()
  • quit()

πŸ”Ή Why Do We Need to Handle Multiple Windows in Selenium?

In real-world web applications, clicking a link or button often opens a new tab or window.
By default, Selenium only interacts with the first opened window and does not automatically switch to newly opened ones. If we try to interact with elements in the new window without switching, Selenium will throw an error like:

org.openqa.selenium.NoSuchElementException: Unable to locate element

πŸ’‘ Real-World Scenarios Where Multiple Window Handling is Needed

1️⃣ Login/Signup Pop-ups β†’ Clicking "Login with Google" opens a new authentication window.
2️⃣ Payment Gateways β†’ Clicking "Proceed to Payment" opens a payment provider’s page.
3️⃣ Product Details in E-commerce β†’ Clicking on a product opens a new tab with details.
4️⃣ File Upload/Download Windows β†’ Clicking a "Browse" button opens a system file selector.
5️⃣ Advertisement Pop-ups β†’ Some sites open new pop-ups or windows for ads.


πŸ”Ή How Selenium Identifies and Switches Between Windows

Each browser window or tab is assigned a unique identifier called a Window Handle.
Selenium provides methods to retrieve, switch, and manage multiple windows.

πŸ“Œ Key Methods for Handling Multiple Windows

Method Description
getWindowHandle() Gets the current active window's handle.
getWindowHandles() Returns all open window handles.
switchTo().window(handle) Switches Selenium’s focus to the specified window.
close() Closes only the current window.
quit() Closes all browser windows and ends the session.



πŸ”Ή Methods for Handling Multiple Windows in Selenium

1️⃣ getWindowHandle() – Get Current Window Handle

βœ… This method retrieves the unique identifier (window handle) of the current browser window.

πŸ”Έ Syntax:

String parentWindow = driver.getWindowHandle();
System.out.println("Parent Window Handle: " + parentWindow);

βœ… Returns: A unique string ID representing the window.


2️⃣ getWindowHandles() – Get All Window Handles

βœ… This method returns a Set of all open window handles.

πŸ”Έ Syntax:

Set<String> allWindows = driver.getWindowHandles();
System.out.println("All Window Handles: " + allWindows);

βœ… Returns: A Set of Strings, each representing a unique window.


3️⃣ switchTo().window(handle) – Switch Between Windows

βœ… This method allows us to switch focus from one window to another using the window handle.

πŸ”Έ Syntax:

driver.switchTo().window(windowHandle);

4️⃣ close() – Close Current Window

βœ… This method closes the active window but keeps other windows open.

πŸ”Έ Syntax:

driver.close();

5️⃣ quit() – Close All Windows

βœ… This method closes all browser windows and terminates the WebDriver session.

πŸ”Έ Syntax:

driver.quit();

πŸ”Ή How to Switch Between Multiple Windows in Selenium

πŸ“Œ Scenario: Switching to a New Window and Performing an Action

πŸ”Ή Step-by-Step Explanation

1️⃣ Open a website.
2️⃣ Click on a link that opens a new window.
3️⃣ Get all window handles.
4️⃣ Switch to the new window.
5️⃣ Perform some actions.
6️⃣ Switch back to the original window.

πŸ”Έ Example Code:

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 HandleMultipleWindows {
    public static void main(String[] args) throws InterruptedException {
        // Launch Browser
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com"); // Open main website

        // Store the Parent Window ID
        String parentWindow = driver.getWindowHandle();
        System.out.println("Parent Window: " + parentWindow);

        // Click on a link that opens a new window
        WebElement link = driver.findElement(By.xpath("//a[@target='_blank']"));
        link.click();
        
        // Get All Window Handles
        Set<String> allWindows = driver.getWindowHandles();
        
        for (String window : allWindows) {
            if (!window.equals(parentWindow)) {
                driver.switchTo().window(window);  // Switch to new window
                System.out.println("Switched to New Window: " + window);
                System.out.println("New Window Title: " + driver.getTitle());
                
                // Perform any action (Example: Click a button)
                driver.findElement(By.id("submit")).click();

                // Close the New Window
                driver.close();
            }
        }

        // Switch back to the Parent Window
        driver.switchTo().window(parentWindow);
        System.out.println("Back to Parent Window: " + driver.getTitle());

        driver.quit();  // Close All Windows
    }
}

βœ” Explanation:

  • Stores the Parent Window ID before clicking on a new link.
  • Uses getWindowHandles() to get all open windows.
  • Iterates through the handles and switches to the new window.
  • Performs an action (clicks a button).
  • Closes the new window and switches back to the main window.


πŸ”Ή Handling Multiple Windows Using Iterator

We can also use Iterator to loop through multiple windows.

πŸ”Έ Example Using Iterator:

import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class WindowHandlingWithIterator {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");

        // Click a button that opens a new window
        driver.findElement(By.xpath("//a[@target='_blank']")).click();

        // Get all window handles
        Set<String> handles = driver.getWindowHandles();
        Iterator<String> iterator = handles.iterator();

        String parent = iterator.next();
        String child = iterator.next();

        driver.switchTo().window(child);
        System.out.println("Child Window Title: " + driver.getTitle());
        driver.close();  // Close child window

        driver.switchTo().window(parent);
        System.out.println("Back to Parent Window: " + driver.getTitle());

        driver.quit();  // Close all windows
    }
}

βœ… Key Difference: Uses Iterator instead of a loop.


πŸ”Ή Handling Multiple Tabs in Selenium

πŸ”Έ Scenario:

When you open a new tab instead of a new window, the handling method is the same.

πŸ”Έ Example of Opening a New Tab Using JavaScriptExecutor:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;

public class HandleMultipleTabs {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");

        // Open a new tab using JavaScript
        ((JavascriptExecutor) driver).executeScript("window.open()");
        
        // Get all window handles
        Set<String> handles = driver.getWindowHandles();
        String[] windowArray = handles.toArray(new String[0]);

        driver.switchTo().window(windowArray[1]); // Switch to new tab
        driver.get("https://www.google.com"); // Open new URL
        System.out.println("New Tab Title: " + driver.getTitle());

        driver.close();  // Close new tab
        driver.switchTo().window(windowArray[0]); // Switch back to main tab
        driver.quit();  // Close all
    }
}

βœ… JavaScriptExecutor opens a new tab, then we switch to it and load a different URL.


πŸ”Ή Switching Between Multiple Windows Using Window Titles

πŸ”Έ Example:

public void switchToWindowWithTitle(String expectedTitle) {
    Set<String> allWindows = driver.getWindowHandles();
    
    for (String window : allWindows) {
        driver.switchTo().window(window);
        if (driver.getTitle().equals(expectedTitle)) {
            break;
        }
    }
}

βœ… Switches to a window based on its title.


πŸ”Ή Handling Pop-ups & Authentication Windows

1️⃣ Handling Authentication Pop-ups

πŸ”Έ Example Using URL Encoding:

String username = "admin";
String password = "password";
driver.get("https://" + username + ":" + password + "@example.com");

βœ… Bypasses login pop-ups using credentials in the URL.


πŸ”Ή Key Takeaways

βœ” getWindowHandle() β†’ Gets the current window handle.
βœ” getWindowHandles() β†’ Gets all window handles.
βœ” switchTo().window(handle) β†’ Switches to a specific window.
βœ” close() β†’ Closes the current window.
βœ” quit() β†’ Closes all windows.
βœ” JavaScriptExecutor β†’ Can open new tabs programmatically.

πŸš€ Now you can handle multiple windows, tabs, and pop-ups efficiently in Selenium! 🎯