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! π―