Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource
Table of Contents

How to Handle Multiple Windows in Selenium WebDriver

If you have used Selenium WebDriver, you’ll be familiar with this portable tool which allows you to navigate through multiple windows. It is an extremely popular open-source web framework that enables you to automate web applications and websites. Novice Selenium users will often find themselves in a situation where multiple pages open when they click a button. This might leave you confused about How to Handle Multiple Windows in Selenium. 

To properly access, switch and close its windows, Selenium requires test scripts written in languages like Python, C# or Java. This variety of languages has made Selenium extremely popular among a large group of people and subsequently enhanced its market share. If you are also curious about handling Multiple Windows in Selenium, don't worry about it. In this blog, you will learn How to Handle Multiple Windows in Selenium WebDriver. Read below to learn further!

Table of Contents

1) What is a Window in Selenium WebDriver? 

2) Requirements for windows handling 

3) How to Handle Multiple Windows in Selenium? 

4) Closing all Windows in Selenium   

5) Different methods to Handle Windows in Selenium 

6) Conclusion 

What is a Window in Selenium WebDriver?  

Before we proceed with Window Handling in Selenium, let's take the time to understand some basic Selenium terminologies. Starting with windows, it is the webpage you get directed to once you click on a URL while surfing through a web page or application. A window is generally categorised into two categories in Selenium. A Parent Window and a Child Window.  

If you are using Selenium WebDriver to navigate through a URL, the main page which opens is referred to as a “Parent Window” or simply the main window. When you run an automation script, this Parent Window opens during the script’s execution. The Parent page will have elements like a new tab and new windows allowing us to open new web pages within it. These new web pages that open within the Main or Parent Window are referred to as Child Windows.  

A Child Window is categorised as any webpage that opens within the main page and can be opened with the “New Window” button. A Parent Window allows you to open single or multiple such Child Windows within it. These new Child pages are also referred to as “New Window” in Selenium. 

For example, if you were to open The Knowledge Academy’s homepage, the page you will be guided to is your Parent Window. This webpage contains various elements and buttons that allow you to interact with them. If you were to click on one of the following buttons, such as “PMP”, it will contain a URL which guides you to another web page. This makes any of these new web pages a Child Window, although not every Child page has a URL. 
 

Selenium Training


What is a Window Handle? 

To navigate through windows in Selenium, we need to direct a WebDriver to them properly. This is accomplished with the help of a window’s handle, which is essentially a name or label which is used to identify it and distinguish it from other windows. This makes a page handle an identifier for its respective pages, where each of them holds an address for its window. These addresses are alphanumeric in nature, which enables them to act as pointers.   

Since each browser has a different handle value, we can retrieve these values using handle functions. The retrieved value of the Window can be then run through a test script, directing you to that specific page. This test script allows you to move from one page to another, switching through the windows. This is done by changing the focus of the WebDriver you are currently using. 

Try our course in Introduction To Test Automation With Selenium Web Driver today! 

Requirements for Handling Windows 

Handling a window in Selenium requires certain prerequisites that you should keep in mind. Your experience with Selenium WebDriver is influenced by various factors, some of which are listed below:

Criteria for Managing Windows 

Programming Language: Your proficiency in Window Handling in Selenium WebDriver largely depends on the programming language you choose.  

Programming languages act as a medium to run test scripts on Selenium. In this blog, Java is used as the programming language to run test scripts. Java is a popular choice for Selenium test scripts due to its versatility, robustness, and speed. 

To use Java, you need to install Java Runtime Environment (JRE). However, you are free to choose any other programming language that suits your needs, such as Python, PHP, JavaScript, Perl, Ruby, or C#. Selenium supports various languages, allowing you the freedom to choose. 

Platform: Once you have chosen a programming language, you need an Integrated Development Environment (IDE) to write your code. There are several IDE options to run Java programs, such as Visual Basic Code, Eclipse, NetBeans, IntelliJ, and Spring Tool Suit (STS). Similarly, you can use different IDEs for different programming languages in Selenium. Note that some IDEs allow you to run multiple languages. 

Driver: Finally, you need drivers based on the browser you are using. For example, if you are using Google Chrome, you need to install Chrome Driver. You also need plug-ins for Selenium, such as Selenium Standalone Server, and IDE for Selenium and Selenium Jar files to navigate windows. You can do this by running a test script for Selenium that allows you to switch the focus of pages. 

Don’t wish to use Selenium in Python? Try our Selenium WebDriver With Python Training today! 

Reasons to Handle Multiple Windows in Selenium  

Selenium WebDriver allows you to open Child Windows within a Parent Window, which raises its own set of concerns. There is a possibility that multiple new pages might open inside your main page when you click on a button. Since the Selenium Web Driver works with only specific contexts, this can become a hindrance to the proper functioning of Selenium. This happens because each Child Window opened inside the Parent Window has its own specific context.  

If the focus of the Selenium WebDriver has not switched to a different window, any test script run will lead to an exception. This happens because each Child or New Window that opens within the Parent Page will have its own unique context. To avoid such an issue, we need to direct the WebDriver accordingly to the New Window, allowing you to automate those pages properly. 

How to Handle Multiple Windows in Selenium?  

By this point, you must be well aware of how the Selenium WebDriver works. It allows you to open and access many windows within a Parent Window. However, the presence of many windows demands proper handling, allowing you to switch from one window to another if needed. Let’s assume you have landed on the main page of a website. Here is a general set of steps on How to Handle Multiple Windows in Selenium using test scripts written in Java:    

Step 1: Use the command String parentWindowHandle = driver.getWindowHandle(); to get the Parent Window’s handle. 

Step 2: Once the Parent Window’s handle is retrieved, print it. 

Step 3: Use the element locator to find the element within the web page. 

Step 4: Open multiple Child Windows within the Parent Window. 

Step 5: Iterate through the Child Windows.  

Step 6: Use the command Set allWindowHandles = driver.getWindowHandles(); to retrieve handles of all currently open windows. 

Step 7: Lastly, use command switchTo to switch to the preferred window. 

Ideally, a test script in Java which focuses on switching the context will follow certain steps. It will be included in documenting your current window handle and opening a Child Window by clicking on a button.  

You will need to retrieve all the handles, using the getWindowHandles(); syntax. Once you have handles of Child Windows, you can use the switchTo() syntax to change the current focus of the WebDriver. Failure to switch the context would result in an exception stating the absence of an element. The Java program here demonstrates the proper method of Handling Multiple Windows in Selenium and switching to Child Windows with a test script. 
 

//A program demonstrating How to Handle Multiple Windows in Selenium
//This line retrieves current window handle for you in Selenium
String parentWindowHandle = driver.getWindowHandle();
//This line clicks on the button, opening the Child Page
driver.findElement(By.linkText("Open Child Window")).click();
// method to get handle of all windows in Selenium session
Set allWindowHandles = driver.getWindowHandles();
//This function allows you to switch to the Child Page via handle
for (String windowHandle : allWindowHandles)
  {
    if (!windowHandle.equals(parentWindowHandle))
     {
       driver.switchTo().window(windowHandle);
    }
}
// This line retrieves the text from the Child Window
String childWindowText = driver.findElement(By.tagName("body")).getText();
// This line prints the text from the Child Window
System.out.println("Text from child window: " + childWindowText);
// This line switches focus back to Parent window
driver.switchTo().window(parentWindowHandle);

 

Single Child Window handling in Selenium  

Selenium allows for creation of both a single Child Window and multiple Child Windows within a Parent Window. Here is a Java code that will allow you to run a test script to handle a single Child Window. You’ll need to import certain libraries to perform this code including, Selenium Webdriver and ChromeDriver (if using Chrome browser). 

Additionally, you might need to import more libraries such as WebElement in your program. The syntax to do so is import org.openqa.selenium.WebElement; which allows you to locate elements and retrieve attribute properties. This blog’s code only utilises the driver with the syntax import org.openqa.selenium.chrome.ChromeDriver;  which allows WebDriver to access the following windows. 

You can set the path of the ChromeDriver by using the System.setProperty() method. Then, you’ll need to create a new instance of ChromeDriver allowing you to navigate to your preferred URL using the driver.get() method. Lastly, you’ll need to close the browser window using the quit() method to avoid testing failure and memory leaks in future, all while understanding the role of System setProperty in Selenium.

