How to handle popup windows in Selenium?


Selenium has getWindowHandles() method , which returns all the window handle ids for all the open windows. This is stored in Set data structure in String data types.

In order to navigate to a specific window, we need to traverse to the window we want to access with the iterator() method then switch to that window.

getWindowHandle() method gives the window handle id of the current window Id.

Example

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;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
import org.testng.annotations.Test;
public class WindowHandles{
   @Test
   public void windowHandle() throws Exception {
      System.setProperty("webdriver.chrome.driver", "C:\Selenium\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // getting the current window handle id
      String currentwindow = driver.getWindowHandle();
      // getting all the window handles in Set data structure
      Set<String> allWindows = driver.getWindowHandles();
      // traversing each ids with the help of iterator()
      Iterator<String> i = allWindows.iterator();
      //Iterating through the window handle ids
      while(i.hasNext()){
         String childwindow = i.next();
         if(!childwindow.equalsIgnoreCase(currentWindow)){
            driver.switchTo().window(childwindow);
            System.out.println("The child window is "+childwindow);
         } else {
            System.out.println("There are no children");
         }
      }
      driver.quit();
   }
}

Updated on: 10-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements