i

Selenium Step By Step Guide

Handling tabs and Pop-ups – Code

Handling tabs and Pop-ups – Code:

In a scenario, we need to open a new tab from current and then launch a new url on a new tab. Once the URL is launched, we need to fetch the title of the web page. Finally, we need to switch back to the main tab and check the title of the main tab's web page. Let us check the complete code to handle the above scenario:

package SeleniumTest.SeleniumTest;

 

import java.util.Iterator;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.Keys;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

 

public class WindowsHandles

{

    static public void main( String[] args ) throws InterruptedException

    {

        System.setProperty("webdriver.chrome.driver","C:\\Users\\chromedriver.exe");

        WebDriver driver=new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://selflearning.io/");

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

        String mainWindowsHandle=driver.getWindowHandle();

        Set<String> allWindows=driver.getWindowHandles();

        Iterator<String> 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());

                              

               }

        }

        driver.switchTo().window(mainWindowsHandle);

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

        driver.quit();

    }

}