Selenium allows for creation of both a single Child Window and multiple Child Windows within a Parent Window. Here is a Java code that will allow you to run a test script to handle a single Child Window:import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ChildWindowExample
  {
     public static void main(String[] args)
{

   System.setProperty("webdriver.chrome.driver",
   "path/to/chromedriver.exe");
   WebDriver driver = new ChromeDriver();
   driver.get("https://www.example.com");
   String parentWindowHandle = driver.getWindowHandle();
   // Click on a link that opens a new page in Selenium
   driver.findElement(By.linkText("Open New Window")).click();
   // Get all handle of all pages
   Set windowHandles = driver.getWindowHandles();
   // Loop through handle of all pages
   for (String handle : windowHandles)
     {
       // Check if the handle is not the parent window handle
      if (!handle.equals(parentWindowHandle))
       {
         // Switch to the Child Page
        driver.switchTo().window(handle);
        // Perform actions on the Child page
        // ...
       // Close the Child page
       driver.close();
      }
  }
    // Switch back to the parent page
    driver.switchTo().window(parentWindowHandle);
    // Perform actions on the parent page
    // ...
    // Quit the driver
    driver.quit();
   }
}

 

You’ll need to import certain libraries to perform this code including, Selenium Webdriver and ChromeDriver (if using Chrome browser). Additionally, you might need to import more libraries such as WebElement in your program.

The syntax to do so is import org.openqa.selenium.WebElement; which allows you to locate elements and retrieve attribute properties. This blog’s code only utilises the driver with the syntax import org.openqa.selenium.chrome.ChromeDriver;  which allows WebDriver to access the following windows. 

You can set the path of the ChromeDriver by using the System.setProperty() method. Then, you’ll need to create a new instance of ChromeDriver allowing you to navigate to your preferred URL using the driver.get() method. Lastly, you’ll need to close the browser window using the quit() method to avoid testing failure and memory leaks in future.

Multiple Child Window handling in Selenium

This method will also require you to set the path of the ChromeDriver executable using the System.setProperty() method. This is quite similar to handling a single Child Window in Selenium. Then, you’ll need to create a new instance of ChromeDriver and navigate to the Parent Window.  

Next, you can get the handles of all open windows using the getWindowHandles() method and loop through each window. This is different from getWindowHandle() function which is used to retrieve value of only a single page. You can switch to the window using the switchTo() method and print the handles in the console. Finally, you can close all windows using the quit() method.  
 

import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ChildWindowExample
   {
      public static void main(String[] args)
   {
       System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
       WebDriver driver = new ChromeDriver();
       driver.get("https://www.example.com");
       String parentWindowHandle = driver.getWindowHandle();
       // Click on a link that opens a new page in Selenium
       driver.findElement(By.linkText("Open Multiple New Windows")).click();
       // Get handle of all pages
       Set windowHandles = driver.getWindowHandles();
       // Loop through all the handles
       for (String handle : windowHandles)
         {
           // Check if the handle is not the Parent Window handle
            if (!handle.equals(parentWindowHandle))
              {
                 // Switch to the child window via the handle
                driver.switchTo().window(handle);
                // Perform actions on the Child Window
                 // ...
                // Close the Child page
              driver.close();
          }
      }
     // Switch back to the parent page via its handle
     driver.switchTo().window(parentWindowHandle);
     // Perform actions on the parent window
    // ...
    // Quit the driver
    driver.quit();
   }
}


Gain knowledge of importing Selenium libraries with Selenium Testing Framework Training!

Closing all Windows in Selenium 

Selenium WebDriver is a context-focused framework. It means that if you have a currently open window in use, it needs to be closed before switching to another window. For example, if you were to switch to a previous page in Selenium without closing the current one. This would lead to several problems, such as Selenium mistaking your current window’s context with an unclosed one.  

Moreover, if you didn’t close all windows at the end of your process, it could burden your system. Failure at Handling Multiple Pages in Selenium correctly could cause problems later because the Selenium WebDriver will keep consuming your power. This can lead to a potential crash. Further, the crash could result from the continued drain in processing power or a collective memory leak. 

Since the Selenium WebDriver allows you the usage of multiple pages, it can be challenging to manage them all together. Closing more than one Child Window in Selenium is no exception to this. Spending time closing Multiple Windows in Selenium one at a time is not only comical but also unnecessarily time-consuming. Fortunately, closing Multiple Windows simultaneously in Selenium is rather easy.  

There are two methods to close different windows in Selenium at once. The driver.close(); method is used to close a selective page out of all open windows. However, if only one window is running at that moment, it would end the WebDriver session entirely. The code snippet using this function is as follows:
 

// Handling Multiple Windows in Selenium and closing them
// This part launches the WebDriver in Selenium
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// This opens a new page for you in Selenium
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open('https://www.google.com','_blank');");
Thread.sleep(2000); // Wait for 2 seconds for the new window to open
// This will let you switch to the new page in Selenium with handle
String newWindowTitle = "Google";
for (String windowHandle : driver.getWindowHandles())
    {
       driver.switchTo().window(windowHandle);
       if (driver.getTitle().equals(newWindowTitle))
   {
     break;
   }
}
// Using the close function to close the page
driver.close();
// Switching back to original page with the handle
driver.switchTo().window(driver.getWindowHandles().iterator().next());
// Closing the original page as well
driver.close();


