Is it possible to handle Windows based pop-ups in Selenium?


Yes, it is possible to handle Windows based pop-ups in Selenium webdriver. Sometimes on clicking a link or a button, another window gets opened. It can be a pop up with information or an advertisement.

The methods getWindowHandles and getWindowHandle are used to handle child windows. The getWindowHandles method stores all the handle ids of the opened windows in the form of Set data structure.

The getWindowHandle method stores the handle id of the window in focus. Since the getWindowHandles method holds all the opened window handle ids, we can iterate through these handle ids with the iterator and next methods.

To switch to a specific window, switchTo.().window() method can be used. The handle id of the window where we want to switch is passed as a parameter to this method.

Code Implementation

import org.openqa.selenium.By;
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;
public class FirstAssign {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "chromedriver");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
      //url launch
      driver.get("https://secure.indeed.com/account/login");
      driver.findElement(By.id("login-google-button")).click();
      //hold window handles
      Set<String> s = driver.getWindowHandles();
      // iterate handles
      Iterator<String> i = s.iterator();
      //child window handle id
      String c = i.next();
      //parent window handle id
      String p = i.next();
      // child window switch
      driver.switchTo().window(c);
      System.out.println("Page title of child window: "+ driver.getTitle());
      // switch to parent window
      driver.switchTo().window(p);
      System.out.println("Page title of parent window: "+ driver.getTitle());
      //browser quit
      driver.quit();
   }
}

Output

Updated on: 25-Jun-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements