How to handle multiple windows in Selenium?

Run Selenium Tests to handle Multiple Windows in real user conditions on real device cloud

Guide Banner Image
Home Guide How to handle multiple windows in Selenium?

How to handle multiple windows in Selenium?

Handling multiple windows in Selenium is essential for testing web applications that open new tabs or pop-ups.

Overview

Methods that will be used to handle multiple windows in Selenium:

  • getWindowHandle(): Retrieves the handle of the current browser window.
  • getWindowHandles(): Retrieves handles of all open browser windows.
  • Set<String>: Stores multiple window handles returned by getWindowHandles().
  • switchTo(): Switches the driver’s context between windows.
  • Action methods: Used to perform operations on the active window.

This guide covers how to switch between windows, capture window handles, and manage multiple browser contexts seamlessly during automation.

Handling Multiple Windows in Selenium using Window Handles

The user scenario being automated here is: Open a new tab and then switch back to the last window to complete the other pending activities. In such scenarios, Selenium helps to handle multiple windows through window handlers and javascript executors.

What is a Window Handle?

It is a unique identifier that holds the address of all the windows. Think of it as a pointer to a window, which returns the string value. It is assumed that each browser will have a unique window handle. This window handle function helps to retrieve the handles of all windows.

Syntax

  1. get.windowhandle(): This method helps to get the window handle of the current window
  2. get.windowhandles(): This method helps to get the handles of all the windows opened
  3. set: This method helps to set the window handles in the form of a string. set<string> set= driver.get.windowhandles()
  4. switch to: This method helps to switch between the windows
  5. action: This method helps to perform certain actions on the windows

These are some of the methods that will be used to handle multiple windows in Selenium.

Example of handling multiple windows using Window handles in Selenium

Scenario: Navigate to the BrowserStack home page. This is the parent window. From the parent window, let’s see how to handle the child windows and then again navigate back to the parent windows.

Steps to execute:

  1. Get the handle of the parent window using the command: String parentWindowHandle = driver.getWindowHandle();
  2. Print the window handle of the parent window.
  3. Find the element on the web page using an ID which is an element locator.
  4. Open multiple child windows.
  5. Iterate through child windows.
  6. Get the handles of all the windows that are currently open using the command: Set<String> allWindowHandles = driver.getWindowHandles(); which returns the set of handles.
  7. Use the SwitchTo command to switch to the desired window and also pass the URL of the web page.

Refer to the complete program below.

Before running the code, one should quickly check out the 6 things to avoid while running selenium scripts.

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

public class WindowHandle_Demo { 
public static void main(String[] args) throws Exception {


System.setProperty("webdriver.chrome.driver","Path to the driver"); 
WebDriver driver = new ChromeDriver();

driver.manage().window().maximize();

// Load the website
driver.get("http://www.naukri.com/");

// It will return the parent window name as a String
String parent=driver.getWindowHandle();

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

// Now iterate using Iterator
Iterator<String> I1= s.iterator();

while(I1.hasNext())
{

String child_window=I1.next();


if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);

System.out.println(driver.switchTo().window(child_window).getTitle());

driver.close();
}

}
//switch to the parent window
driver.switchTo().window(parent);

}
}

Output:

Handling multiple windows in Selenium

On executing the parent window handle, it will open multiple child windows and then navigate back to the final window handle.

Run Selenium Tests on Real Device Cloud for Free

Now let’s perform some actions on the BrowserStack website.

  • Use the javascriptexecutor to scroll down through a page.
  • Find the element using XPath and send keys (which is of the form string) to that particular element location.
  • Declare the web element Link to click on a particular link on the page. In this case, the link must open in a new window.
  • Get the window handles of all the windows and print them in a sequential manner.
  • Switch to the parent window and check if the title matches. If it does, scroll down the page using the javascriptexecutor.
  • Find another element on the web page using the element locator and specify the position of the new window.
  • Switch back to the parent window and scroll down through the page.

Pro Tip: Want to dive deeper into Selenium implementation on BrowserStack with free interactive courses and lab exercises? Visit Test University

Talk to an Expert

Code Snippet

import java.util.Set; 
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor; 
import org.openqa.selenium.Keys; 
import org.openqa.selenium.Point; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.chrome.ChromeDriver; 
import org.openqa.selenium.interactions.Actions; 

