How to Handle Multiple Windows in Selenium using Java?


When working with Selenium and Java, it is crucial to know how to handle multiple windows effectively. Managing multiple windows in Selenium involves navigating between different browser windows or pop-ups during test automation. It allows for interaction with various elements and validating functionality across different windows.

Proper handling of multiple windows ensures comprehensive testing coverage and accurate results. By leveraging Selenium's WebDriver interface and Java, you can retrieve window handles, switch between windows, perform operations on specific windows, and automate complex scenarios that involve multiple browser windows. Mastering this skill enhances the efficiency and reliability of your Selenium test automation scripts.

Selenium

Selenium is an open source automation framework that is widely used for testing web applications. It simplifies browser interactions, user action simulations and functional tests by providing a range of libraries and tools. Additionally, Selenium supports various programming languages including Java, making it a popular choice among developers globally.

WebDriver driver = new ChromeDriver();

Approaches

When dealing with multiple windows in Selenium using Java, there are a variety of methods and techniques available. This tutorial includes different examples to help readers comprehend how to handle multiple windows effectively.

  • Using getWindowHandles()

  • Using switchTo().window(handle)

  • Using quit()

Approach 1: Using getWindowHandles()

When working with multiple windows in Selenium using Java, there's a useful method called `getWindowHandles()`. This method returns all currently open window handles as a set. By storing them in this way, users can easily switch between different windows whenever nece-ssary. To use the method, start by obtaining the current window handle using `getWindowHandle()`. After performing an action that opens a new window, retrieve all handles using `getWindowHandles()` to continue switching between them.

To efficiently handle multiple windows during automated testing, one can iterate through the set and use the `switchTo().window()` method while passing the desired handle as a parameter. This lets us interact with specific windows in Selenium and Java, making testing more effective.

Algorithm

  • The method to get the current window's handle is through getWindowHandle() function. This handle can then be stored in a variable for further use.

  • Retrieve all the window handles using the getWindowHandles() method and store them in a set.

  • Iterate through the set of window handles using a loop.

  • To switch to a specific window inside the loop, one can utilize the switchTo().window() method and include the corresponding handle as an input parameter.

  • Perform the required operations or actions on the new window.

Example

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

import java.util.Set;

public class MultipleWindowsExample {

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

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

      // Navigate to the webpage with multiple windows
      driver.get("https://www.tutorialspoint.com");

      // Perform an action that opens a new window, such as clicking a link
      driver.findElement(By.linkText("Open New Window")).click();

      // Get all window handles
      Set<String> windowHandles = driver.getWindowHandles();

      // Iterate through each window handle
      for (String windowHandle : windowHandles) {
         // Switch to the desired window
         driver.switchTo().window(windowHandle);
         // Perform actions on the window
         System.out.println("Title of the window: " + driver.getTitle());
      }

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

Output

Title of the window: Online Courses and eBooks Library
Title of the window: New Window

Approach 2: Using switchTo().window(handle)

When working with multiple windows in Selenium by means of Java, the `switchTo().window(handle)` method is fundamental. First, we retrieve the window handles through `getWindowHandles()`. From there, iterating through each handle and applying this technique allows us to execute various actions and interact with specific elements that belong to a particular window. Passing on the relevant window handle as a parameter switches the context of the driver; thus, executing an action just where it is needed.

Algorithm

  • To initiate the opening of a new window, one must first identify the trigger action or event such as clicking on a link or button.

  • To retrieve the window handles, utilize the getWindowHandles() method. This method retrieves all open windows and returns them as a set.

  • While inside the loop, one can smoothly switch to each available window by utilizing the `switchTo().window(handle)` method. To clarify, "handle" in this context refers to

  • The code may require switching back to the original window by using switchTo().window(originalHandle) before moving on to the next iteration.

Example

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

import java.util.Set;

public class MultipleWindowsExample {

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

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

      // Navigate to the main window
      driver.get("https://www.tutorialspoint.com");

      // Perform an action that opens a new window, such as clicking a link
      driver.findElement(By.linkText("Open New Window")).click();

      // Get all window handles
      Set<String> windowHandles = driver.getWindowHandles();

      // Switch to the new window
      for (String windowHandle : windowHandles) {
         driver.switchTo().window(windowHandle);
         // Check if the window title matches the new window
         if (driver.getTitle().equals("New Window Title")) {
            // Perform actions on the new window
            System.out.println("Title of the new window: " + driver.getTitle());
            break;
         }
      }

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

Output

Title of the window: Online Courses and eBooks Library
Title of the window: New Window

Approach 3: Using quit()

To handle multiple windows in Selenium using Java, the `quit()` method is important for proper cleanup and closure of the browser. After performing the required operations on all windows, it is crucial to invoke the `quit()` method on the driver instance. This method closes all browser windows and terminates the WebDriver session. It releases the associated system resources and ensures a clean exit.

Algorithm

  • The current window's handle can be retrieved using the getWindowHandle() method. Simply store this handle in a variable to access it later.

  • To switch to a specific window inside the loop, one can use the `switchTo().window()` method by passing the handle as an argument.

  • To return to the original window, one can utilize the switchTo().window() method with the original window handle passed as a parameter if necessary.

  • After completing all the necessary operations on the windows, close the browser by calling the quit() method on the driver instance.

  • The WebDriver session ends gracefully by executing the quit() method, which ensures all browser windows are closed and resources are released.

Program

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

public class QuitExample {

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

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

      // Navigate to a webpage
      driver.get("https://www.tutorialspoint.com");

      // Perform actions on the webpage

      // Close all windows opened by the WebDriver instance
      driver.quit();
   }
}

Output

Closes the webpage

Conclusion

In this tutorial, we have learned that handling multiple windows in Selenium using Java is an essential aspect of web automation testing. By utilizing methods such as getWindowHandles() and switchTo().window(handle), testers can effectively navigate between different windows, perform actions on specific windows, and retrieve window handles as needed. The quit() method is valuable for closing all windows opened by the WebDriver instance and ensuring proper cleanup and termination of the WebDriver session.

Updated on: 25-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements