How to close child browser window in Selenium WebDriver using Java?

SeleniumAutomation TestingTesting ToolsJava

We can close the child browser window in Selenium webdriver. The getWindowHandles and getWindowHandle methods can be used to handle child windows. The getWindowHandles method is used to store all the opened window handles in the Set data structure.

The getWindowHandle method is used to store the browser window currently active. To iterate over the window handles, the iterator method is used. We have to add import java.util.Set to accommodate Set and import java.util.List and import java.util.Iterator statements to accommodate iterator in our code.

By default, the driver object can access the elements of the parent window. In order to switch its focus from the parent to the child window, we shall take the help of the switchTo().window method and pass the window handle id of the child window as an argument to the method. Then to move from the child window to the parent window, we shall take the help of the switchTo().window method and pass the parent window handle id as an argument to the method.

Example

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 CloseChildWindow {
   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(2, TimeUnit.SECONDS);
      driver.findElement(By.id("login-google-button")).click();
      // window handles
      Set w = driver.getWindowHandles();
      // window handles iterate
      Iterator t = w.iterator();
      String ch = t.next();
      String pw = t.next();
      // switching child window
      driver.switchTo().window(ch);
      System.out.println("Child window title "+ driver.getTitle());
      // close the child browser window
      driver.close();
      // switching parent window
      driver.switchTo().window(pw);
      System.out.println("Parent window title: "+ driver.getTitle());
      driver.quit();

Output

raja
Published on 26-Oct-2020 11:10:10
Advertisements