How to handle multiple windows in Selenium? Step-by-Step

Last updated on : Nov 29, 2023 by Shubham Srivastava

In this Selenium guide, we will understand – How to handle multiple windows in Selenium? You might have face multiple situations, when clicking a link or button, a pop-up window gets open Or, a new browser window gets open in same browser. To deal with multiple windows and tabs in Selenium, let’s see what Selenium methods we can use in our automation scripts.

Let’s get started –

Handle multiple windows in Selenium

How to handle multiple windows in Selenium [Solution 1]

From Selenium version 3, we have multiple methods available to handle multiple browser windows and tabs related test scenarios. The available methods are below –

1) driver.getWindowHandle() :

This method helps to get a handle (Unique Access ID) to identify current browser window that uniquely identifies it within current driver instance. This can be used to switch to this window at later steps.

Syntax :

public String getWindowHandle()

2) driver.getWindowHandles() :

This method helps to get a Set of handles (Unique Access IDs) to identify all currently opened browser windows within current driver instance. This method can be used to switch to any browser window at later steps.

Syntax :

public java.util.Set<String> getWindowHandles()

Example 1

Let’s see a simple example. Here is a Selenium and Java based program designed to handle multiple browser windows –

/******************************************************************************

                            LogicalDuniya.com
         Program on - How to handle multiple browser windows in Selenium?
       Copy this program, and run using Java 8 or above to get the results. 

*******************************************************************************/

import org.openqa.selenium.WebDriver;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class MultipleWindowsHandleTest {

    public static void main(String[] args) {


        // Setup of WebDriver -
        System.setProperty("webdriver.chrome.driver", "path_to_chromedriver_in_your_computer");
		WebDriver driver = new ChromeDriver();
        


        // 1st approach - To handle windows :
        // Getting all opened browser windows IDs in Set object-
        Set<String> windowsSet = driver.getWindowHandles();
        
        // Getting iterator to access Set values-
        Iterator it = windowsSet.iterator();
        
        // Switching to latest window handle-
        driver.switchTo().window( it.next().toString() );

        // Perform any action on the new switched window-
        


        // 2nd approach - To handle windows :
        // Getting all opened browser windows IDs in List Object-
        List<String> windowsList = new ArrayList<String>(driver.getWindowHandles());
        
        // Switching to latest window handle-
        driver.switchTo().window( windowsList.get( windowsList.size()-1 ));

        // Perform any action on the new switched window-
    }
}

Explanation : Step by Step

Let’s understand, what have we done in above programming example of Handling multiple windows using Window handles in Selenium

Step 1: First do the WebDriver Setup:

  • The program starts by setting up the WebDriver.
  • It uses ChromeDriver, and the path to the ChromeDriver executable needs to be provided.

Step 2: The 1st Approach is to work with Set and Iterator:

  • getWindowHandles() retrieves a set of window handles (unique identifiers) for all open browser windows.
  • An iterator (it) is created to iterate over the set.
  • switchTo().window() is used to switch to the latest window by getting the next window handle from the iterator.

Step 3: The 2nd Approach is to use List :

  • An alternative approach is to use a List<String> to store window handles.
  • The getWindowHandles() set is converted to a list (windowsList).
  • switchTo().window() is used to switch to the latest window by getting the handle from the end of the list.

In both approaches, the code switches to the latest window handle, which is often the newly opened window. This is useful when dealing with pop-ups or scenarios where a new window is launched during the execution of the script.


How to handle multiple windows in Selenium [Solution 2]

While working with windows and tabs selenium java, we can also use a latest feature available from Selenium version 4. Now, we have brand new methods available to handle multiple browser windows and tabs. The available methods are below –

1) newWindow(WindowType.TAB) :

This is an abstract method, which is used to open a new tab in the browser. This method will be called to create a new browser tab and automatically switches the focus for future commands of current driver to the new tab.

Syntax :

public abstract WebDriver newWindow(  org.openqa.selenium.WindowType )

2) newWindow(WindowType.WINDOW) :

This is the same abstract method that we explained previously, but to open a new browser window, just we need to change the parameter value to WindowType.WINDOW . This method will be called to create a new browser window and automatically switches the focus for future commands of current driver to the new browser window.

Syntax :

public abstract WebDriver newWindow(  org.openqa.selenium.WindowType )

Example 2

Let’s see an example to understand the above newWindow() method in depth and step by step –

/******************************************************************************

                            LogicalDuniya.com
           Program to handle multiple browser windows using Selenium 4?
       Copy this program, and run using Java 8 or above to get the results. 

*******************************************************************************/

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;

public class NewWindowExample {

    public static void main(String[] args) {
        // Step 1 : Set the path to the ChromeDriver executable
        System.setProperty("webdriver.chrome.driver", "path_to_chromedriver_in_your_computer");

        // Create a new instance of the ChromeDriver
        WebDriver driver = new ChromeDriver();

        // Step 2 : Navigate to a website
        driver.get("https://www.logicalduniya.com");

        // Step 3 : Open a new tab
        driver.switchTo().newWindow(WindowType.TAB);

        // Step 4 : Navigate to another website in the new tab
        driver.get("https://www.google.com");

        // Open a new window
        driver.switchTo().newWindow(WindowType.WINDOW);

        // Navigate to a different website in the new window
        driver.get("https://www.selenium.dev");

        // Step 5 : Perform any other actions if needed...

        // Close the browser
        driver.quit();
    }
}

Explanation : Step by Step

Let’s understand, what have we done in above programming example of Handling multiple windows using Window handles in Selenium β€“

Step 1: First do the WebDriver Setup

  • The program starts by setting up the WebDriver.
  • It uses ChromeDriver, and the path to the ChromeDriver executable needs to be provided.

Step 2: Navigation

Step 3: New Tab

  • switchTo().newWindow(WindowType.TAB) is used to open a new tab.
  • It then navigates to a different website in the new tab (in this case, “https://www.google.com“).

Step 4: New Window

  • switchTo().newWindow(WindowType.WINDOW) is used to open a new browser window.
  • It navigates to yet another website in the new window (in this case, “https://www.selenium.dev“).

Step 5 :

  • Any other actions can be performed in each tab or window if needed.

Final Step : Browser Closure

  • Finally, the driver.quit() method is used to close the browser.

NOTE πŸ’‘
In above code snippet of newWindow() method, the parameter WindowType is of type Enum . Switching to browser tab / window is a Most Common Selenium Interview Question. Check more interview questions using this link . . .

Conclusion

In this in depth and step by step solution on – How to handle multiple windows in Selenium? We have successfully learnt about 4 different approaches browser window / tabs management in above 2 examples. We have understood the usage of getWindowHandle() and getWindowHandles()methods. Also, we have learnt about the newly introduced driver.switchTo().newWindow() method of Selenium 4.

If you have any query or suggestions, feel free to comment below, and I will try my best to answer you doubts within 24 hours. You will learn so many concepts of Manual and Automation Testing along with Latest Interview Questions and Answers, So I’ll recommend to Bookmark the LogicalDuniya.com in your favourite browser.

Next Read This –

Shubham

Shubham Srivastava

Hey there, my name is Shubham and I'm working as an SDET at a US based FinTech company. I've more than 7 years of working experience and using my knowledge - I want make this platform super helpful for those, who want to solve any software development and testing related problems. Comment your query / request or suggestion in the below section, and I'll try to respond within 24 hours. Keep improving, Keep coding !!

Recommended Posts :


4.5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Press ESC to close