Navigating Between Windows using Selenium

Selenium Multiple Windows

Windows Navigation

Many a times, you may have noticed that on clicking any link or button on a website opens the target webpage/website in a new browser window. We cannot simply continue using our existing driver object to interact with the WebElements in newly opened window. Here we will learn how to navigate between multiple opened windows using selenium WebDriver.

In order to work with the WebElements of website opened new window, we must tell our existing driver “Hey, you should now work on this new window. And after performing operations on new window return to old window and perform remaining steps there.”
Selenium provides this facility in WebDriver interface which help user to interact with multiple opened windows and yet keep a track of them. Suppose following is the HTML of link which opens a new browser window:
<a href="example.html" target="newWindow">Open in New Window</a>

Following is the code to get hold of the new window:

driver.switchTo().window("newWindow");

If you already have multiple windows opened and you want to work with a particular window, then you may use getWindowHandles() method which will return a Set of String values. We will traverse the list using for each loop and print the handle name of all the opened windows. Further, user may use if else condition within the for each loop to get desired window.

for (String handle : driver.getWindowHandles()) {
    driver.switchTo().window(handle);
}

LAB EXERCISE:

On website “https://the-internet.herokuapp.com/windows”, click on “click Here” button and verify if new window is indeed opened?
Selenium WebDriver

Solution:

We will break the problem into smaller tasks. This is demonstrated below:

Step 1: Create a method to open the browser and navigate to desired url. 

Create a new method getURL() and open the desired url using WebDriver get() method.

Step 2: Identify the link(WebElement) “Click Here” and click on it.

Right click on the link and select “Inspect Element“. Check the <a> tag and note down “target” value, which is “_blank” in this case.
AutomationUtils Selenium WebDriver

Check the title of new opened window. We will use this property to verify if correct new window is opened.

AutomationUtils Selenium WebDriver
Here we can see that new window’s title is “New Window“.

Step 3: Verify the new window’s title against which we have noted in above steps.

Since there would be more than 1 browser window, we will use getWindowHandles()method to extract all opened windows’ title and store them in a Set of String variable. Full code is explained below:

Step 1:

package testpkg.SeleniumWebDriverDemo;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Frame {
        //initialize the driver at class level so that it is available throughout the code

    public WebDriver driver = null;

    public static void main(String[] args) throws Exception {

    }

    public void getUrl() throws Exception {
        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Dhawal\\Downloads\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();

        // Open the Browser and navigate to desired url

        driver.get("https://the-internet.herokuapp.com/windows");
         }
}

Step 2: Update above code with following in bold

package testpkg.SeleniumWebDriverDemo;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Frame {
        //initialize the driver at class level so that it is available throughout the code

    public WebDriver driver = null;

    public static void main(String[] args) throws Exception {

    }

    public void getUrl() throws Exception {
        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Dhawal\\Downloads\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();

        // Open the Browser and navigate to desired url

        driver.get("https://the-internet.herokuapp.com/windows");
                
                // Identify the link(WebElement) "Click Here" and click on it.
        driver.findElement(By.linkText("Click Here")).click();
        Thread.sleep(3000);
         }
}

Step 3:

package testpkg.SeleniumWebDriverDemo;

import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Frame {
    public WebDriver driver = null;

    public static void main(String[] args) throws Exception {
        Frame frame = new Frame();
        frame.getUrl();
    }

    public void getUrl() throws Exception {
        System.setProperty("webdriver.chrome.driver",
                "C:UsersDhawalDownloadschromedriver_win32chromedriver.exe");
        driver = new ChromeDriver();

        // Open the Browser and navigate to desired url
        driver.get("https://the-internet.herokuapp.com/windows");

        // Identify the link(WebElement) "Click Here" and click on it.
        driver.findElement(By.linkText("Click Here")).click();
        Thread.sleep(3000);

        Set<String> handles = driver.getWindowHandles();
        for (String handle : handles) {
            if (driver.switchTo().window(handle).getTitle().equalsIgnoreCase("new window")) {
                System.out.println("Correct Window Opened");
            }

        }

    }
}

We have created a Set of String “handle“, which will hold all the opened window handles (Remember, getWindowHandles() always returns a collection of String values). In this example we have 2 opened windows. We have iterated over these values using a for-each loop and verified if any of the opened windows’ title is “new window”.

Further, if we need to interact with any of the WebElement in new window, we will use driver.switchTo().window(handle).findElement(By) to get the WebElement reference.

Try to interact with WebElements of new window, and comment below in case you need help.


Hope you guys have understood how we can keep track of all opened windows and traverse among them. Next, we will see how to work with frames. This would be a cake-walk as in this case we know the locators and total number of frames in a window in advance.

Author: Dhawal Joshi

A post-graduate in MCA, ISTQB & ITIL certified QA with more than 8 years of experience in QA working with a CMMI Level 5 organization as System Analyst. I started my automation journey with HP UFT(formerly known as QTP) and for the past few years, I am using Selenium for automation. I also have experience in Android Application Development, Java, HTML, and VBScript. When I am not working, I like to spend time with my family, cooking and learning new developments in IT.

2 thoughts on “Navigating Between Windows using Selenium

Leave a Reply

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