Meanwhile, driver.quit(); method allows you to close every window opened in a particular session. The quit function also ceases the browser process and the background driver process. This would mean that if any other function was used once Driver has stopped, it will throw an exception. It will also notify Selenium Grid that the browser is no longer in use so it can be used by another session. The Java program using the quit function in Selenium will be as follows: 
 

// Handling Multiple Windows in Selenium and quitting them
// This will launch browser in Selenium and navigate to a webpage
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
// Open a new page in Selenium and navigate to a webpage
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.open('https://www.google.com','_blank');");
Thread.sleep(2000); // Wait for 2 seconds for the new window to open
// Get a set of every handle in Selenium session
Set windowHandles = driver.getWindowHandles();
// Iterate through the handle set and close each page
for (String windowHandle : windowHandles)
  {
    driver.switchTo().window(windowHandle);
    driver.close();
 }
// Quit the driver
driver.quit();


Different methods to Handle Windows in Selenium  

Handling multiple windows in Selenium WebDriver is extremely easy due to the handling methods available. These methods consist of functions and syntaxes that vary with the programming language of your test scripts. You will find these syntaxes commonly used within this blog, and they will be of great help to you in the future. When considering Selenium vs Cucumber, Selenium offers direct methods for window handling, which are often utilized in Java test scripts. Here are some such common window-handling functions for Selenium test scripts used in Java:

1) getWindowHandle(): This method is used to get the ID of the Parent Window (main page). It retrieves the unique id of the current window, which is identified within the driver instance. The value returned by this method is a String type. 

2) getWindowHandles(): This method is used to obtain the ID of all the currently opened windows with the WebDriver. These are Child Windows and are stored in a Set of String type.  

3) switchTo(): We can perform a switch operation within a window using this syntax. This syntax enables you to switch between different pages. 

4) action: This syntax is used to perform certain actions within the windows. 

5) set: This syntax allows you to set windows that are in string form.  

Conclusion 

Selenium WebDriver is a platform for quality analysis automation using programming languages such as Java. Hopefully, this blog help you in understanding How to Handle Multiple Windows in Selenium, the concept of Parent Windows, Child Windows, running a test script to retrieve their handles and switching the Windows respectively. Additionally, referring to a Selenium PDF can provide structured guidance and deeper insights into mastering Selenium WebDriver effectively. 

Elevate your automation skills and drive your career forward with our Selenium Immersion with C# Course – join us now!

Frequently Asked Questions

How do I handle multiple browser windows?

faq-arrow

To manage multiple browser windows, you can utilise window handles. First, you must capture handles for each window. Later, you can switch between them using `driver.switch_to.window(handle)`, and perform actions as needed.

How to handle multiple sessions in Selenium?

faq-arrow

In Selenium, handling multiple sessions requires certain crucial steps. Here are those steps:

a) Open the Main Window

b) Trigger Action for New Window

c) Capture Window Handles

d) Switch to New Window

e) Perform Stuff in the New Window

f) Switch Back to the New Window

g) Continue Testing on Main Window

h) Repeat the process as per requirements

i) Close the current Window
 

What are the other resources and offers provided by The Knowledge Academy?

faq-arrow

The Knowledge Academy takes global learning to new heights, offering over 3,000 online courses across 490+ locations in 190+ countries. This expansive reach ensures accessibility and convenience for learners worldwide.   

Alongside our diverse Online Course Catalogue, encompassing 19 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.

What is the Knowledge Pass, and how does it work?

faq-arrow

The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.

What are related courses and blogs provided by The Knowledge Academy?

faq-arrow

The Knowledge Academy offers various Selenium Trainings, including the Selenium Testing Framework Training, Selenium WebDriver with Python Training, and Selenium Immersion with C## Training. These courses cater to different skill levels, providing comprehensive insights into How to Refresh Browser Pages in Selenium.

Our Programming & DevOps Blogs cover a range of topics related to Selenium, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Programming and DevOps skills, The Knowledge Academy's diverse courses and informative blogs have got you covered.
 

Upcoming Programming & DevOps Resources Batches & Dates

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross
Unlock up to 40% off today!

Get Your Discount Codes Now and Enjoy Great Savings

WHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.