How to handle multiple windows in Selenium?

Related Product On This Page Handling Multiple Windows in Selenium utilise Window Handles<

April 01, 2026 · 10 min read · Tool Comparison
Related Product

How to handle multiple windows in Selenium?

Most examiner often thinkhandling multiple window inis straightforward—just switch and continue.

But around47 % of testers shin with managing pop-ups, modal, and new browser window in Selenium, often ensue in and inconsistent results.

I thought everything was hunky-dory too—until atest involving a popup, a redirected tab, and the main window beganfailing unpredictably.

Selenium kept interacting with the wrong window, and I wasted hr trying postponement, switching by title, and former hack that didn ’ t fix anything.

That ’ s when I realized the real matter wasn ’ t Selenium at all—it was my want of savvy ofhow window handle actually work.

Pop-ups breaking your Selenium tests?

Get expert advice on how to handle multiple browser windows seamlessly in Selenium.

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

Overview

Handling multiple windows in Selenium allows your test to switch between popups, tabs, and new browser windows without losing context.

How window handles are used in Selenium:

  • Identifying Each Window/Tab:Whenever Selenium opens multiple tabs or popups, the browser assigns a unique alphameric ID to each one. This ID—called a window handle—acts like the window ’ s speech, allowing Selenium to reference it straightaway.
  • Switching Control:WebDriver can merely act on the window it ’ s currently focused on. To interact with another tab or popup, you must switch control to it using its hold via driver.switchTo () .window (handle).

Handling multiple windows in Selenium:

  • getWindowHandle ():Retrieves the hold of the current browser window.
  • getWindowHandles ():Retrieves handles of all open browser window.
  • Set & lt; String & gt;:Stores multiple window handles returned by getWindowHandles ().
  • switchTo ():Switches the driver ’ s context between window.
  • Action method:Used to perform operations on the active window.

Now let ’ s dive into the pragmatic steps that helped me handle multiple windows in Selenium effectively.

Handling Multiple Windows in Selenium using Window Handles

A commontesting scenario involves open a new tab or popup,performing an action there, and soswitching rearward to the original windowto continue the remaining steps.

Selenium supports this workflow habituate window hold, which let you identify each open window, and JavaScript executors, which can help trigger new tabs when needed.

Together, they allow WebDriver to switch focus seamlessly between multiple browser windows.

What is a Window Handle?

A window handle is a unique identifier assigned to every browser window or tab in a Selenium session. Think of it as the window ’ s speech, stored as a string, that WebDriver uses to locate the correct window before interacting with it.

Since each window has its own handle, WebDriver can use these identifiers to switch control, find all open windows, and treat multi-window workflows dependably.

According toCrissy Joshua, handling multiple windows in Selenium get more dependable when tests explicitly track window handles and switch context only when needed, ensuring interactions are always performed on the intended browser window and reducing flaky test behavior.

Syntax

  1. get.windowhandle (): This method helps to get the window handle of the current window
  2. get.windowhandles (): This method help to get the handles of all the windows opened
  3. set: This method help to set the window handgrip in the form of a string.set & lt; string & gt; set= driver.get.windowhandles ()
  4. permutation to:This method facilitate to switch between the window
  5. action: This method helps to do sure actions on the window

These are some of the method that will be expend to treat multiple windows in Selenium.

Read More:

Example of handling multiple windows apply Window handles in Selenium

Scenario: Navigate to the. 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.

Read More:

Steps to execute:

  1. Get the handgrip of the parent window using the bid:String parentWindowHandle = driver.getWindowHandle ();
  2. Print the window hold of the parent window.
  3. Find the element on the web page use an ID which is an element locator.
  4. Open multiple child window.
  5. Iterate through fry windows.
  6. Get the handles of all the windows that are presently open using the bid:Set & lt; String & gt; allWindowHandles = driver.getWindowHandles ();which returns the set of handles.
  7. Use the SwitchTocommand to switch to the desired window and also legislate the URL of the web page.

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

Refer to the complete program below.

Before running the code, one should quickly check out the.

