How to handle multiple windows in Selenium?
Last Updated : 06 Jan, 2025
Handling multiple windows in Selenium is crucial when dealing with web applications that open new tabs or windows during interactions. Whether you're testing applications with pop-ups, modals, or new browser tabs, Selenium WebDriver provides efficient methods to switch between multiple windows or tabs.
This functionality allows for comprehensive testing of all parts of a web application, ensuring that the user experience remains seamless across different browser contexts..
What is a Window Handle?
It is used to contain the address of all the windows. Consider it as a pointer to a window that yields a value in string data type. The handle for the window will be unique for each browser. The existence meaning for this function of the window retrieves all window handles.
Syntax
- get.windowhandle(): It is used to return the handle of the currently active window.
- get.windowhandles() : This method is used to get the handle of all opened windows.
- set: It will set the window handles in the form of string. set<string> set= driver.get.windowhandles();
- switch to: This function is used to switch between the windows.
- action: This methods helps to do actions to windows.
Handling Multiple Windows in Selenium using Window Handles
Handling multiple windows in Selenium is done using window handles. One navigates between several browser tabs or windows. Here's how:
- Open New Window/Tabs: When a link or button is clicked, execute actions that will open any window or tab.
- Get current window handle: Save the handle of the current window so that you can switch back. You can do this by calling driver.getWindowHandle().
- Get All Window Handles: It returns a set of handles of all opened windows or tabs using the driver.getWindowHandles().
- New Window: This will loop through all window handles identifying which handle is not the current handle. It then switches to that window by using driver.switchTo().window(handle).
- Perform actions: Upon change, perform actions in the new window or tab as required.
- Close Window: Closes currently active window if needed using driver.close().
- Switch Back: Your saved handle is to be used for switching back to the original window.
Steps to handle multiple windows in Selenium
- Visit the official site of geeksforgeeks.org
- Click on courses at GeeksforGeeks from quick links
- Select a particular course ( Open with a new window )
- Click on the element of the new window
Expected Result: It should click on the element of the new window
Implementation
Program 1: Click on the element of the new window without shifting the focus of selenium
Java import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class GFGWindowHandling { public static void main(String[] args) throws InterruptedException { // we are using chrome driver System.setProperty("webdriver.chrome.driver", "Path of chromedriver.exe"); WebDriver driver = new ChromeDriver(); // entering the URL driver.get("https:// www.geeksforgeeks.org/"); // to maximize the window driver.manage().window().maximize(); // to delete all cookies driver.manage().deleteAllCookies(); // to Scroll the screen to locate element JavascriptExecutor je = (JavascriptExecutor)driver; je.executeScript("window.scrollBy(0, 200)"); driver.findElement(By.xpath("(// span[text()='Courses at GeeksforGeeks'])[2]")).click(); // to select a particular course Thread.sleep(2000); driver.findElement(By.xpath("(// h4[text()='Data Structures and Algorithms - Self Paced'])[1]")).click(); // it will open with new tab // to click on (Read more here) on new window driver.findElement(By.xpath("(// a[text()='(Read more here)'])[1]")).click(); // statement to understand that operation is performed on new window System.out.println("operation is performed on new window"); } }
Console Output:
outputorg.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath", "selector":"(//a[text 1="more" 2="here)'" language="()='(Read"][/text])[1]"}
This exception is because when we click on a particular course new window (child window) is open and when we try to click on Read more here, at that time focus of selenium is on the main window (parent window). So we will use some method to shift the focus of selenium from one window to another.
Syntax:
driver.switchTo().window(ID);
Where ID: ID of a particular window on which you need the change the focus of selenium.
To get the ID of Windows we will use the following method.
- driver.getWindowHandle(): To get the ID of the parent window (main window)
- driver.getWindowHandles(): To get the ID of child windows (new window)
Let's observe how the IDs of two different windows are different,
Program 2: To get the IDs of different windows
Java import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class GFGIDsOfWindows { public static void main(String[] args) throws InterruptedException { // we are using chrome driver System.setProperty("webdriver.chrome.driver", "Path of chromedriver.exe"); WebDriver driver = new ChromeDriver(); // entering the URL driver.get("https:// www.geeksforgeeks.org/"); // to maximize the window driver.manage().window().maximize(); // to delete all cookies driver.manage().deleteAllCookies(); // to Scroll the screen to locate element JavascriptExecutor je = (JavascriptExecutor)driver; je.executeScript("window.scrollBy(0, 200)"); driver.findElement(By.xpath("(// span[text()='Courses at GeeksforGeeks'])[2]")).click(); // to select a particular course Thread.sleep(2000); driver.findElement(By.xpath("(// h4[text()='Data Structures and Algorithms - Self Paced'])[1]")).click(); // it will open with new tab // getWindowHandle method to get ID of main window(parent window) String Parent_id = driver.getWindowHandle(); System.out.println(Parent_id); // getWindowHandle method to get ID of new window (child window) Set<String> Child_id = driver.getWindowHandles(); // for each loop for (String a : Child_id) { // it will print IDs of both window System.out.println(a); } } }
Console Output:

Here you can observe the IDs of windows are different.
CDwindow-EA925E71098EEFBB80858BE787CED1A5 (ID of main window)
CDwindow-C9078346729F1D0CF8AF12E938CE49DD (ID of new window)
So to change the focus of selenium from one window to another window we will use For each loop and provide the if-else condition. For each loop
for( Datatype variable : collection )
{
Statements;
}
Program 3: Click on the element of the new window by shifting the focus of selenium
Java import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class GFGWindowHandlingEx { public static void main(String[] args) throws InterruptedException { // we are using chrome driver System.setProperty("webdriver.chrome.driver", "Path of chromedriver.exe"); WebDriver driver = new ChromeDriver(); // entering the URL driver.get("https:// www.geeksforgeeks.org/"); // to maximize the window driver.manage().window().maximize(); // to delete all cookies driver.manage().deleteAllCookies(); // to Scroll the screen to locate element JavascriptExecutor je = (JavascriptExecutor)driver; je.executeScript("window.scrollBy(0, 200)"); driver.findElement(By.xpath("(// span[text()='Courses at GeeksforGeeks'])[2]")).click(); // to select a particular course Thread.sleep(2000); driver.findElement(By.xpath("(// h4[text()='Data Structures and Algorithms - Self Paced'])[1]")).click(); // it will open with new tab // getWindowHandle method to get ID of main window(parent window) String Parent_id = driver.getWindowHandle(); System.out.println(Parent_id); // getWindowHandle method to get ID of new window (child window) Set<String> Child_id = driver.getWindowHandles(); // for each loop for (String a : Child_id) { // it will print IDs of both window System.out.println(a); // condition to change the focus of selenium if (Parent_id.equals(a)) { } else { // to change focus on new window driver.switchTo().window(a); Thread.sleep(2000); // to handle the popup regarding cookies driver.findElement(By.xpath("// button[text()='Got it!']")).click(); // to click on (Read more here) je.executeScript("window.scrollBy(0, 600)"); driver.findElement(By.xpath("(// a[text()='(Read more here)'])[1]")).click(); // statement to understand that operation is performed on new window System.out.println("operation is performed on new window"); } } } }
Console Output:

Output Video
Conclusion
Effectively managing multiple windows in Selenium ensures that your automated tests can interact with all parts of your web application, including new tabs and pop-ups. By utilizing Selenium's built-in capabilities to switch between different windows or tabs, you can create robust and reliable test cases that cover a broader range of user interactions. This approach not only improves the accuracy of your tests but also helps in verifying the complete functionality of your web application in various scenarios
Similar Reads
How to Handle iframe in Selenium with Java?
In this article, we are going to discuss how to handle the iframe in Selenium with Java. The following 6 points will be discussed. Table of Content What are iframes in Selenium?Difference between frame and iframe in SeleniumSteps to Identify a Frame on a Page?How to Switch Over the Elements in ifram
11 min read
How to Handle Alert in Selenium using Java?
Imagine filling out a form online and accidentally missing some information. You only know if you made a mistake if the website tells you somehow, like with a pop-up message. This article explains what those pop-up messages are called in Selenium (alerts) and how to deal with them in your automated
6 min read
How to handle alert prompts in Selenium Python ?
Seleniumâs Python Module is built to perform automated testing with Python. Alerts are a way to show popups in the browser for either accepting data or displaying data. Selenium provides methods to handle alerts of all kinds. Seleniumâs Python Module is built to perform automated testing with Python
2 min read
How to Scroll an Element into View in Selenium?
A high-level programming language that helps users in building web applications is called Java. It is not only used for creating web applications but it can also be used for automating web applications through various automation tools. Selenium is one such tool, which gives users the capability to a
4 min read
How to use close() and quit() method in Selenium Python ?
While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the drive
2 min read
How to handle Frames/iFrames in Selenium with Python
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python. HTML outlines are utilized to isolate yo
2 min read
How to scrape multiple pages using Selenium in Python?
As we know, selenium is a web-based automation tool that helps us to automate browsers. Selenium is an Open-Source testing tool which means we can easily download it from the internet and use it. With the help of Selenium, we can also scrap the data from the webpages. Here, In this article, we are g
4 min read
How to save and load cookies in Selenium using Python
In web automation and testing, maintaining session information across different runs of scripts is often necessary. Cookies are a great way to save session data to avoid logging in repeatedly. Selenium, a popular tool for web testing, provides straightforward ways to save and load cookies using Pyth
4 min read
minimize_window driver method - Selenium Python
Seleniumâs Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout â Navigating links using get method â Selenium Python. Just bein
2 min read
set_window_position driver method - Selenium Python
Seleniumâs Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout â Navigating links using get method â Selenium Python. Just bein
2 min read