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.

Syntax:

// 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.

Syntax:

// 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.

Scenario

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,

package com.blog.junitTests;

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;

    @Before
    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 = "https://chandanachaitanya.github.io/selenium-practice-site/";
    }

    @Test
    public void testPageTitle() throws Exception {
        // Open baseUrl in Firefox browser window
        driver.get(baseUrl);

        // 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(By.id("win1"));
        // Click the button to open a new window
        newWindowBtn.click();
        // Get the window handles of all open windows
        Set<String> winHandles = driver.getWindowHandles();
        // Loop through all handles
        for(String handle: winHandles){
            if(!handle.equals(parentWinHandle)){
            driver.switchTo().window(handle);
            Thread.sleep(1000);
            System.out.println("Title of the new window: " +
driver.getTitle());
            System.out.println("Closing the new window...");
            driver.close();
            }
        }
        // Switching the control back to parent window
        driver.switchTo().window(parentWinHandle);
        // Print the URL to the console
        System.out.println("Parent window URL: " + driver.getCurrentUrl());

    } // End of @Test

    @After
    public void tearDown() throws Exception {
        // Close the Firefox browser
        driver.close();
    }
}

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!

4 Comments 9y. WebDriver – Handling multiple windows

  1. Chandana Chaitanya

    Hi Sharath,

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

    Reply
  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.

    Reply
  3. 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?

    Reply
    1. 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.

      Thanks.

      Reply

Leave 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.