How to Handle Multiple Windows in Selenium

How to Handle Multiple Windows in Selenium?

Last updated on 25th Sep 2020, Artciles, Blog

About author

Vignesh (Sr Technical Project Manager )

He is a TOP-Rated Domain Expert with 11+ Years Of Experience, Also He is a Respective Technical Recruiter for Past 5 Years & Share's this Informative Articles For Freshers

(5.0) | 16477 Ratings 824

Software testing plays a vital role in creating error-free products that offer seamless user experiences. Therefore, it is essential to test the software before putting it into production.

As technology advances, it is necessary to adopt automation testing into the development pipeline. Selenium is the most widely used framework for automated software testing of a website. Every website must be tested by putting it through multiple real-world user scenarios. One such scenario is the handling of multiple windows. This article will discuss how to automate this action with Selenium so that the website’s behavior can be monitored by testers.

Subscribe For Free Demo

Error: Contact form not found.

Selenium

Handling Multiple Windows in Selenium

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. 1. get.windowhandle(): This method helps to get the window handle of the current window
  2. 2. get.windowhandles(): This method helps to get the handles of all the windows opened
  3. 3. set: This method helps to set the window handles in the form of a string.
    • set= driver.get.windowhandles()
  4. 4. switch to: This method helps to switch between the windows
  5. 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

Scenario: Navigate to the xxx 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. 1. Get the handle of the parent window using the command:
    • String parentWindowHandle = driver.getWindowHandle();
  2. 2. Print the window handle of the parent window.
  3. 3. Find the element on the web page using an ID which is an element locator.
  4. 4. Open multiple child windows.
  5. 5. Iterate through child windows.
  6. 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. 7. Use the SwitchTo command to switch to the desired window and also pass the URL of the web page.

Basics of Multiple Window

There is only one way you can get multiple windows via Selenium web driver, that is by clicking on a link that opens the page in a new browser window. Selenium web driver keeps a track of how many windows it opened during a session. This means that it will not keep track of any browser window which is – Opened manually – Opened by a previous session of Selenium Webdriver By session of selenium WebDriver we mean the duration from the time we instantiate a WebDriver instance to the time we kill it via WebDriver.Quit or by manually killing the process. With this understanding lets first open some windows using Selenium WebDriver. To achieve this all we have to do is to click on the button on our practice page. Here is the code for that

  • public static void main(String[] args) throws InterruptedException
  • WebDriver driver = new FirefoxDriver();
  • driver.get(“https://toolsqa.com/automation-practice-switch-windows/”);
  • WebElement clickElement = driver.findElement(By.id(“button1”));
  • for(int i = 0; i < 3; i++)
  • {
  • clickElement.click();
  • Thread.sleep(3000);
  • }
  • }

This will click on the “New Browser Window” button three times. As a result, there will be 4 windows that will come into existence. Keep in mind that the window opened during driver initialization is the Parent window. This is how the windows will look like

Handling-Windows
Course Curriculum

Gain In-Depth Knowledge in Selenium Training from MNC Experts

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

Handle Windows in Selenium Webdriver

To uniquely identify an opened browser Selenium WebDriver keeps a map of Opened windows VS Window Handle. Window handle is a unique string value that uniquely identifies a Browser window on desktop. It is guaranteed that each browser will have a unique window handle. To get Window handle WebDriver interface provides two methods

  1. 1. getWindowHandle()
  2. 2. getWindowHandles()
Selenium-Webdriver

getWindowHandle() method returns a string value and it returns the Window handle of the current focused browser window. getWindowHandles() method returns a set of all Window handles of all the browsers that were opened in the session. In this case it will return 4 windows handles because we have 4 windows open. Here is the code to print out window handles on the console of eclipse.

  • public static void main(String[] args) throws InterruptedException
  • WebDriver driver = new FirefoxDriver();
  • driver.get(“https://toolsqa.com/automation-practice-switch-windows/”);
  • String parentWindowHandle = driver.getWindowHandle();
  • System.out.println(“Parent window’s handle -> ” + parentWindowHandle);
  • WebElement clickElement = driver.findElement(By.id(“button1”));
  • for(int i = 0; i < 3; i++)
  • {
  • clickElement.click();
  • Thread.sleep(3000);
  • }
  • Set<String> allWindowHandles = driver.getWindowHandles();
  • for(String handle : allWindowHandles)
  • {
  • System.out.println(“Window handle – > ” + handle);
  • }

Console Output : This is the output that you will get on console. Pay attention to the Window handle values, they are unique to each other

Console-Output

Handling Multiple Windows in Selenium WebDriver

There is a concept of a current focused window which means that all selenium webdriver commands will go to the focused window. By default the focus is always on the Parent window, please see the screenshot above. In order to shift focus from Parent Window to any child window we have to use the following command on WebDriver –

  • WebDriver.SwitchTo().window(String windowHandle);
This command takes in a window handle and switches the driver context on that window. Once the Switch happens all the driver commands will go to the newly focused window. This is very important to understand, without switching to the desired window we will not be able to perform any action on that window. Now lets see some code which iteratively moves across all the open windows and navigates to a particular page in all the open windows one by one.

  • public static void main(String[] args) throws InterruptedException
  • WebDriver driver = new FirefoxDriver();
  • driver.get(“https://toolsqa.com/automation-practice-switch-windows/”);
  • String parentWindowHandle = driver.getWindowHandle();
  • System.out.println(“Parent window’s handle -> ” + parentWindowHandle);
  • WebElement clickElement = driver.findElement(By.id(“button1”));
  • for(int i = 0; i < 3; i++)
  • {
  • clickElement.click();
  • Thread.sleep(3000);
  • Set<String> allWindowHandles = driver.getWindowHandles(); 
  • for(String handle : allWindowHandles)
  • {
  • System.out.println(“Switching to window – > ” + handle);
  • System.out.println(“Navigating to google.com”);
  • driver.switchTo().window(handle); //Switch to the desired window first and then execute commands using driver
  • driver.get(“https://google.com”);
  • }
  • }

Closing all the Windows

There are basically two commands that we can use to close the opened browser windows.

  1. 1. WebDriver.close()
  2. 2. WebDriver.quit()

WebDriver.Close() command will close the current window on which the focus is present. This can be used to close windows selectively. Just switch to the window that you want to close by using the correct Window handle and the call the WebDriver.close command. That will close the current browser window.

Selenium Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

Note: After closing a window you have to explicitly switch to another valid window before sending in any WebDriver commands. if you fail to do this you will get the following exception.org.openqa.selenium.NoSuchWindowException: Window not found. The browser window may have been closed.

In the code below we will close the parent window and then explicitly move focus to the last window in the list.

  • public static void main(String[] args) throws InterruptedException
  • {
  •  
  • WebDriver driver = new FirefoxDriver();
  • driver.get(“https://toolsqa.com/automation-practice-switch-windows/”);
  • String parentWindowHandle = driver.getWindowHandle();
  • System.out.println(“Parent window’s handle -> ” + parentWindowHandle);
  • WebElement clickElement = driver.findElement(By.id(“button1”));
  •  
  • for(int i = 0; i < 3; i++)
  • {
  • clickElement.click();
  • Thread.sleep(3000);
  • }
  • Set<String> allWindowHandles = driver.getWindowHandles();
  • String lastWindowHandle = “”;
  • for(String handle : allWindowHandles)
  • {
  • System.out.println(“Switching to window – > ” + handle);
  • System.out.println(“Navigating to google.com”);
  • driver.switchTo().window(handle); //Switch to the desired window first and then execute commands using driver
  • driver.get(“https://google.com”);
  • lastWindowHandle = handle;
  • }
  • //Switch to the parent window
  • driver.switchTo().window(parentWindowHandle);
  • //close the parent window
  • driver.close();
  • //at this point there is no focused window, we have to explicitly switch back to some window.
  • driver.switchTo().window(lastWindowHandle);
  • driver.get(“https://toolsqa.com”);
  • }

WebDriver.quit() will close all the windows opened in the session. This command basically shuts down the driver instance and any further commands to WebDriver results in an exception. 

Wrapping it Up!

This is just the end of the beginning! You now know how to handle multiple browser windows in Selenium. Go ahead, and handle the heck out of these browser windows. They might have been a nightmare before, but between you and me, we now know that it’s just a piece of cake! You now know how to handle multiple windows in Selenium. The framework is robust, flexible and provides various inbuilt classes and functions.

Are you looking training with Right Jobs?

Contact Us

Popular Courses