import java.util.Iterator; importee java.util.Set; import org.openqa.selenium.By; meaning org.openqa.selenium.WebDriver; importation org.openqa.selenium.chrome.ChromeDriver; public stratum WindowHandle_Demo {public static emptiness master (String [] args) throw 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 & lt; String & gt; s=driver.getWindowHandles (); // Now restate using Iterator Iterator & lt; String & gt; 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:

On execute the parent window grip, it will open multiple child windows and then sail back to the last window handle.

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

  • Use the javascriptexecutorto scroll down through a page.
  • Find the factor using and (which is of the form twine) to that particular element location.
  • Declare the web elementLinkto snap on a particular connectedness on the page. In this case, the connectedness must open in a new window.
  • Get the window handles of all the windows and publish them in a sequential manner.
  • Switch to the parent window and check if the title matches. If it does, scroll down the page using thejavascriptexecutor.
  • Find another element on the web page using the and specify the position of the new window.
  • Switch back to the parent window and through the page.

Tests Failing When Pop-ups Appear?

Get expert advice on how to treat multiple browser windows seamlessly in Selenium.

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; significance org.openqa.selenium.WebDriver; significance org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class selenium {public static nothingness 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 (connectedness) .keyUp (Keys.SHIFT) .build () .perform (); //Thread.sleep (2000); //js.executeScript (`` window.scrollBy (0,400) ''); Thread.sleep (3000); Set & lt; String & gt; windows = driver.getWindowHandles (); System.out.println (windows); System.out.println (`` a1 ''); for (String window: windows) {driver.switchTo () .window (window); if (driver.getTitle () .contains (`` Most Dependable App & amp; 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 & lt; String & gt; 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 codification above, it will launch multiple windows, and the window handle will be find. Run the codification and automate user navigation through multiple windows. However, to ensure that the website works utterly in, it is indispensable to test on a like BrowserStack for more precise test solvent. It allows you to test on 3000+ existent device browser combinations and. allows run multiple Selenium tests simultaneously on its use.

Difference between getWindowHandle () and getWindowHandles () in Selenium

In Selenium, when act with web covering that open new tabs or pop-up windows, it becomes important to manage and shift between different browser windows. Selenium WebDriver supply two key method for this:

  • getWindowHandle ()

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

  • getWindowHandles ()

This method returns aset of all window handlespresently open by the WebDriver. It allows you to iterate through all exposed browser windows or tabs and switch control as require.

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

MethodDescriptionReturn TypeUse Case
getWindowHandle ()Retrieves the handle (ID) of the current browser windowStringTo store and retrovert to the main window
getWindowHandles ()Retrieves handles of all open browser windows/tabsSet & lt; String & gt;To switch between multiple open windows

BrowserStack experts can facilitate you leverage these methods effectively across different environments and assist you in handling complex window-switching scenarios.

Get Expert QA Guidance Today

to discuss your testing challenges, automation strategies, and tool integrating. Gain actionable insights tailored to your projects and control fast, more reliable package delivery.

Tests Failing When Pop-ups Appear?

Get expert advice on how to care multiple browser windows seamlessly in Selenium.

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

To change to a new window in Selenium WebDriver use 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 open a new window driver.findElement (By.linkText (`` Open New Window '')) .click (); // Get all window hold Set & lt; String & gt; 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 singular handle (aString).
  • Always store the primary window handle before opening a new one.
  • Use driver.close ()to close the current window anddriver.quit ()to close all.

Why run Window Handling Selenium examination on BrowserStack?

Testing window handling in Selenium across different environments is critical to ensure reliability. Here & # 8217; s why is a strong choice:

  • Cross-Browser Accuracy:Verify that window switching and pop-up handling work systematically across,,, Edge, and more.
  • :Test on real nomadic devices and desktops to reflect actual exploiter environments, not just emulators or virtual machines.
  • Execution:Accelerate examination by running Selenium trial concurrently across multiple browser-OS combinations.
  • Reliable Pop-up Behavior:Pop-up and window behaviour can alter by browser. BrowserStack provides accurate, environment-specific results.
  • Debugging Tools:Access detail logs, screenshots, and session video recordings to quickly identify and fix number in window handling.

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

Read More:

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 technique, you can progress robust and true tryout scripts.

Run your multi-window tryout seamlessly across real browsers and devices with. With BrowserStack, ensure consistent deportment, fast execution, and effortless debugging.

Tags

FAQs

Selenium can just interact with the window it ’ s currently concentre on. If a new tab or popup opens and WebDriver doesn ’ t switch to it, interactions will fail. Using window handles ensures Selenium targets the correct window before performing any action.

You can store the original window ’ s handle using getWindowHandle () and change back to it anytime with driver.switchTo () .window (originalHandle). This is utilitarian when completing project across multiple window in a workflow.

No, Selenium doesn ’ t support switching windows by index directly. You must work with the set of window grip returned by getWindowHandles (), convert it to a tilt if needed, and so switch habituate the corresponding handle.

47,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free