How to close the pop up window in selenium running?

Software TestingAutomation TestingSelenium Web Driver

We can close the pop up window with Selenium. The getWindowHandles and getWindowHandle methods are used for the pop up window. To store all the window handles opened in a Set data structure, the getWindowHandles method is used.

To store the window handle of the pop up in focus, the getWindowHandle method is used. To iterate over the window handles, the iterator method is used. By default, the Selenium driver has the control over the parent window.

To switch the focus of the driver to the child pop up window, we can take the help of the switchTo().window method. The window handle id of the pop up is passed as an argument to the method.

We have to incorporate import java.util.Set, import java.util.List, and import java.util.Iterator packages to work with the above methods.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
public class ClosePopup {
   public static void main(String[] args) {
      System.setProperty("",       "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      // store window handles in Set
      Set<String> wnd = driver.getWindowHandles();
      // window handles iteration
      Iterator<String> i = wnd.iterator();
      String prntw =;
      String popwnd =;
      // switching pop up window handle id
      System.out.println("Page title of popup: "+ driver.getTitle());
      // closes pop up window
      // switching parent window handle id
      System.out.println("Page title of parent window: "+ driver.getTitle());


Published on 28-Nov-2020 18:12:43