public class selenium { public static void main(String[] args) throws Exception 
{ 
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver.exe"); 
WebDriver driver = new ChromeDriver(); 
driver.get("https://www.browserstack.com/"); 
String title = driver.getTitle(); System.out.println(title);

JavascriptExecutor js = (JavascriptExecutor) driver; 
driver.findElement(By.xpath("//span[contains(text(),'Solutions')]")).click();
driver.findElement(By.xpath("//a[contains(text(),'Geolocation Testing')]")).click();
js.executeScript("window.scrollBy(0,40)"); 

WebElement link = driver.findElement(By.xpath("//a[@id='product-menu-toggle']//span[@class='account-down-caret']//*[local-name()='svg']")); 
Actions newwin = new Actions(driver); 
newwin.keyDown(Keys.SHIFT).click(link).keyUp(Keys.SHIFT).build().perform(); 
//Thread.sleep(2000); 
//js.executeScript("window.scrollBy(0,400)"); 
Thread.sleep(3000); 
Set<String> windows = driver.getWindowHandles(); 
System.out.println(windows); 
System.out.println("a1"); 
for (String window : windows) 
{ 
driver.switchTo().window(window); 
if (driver.getTitle().contains("Most Reliable App & Cross Browser Testing Platform | Browserstack")) 
{ 
System.out.println("a2"); 
js.executeScript("window.scrollBy(0,1000)"); 
System.out.println("b1");
driver.findElement(By.xpath("//a[@id='logo']//*[local-name()='svg']")).click();

driver.findElement(By.xpath("//a[@id='signupModalButton']")).click(); 
driver.manage().window().setPosition(new Point(2000, 0)); 
} 
} 
Thread.sleep(3000); 
Set<String> windows1 = driver.getWindowHandles(); 
System.out.println(windows1); 
System.out.println("a3"); 
for (String window : windows1) 
{ 
driver.switchTo().window(window); 
System.out.println("a4"); 
js.executeScript("window.scrollBy(0,400)"); 
} 
} 
}

On executing the code above, it will launch multiple windows, and the window handle will be retrieved. Run the code and automate user navigation through multiple windows. However, to ensure that the website works perfectly in real user conditions, it is essential to test on a real device cloud like BrowserStack for more accurate test results. It allows you to test on 3000+ real device browser combinations and maximize the test coverage. BrowserStack Automate allows running multiple Selenium tests simultaneously on its Cloud Selenium Grid using parallel testing.

Run Selenium Tests on Real Devices

Difference between getWindowHandle() and getWindowHandles() in Selenium

In Selenium, when working with web applications that open new tabs or pop-up windows, it becomes important to manage and switch between different browser windows. Selenium WebDriver provides two key methods for this:

  • getWindowHandle()

This method returns the unique identifier (handle) of the currently active browser window. It is typically used to store the original window’s handle so you can return to it later after interacting with other windows.

  • getWindowHandles()

This method returns a set of all window handles currently opened by the WebDriver. It allows you to iterate through all open browser windows or tabs and switch control as needed.

Here is a comparison table showing the main differences between getWindowHandle() and getWindowHandles()

MethodDescriptionReturn TypeUse Case
getWindowHandle()Retrieves the handle (ID) of the current browser windowStringTo store and return to the main window
getWindowHandles()Retrieves handles of all open browser windows/tabsSet<String>To switch between multiple open windows

How to switch to a new window in Selenium Webdriver using Java?

To switch to a new window in Selenium WebDriver using Java, follow these steps:

Step-by-Step Code Example:

java

// Store the current window handle (main window)

String mainWindowHandle = driver.getWindowHandle();




// Perform an action that opens a new window

driver.findElement(By.linkText("Open New Window")).click();




// Get all window handles

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




// Iterate through the window handles

for (String handle : allWindowHandles) {

    if (!handle.equals(mainWindowHandle)) {

        // Switch to the new window

        driver.switchTo().window(handle);

        break;

    }

}




// Now you're in the new window

System.out.println("Title of new window: " + driver.getTitle());

To return to the main window:

java

driver.switchTo().window(mainWindowHandle);

Notes:

  • Each window/tab has a unique handle (a String).
  • Always store the main window handle before opening a new one.
  • Use driver.close() to close the current window and driver.quit() to close all.

BrowserStack Automate Banner

Why run Window Handling Selenium tests on BrowserStack?

Testing window handling in Selenium across different environments is critical to ensure reliability. Here’s why BrowserStack Automate is a strong choice:

  • Cross-Browser Accuracy: Verify that window switching and pop-up handling work consistently across Chrome, Firefox, Safari, Edge, and more.
  • Real Device Cloud: Test on real mobile devices and desktops to reflect actual user environments, not just emulators or virtual machines.
  • Parallel Test Execution: Accelerate testing by running Selenium tests concurrently across multiple browser-OS combinations.
  • Reliable Pop-up Behavior: Pop-up and window behavior can vary by browser. BrowserStack provides accurate, environment-specific results.
  • Debugging Tools: Access detailed logs, screenshots, and session video recordings to quickly identify and fix issues in window handling.

BrowserStack helps you build confidence in your multi-window test automation by replicating real user conditions across devices and browsers.

Conclusion

Handling multiple windows in Selenium is essential for testing modern web applications with pop-ups and new tabs. By mastering window handles and switching techniques, you can build robust and reliable test scripts.

Run your multi-window tests seamlessly across real browsers and devices with BrowserStack Automate. With BrowserStack, ensure consistent behavior, faster execution, and effortless debugging.

Try BrowserStack Automate

Tags
Automation Testing Selenium Selenium Webdriver