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.

Example

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 ClosePopup {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",       "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://secure.indeed.com/account/login");
      //implicit wait
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.findElement(By.id("login−google−button")).click();
      // store window handles in Set
      Set<String> wnd = driver.getWindowHandles();
      // window handles iteration
      Iterator<String> i = wnd.iterator();
      String prntw = i.next();
      String popwnd = i.next();
      // switching pop up window handle id
      driver.switchTo().window(popwnd);
      System.out.println("Page title of popup: "+ driver.getTitle());
      // closes pop up window
      driver.close();
      // switching parent window handle id
      driver.switchTo().window(prntw);
      System.out.println("Page title of parent window: "+ driver.getTitle());
      driver.quit();
   }
}

Output

raja
Published on 28-Nov-2020 13:42:43
Advertisements