i

Selenium Step By Step Guide

Handling tabs

We see situations in web pages where a new tab or a pop-up window gets opened, and the driver needs to control the new tab or window. In this situation, we must know the handle of a new tab/window to get control of the same.

First, we need to get the handle of the main window, and this helps to switch back to the main window once the operation on the second window is completed.

String mainWindowsHandle=driver.getWindowHandle();

We can open a new tab by using the below set of code and then check for total number of windows open.

driver.findElement(By.xpath("/html/body")).sendKeys(Keys.CONTROL+"t");

Let us now fetch the total number of the window handles to switch to other window.

Set allWindows=driver.getWindowHandles();

Now we need to iterate through the set of all window handles and need to switch to the tab which we opened.

   Iterator itr=allWindows.iterator();

        while(itr.hasNext())

        {

               String handle=itr.next();

               if(!handle.equals(mainWindowsHandle))

               {

                               driver.switchTo().window(handle);

                               driver.get("https://www.google.com/");

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

               }

        }

This way we can switch to the newly opened tab and load an URL on the same. We can get the title of the page by using the getTitle() method to verify the web page.

Once we have performed the operations on the web page, we can switch back to the main window by using the main window/tab handle.

driver.switchTo().window(mainWindowsHandle);