How to Switch to a New Window in Selenium

This post is written with the intent to teach you how to switch to a new window in selenium. We make use of window handles when we have to switch to a new window. Each window is given a handle of their own to tell them apart from each other. A handle has nothing but an alphanumeric value for itself as was seen earlier in Selenium Commands tutorial that helps in identification.

handle meme

If you are curious and you wish to find out what your current window handle is, you can simply make use of the following command after opening a new URL:

System.out.println(driver.getWindowHandle());

You might get a value that might look something similar to this:

CDwindow-31249D55763D2E22E492041B5E0FC081

We will discuss more on window handles at a later juncture of this article.

An Example of a Link Opening a New Window

Now let’s imagine a scenario wherein you click a link and another window opens. For e.g. just click on this Selenium link.

Didn’t that just open a new window in your browser?

Well, even though a new window has opened and the control has gone to it, as far as coding is concerned the control is still at your original window, you know, the parent window. So if you want to perform an activity, on the newly opened window, you have to explicitly switch to it before working on it.

In order to cycle through the windows, we make use of the switch to handle method. Let us see how it is done.

Methods to Handle Windows

Selenium provides you two methods to deal with multiple windows situation. They are namely:

  • driver.getWindowHandles()
  • driver.getWindowHandle()

driver.getWindowHandles returns an Iterator thus providing you a method to cycle between the windows. You can make use of the next() method of the iterator to iterate through your handles.

Au contraire, when you wish to handle the current window you can make use of driver.getWindowHandle(). The return type of this method is String.

Apart from the above, in order to actually switch between windows you make use of the following method:

driver.switchTo().window(windowName)

where windowName is the name of the window you wish to switch to.

Now that we know about all the methods we are going to use in order to switch to a newly opened window, let’s see how.

How to Switch to a New Window in Selenium

Let us see an example now in order to learn how to switch to a new window in selenium. We will use an example where we will first navigate to Selenium Commands webpage and then on that page click on an IMDb reference or page.

The only thing that you have to keep in mind is that you have to be really sure to grab a handle (window) before working on it. If you don’t do that, the control might be on some other window and you might end up getting an Element Not Found Exception.

How do you confirm which handle you are on? Yes, guessed right. Through this:

System.out.println("The current handle is " + driver.getWindowHandle());

The first step would be to of course navigate to the first link which we will do with this:

System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\drivers\\chromedriver.exe");
driver = new ChromeDriver(); 

driver.get("http://dumbitdude.com/selenium-commands/");

System.out.println("The current handle is " + driver.getWindowHandle());

The Second Window – Switch

As you can see above, from the last line we have also grabbed its handle just to confirm where our handles are. In order to now click on Will Ferrell now which is basically an IMDb link, we will add the following code:

WebElement we = driver.findElement(By.xpath("//*[@class='entry-inner']//a"));
we.click();

That should open the link and show the newly opened tab on your screen. To show you where the handle is, I will sysout once again to get the window handle.

This is the code so far:

public class SwitchWindowExample {

       static WebDriver driver;

 public static void main(String[] args) {

            System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\drivers\\chromedriver.exe");
            driver = new ChromeDriver(); 

            driver.get("http://dumbitdude.com/selenium-commands/");

            //Printing the window handle
            System.out.println("The current handle is " + driver.getWindowHandle());

            //Clicking on Will Ferrell (an IMDb link)

            WebElement we = driver.findElement(By.xpath("//*[@class='entry-inner']//a"));
            we.click();

            //Printing the window handle again

            System.out.println("The current handle is " + driver.getWindowHandle());

      }

}

If you run the above program now, you will get the output as:

The current handle is CDwindow-C6D945AC0796EBA9EF4272FB333F4836
The current handle is CDwindow-C6D945AC0796EBA9EF4272FB333F4836

You know not necessarily the same alphanumeric digits but it will be something similar, and both of the lines will have the same alphanumeric handle. The webpage displayed would be that of the IMDb page.

will ferrell page example for selenium window handles

The thing to note here is that you can see the Window handle before and after are still the same.

Introducing Window Handles in the Above Code

Moving on to the crucial section of how to switch to a new window in selenium now, we will make use of all the important methods that we had discussed earlier.

Now we will insert the following piece of code after the IMDb link is clicked:

//Switching to the new window
Set<String> handles = driver.getWindowHandles();
String originalWindow = driver.getWindowHandle();

Iterator <String> iterator = handles.iterator();
while(iterator.hasNext()) {

   String newWindow = iterator.next();

    if(!originalWindow.equalsIgnoreCase(newWindow)){

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

}

In order to understand the above code: what we have done is used the getWindowHandles() method and stored the output in a Set of String. We are using the getWindowHandle() method to refer to the original Window.

Then we have used an iterator to iterate or cycle through both the handles using iterator’s next method. How do we actually switch? Yes using driver.switchTo().window() method.

So now the whole code for how to switch to a new window tutorial in selenium would look something like this:

public class SwitchWindowExample {

static WebDriver driver;

public static void main(String[] args) {

            System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\drivers\\chromedriver.exe");
            driver = new ChromeDriver(); 

            driver.get("http://dumbitdude.com/selenium-commands/");

            //Printing the window handle
            System.out.println("The current handle is " + driver.getWindowHandle());

            //Clicking on Will Ferrell (an IMDb link)

            WebElement we = driver.findElement(By.xpath("//*[@class='entry-inner']//a"));
            we.click();

           //Switching to the new window
           Set<String> handles = driver.getWindowHandles();
           String originalWindow = driver.getWindowHandle();

           Iterator <String> iterator = handles.iterator();
           while(iterator.hasNext()) {

           String newWindow = iterator.next();

           if(!originalWindow.equalsIgnoreCase(newWindow)){

           driver.switchTo().window(newWindow);

                  }

           }

           //Printing the window handle again

           System.out.println("The current handle is " + driver.getWindowHandle());

      }

}

Final Output

If you run the above now, this is the output you will get:

The current handle is CDwindow-5EFB5C1F20AE1AAA1B7167B0C4D65B0F
The current handle is CDwindow-E8069008358E60981162D2EF8C067176

As you can see both the handles are different from each other. The second one is that of the new webpage.

This means the above code has taken the control to the newly opened window. To see that in action, I would suggest you try and click on something on the IMDb page using your code.

Let that be your little activity.

Enjoyed learning how to switch to a new window in selenium? Tell us in the comments section below.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

Leave a Reply