Handle multiple windows or tabs in Selenium with Java

Profile picture for user ksharma

While doing automation of web apps sometimes we have to face situation in which we have to move to new tab or window. To replicate the similar scenario we will be using automation practice website and click on facebook, twitter, youtube and google+ icon present in footer section of the website and then get the title of each tab after switching to each tab.

Consider below code:

public class MultipleWindows 
{
    WebDriver driver;
	
    @BeforeTest
    public void bTest()
    {
        System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir") + "//drivers//chromedriver");
        driver = new ChromeDriver();
        driver.get("http://www.automationpractice.com");
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.manage().window().maximize();
    }
	
    @Test
    public void MultipleWindowsHandle() throws InterruptedException
    {
        System.out.println(driver.getTitle());
        
        List<WebElement> elements = driver.findElements(By.cssSelector("section[id='social_block'] li a"));
        for(int i = 0; i < elements.size(); i++)
            elements.get(i).click();
		
        String mainWindow = driver.getWindowHandle();
        Set<String> allWindowHandles = driver.getWindowHandles();

        for(String handle : allWindowHandles)
        {
            if(!handle.equals(mainWindow))
            {
                driver.switchTo().window(handle);
                System.out.println(driver.getTitle());
                Thread.sleep(3000);
            }
        }
		
        driver.switchTo().window(mainWindow);
        System.out.println(driver.getTitle());
}

Explanation:

  • All the social elements are stored in List of WebElements using findElements method. Then we have clicked on all the icons using for loop.
  • getWindowHandle(): This will get the window handle of mainWindow (Automation Practice Website). 
  • getWindowHandles(): This will return a set of window handles which can be used to iterate over all open windows of the WebDriver instance.
  • Set<String>: This will store the window handles in the form of a string in allWindowHandles variable.
  • Using for each loop we are iterating over each handle, we can also use Iterator here to iterate over Set.
  • if current handle is not mainWindow, we will switchTo handle and print title of the window. We have added thread to observe how the things are going during the execution.
  • if current window handle is main window, it will come out of loop and print title of main window again.
  • One point to note here, it will print window title in reverse order, the last open window title will be printed first. Our script uses a set with undefined ordering, and no selenium implementation has ever guaranteed that window handles are returned in the order in which they're open.

Output

My Store
Sign in – Google accounts
Selenium Framework - YouTube
Selenium Framework (@seleniumfrmwrk) / Twitter
Selenium Framework | Facebook
My Store

Optional: Replace for each loop with Iterator if you want to work with Iterator

Iterator<String> itr= allWindowHandles.iterator();
while(itr.hasNext())
{
    String handle = itr.next();
    if(!handle.equals(mainWindow))
    {
        driver.switchTo().window(handle);
        System.out.println(driver.getTitle());
        Thread.sleep(3000);
    }
}