Scroll to top

9y. WebDriver – Handling multiple windows

Hiya folks! Testing workflows involving multiple windows has become a part of life. And with Selenium WebDriver, smoothly switching between these open windows, has become a piece of cake. If you are like me, you are probably anxious to see how all this really works in our code. So, without further delay, let’s take a deep dive…

Whenever a new WebDriver object is instantiated, a unique alphanumeric Id is assigned to each unique window that is opened. This unique Id is called the ‘window handle’ – yet another new term on the crowded streets of Selenium Ville. Thus, using these unique ids, we can easily switch controls between windows and perform required activities.

1. String getWindowHandle():

This method is used to get the window handle of the current window.


// Get current window handle
String parentWinHandle = driver.getWindowHandle();

2. Set<String> getWindowHandles():

This method is used to get the window handles of all the open windows in a Set.


// Get the window handles of all open windows
Set<String> winHandles = driver.getWindowHandles();

The same switchTo() method can be used to switch from one window to another with the reference of the unique handle that is assigned to each open window. For a better understanding of switchTo(), click here.


Let us see a test case implementing these methods to get a good grasp of the concepts at a deeper level,

  1. Open Firefox browser
  2. Navigate to the demo site
  3. Get current window handle and print it to console
  4. Locate ‘Click to open a new browser window!’ button using Id
  5. Click the button to open the new window
  6. Get the window handles of both the open windows
  7. Loop through both handles
  8. Switch to the new window with the handle’s reference
  9. Get the title and print it to console
  10. Close the new window
  11. Switch the control back to parent window and print the URL to the console
  12. Verify Eclipse IDE console output screen and JUnit pane for success result

JUnit code for this scenario is,


import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MultipleWindows {
    // Declaring variables
    private WebDriver driver;
    private String baseUrl;

    public void setUp() throws Exception {
        // Selenium version 3 beta releases require system property set up
        System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
                + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
        // Create a new instance for the class FirefoxDriver
        // that implements WebDriver interface
        driver = new FirefoxDriver();
        // Implicit wait for 5 seconds
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        // Assign the URL to be invoked to a String variable
        baseUrl = "";

    public void testPageTitle() throws Exception {
        // Open baseUrl in Firefox browser window

        // Get current window handle
        String parentWinHandle = driver.getWindowHandle();
        System.out.println("Parent window handle: " + parentWinHandle);
        // Locate 'Click to open a new browser window!' button using id
        WebElement newWindowBtn = driver.findElement("win1"));
        // Click the button to open a new window;
        // Get the window handles of all open windows
        Set<String> winHandles = driver.getWindowHandles();
        // Loop through all handles
        for(String handle: winHandles){
            System.out.println("Title of the new window: " +
            System.out.println("Closing the new window...");
        // Switching the control back to parent window
        // Print the URL to the console
        System.out.println("Parent window URL: " + driver.getCurrentUrl());

    } // End of @Test

    public void tearDown() throws Exception {
        // Close the Firefox browser

Execution Result:

Code is self-explanatory as comments are provided alongside.

In Eclipse IDE -> JUnit pane -> green bar shows that the test case is executed successfully. Console window shows the absence of any errors. It also shows all the printed messages as expected.

multiple windows eclipse output

With this, I will see you soon in another post. Have a great day!

Author avatar
Chandana Chaitanya
Lakshmi Chandana is a Software professional + passion-fueled blogger + novel-reader + artist + tutor to make your day a little brighter than it was before! She is thrilled you are here! She is on a mission to make sure learning sticks but with the fun part kept intact. She uses certain tricks called BrainBells (inspired from barbells and dumbbells used for workout) to achieve this and she says, “this is not the hardest job! As once minions said, it for sure is working in a bubble wrap factory. Imagine the self-control needed!” So, dive in to explore the fun-filled World of Learning!!


  1. Roopa

    Hi Chandana,

    I am Roopa, I have experience in the fields of Manual and Automation.Currently I have taken a break from my career from 2+months. I had a few queries regarding Selenium and automation interviews/jobs.Can you please let me know your email/mobile so that I can ask them?

    • Chandana Chaitanya

      Hi Roopa,

      I have responded with the details to your Gmail id. I will be more than happy to provide any help that you may require.


  2. Sharath

    HI Chandana,
    If multiple windows are open (navigating one after another ), how do we switch to specific window.. if I have static title I switched based on title comparison. but how do we achieve if we have dynamic URL and Title ? Thanks in advance.

  3. Chandana Chaitanya

    Hi Sharath,

    You can always switch to new windows using,
    for(String winHandle : driver.getWindowHandles()){
    //check if the required action/element is present in this window
    // if yes, perform the action and break
    //else continue
    Hope this helps.

Post a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.