How can I close a specific window using Selenium WebDriver with Java?

We can close a specific window with 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 window handle of the browser window in focus. We have to add import java.util.Set and import java.util.List statements to accommodate Set data structure in our code.

By default, the driver object can only 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.


Code Implementation.

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;
public class CloseSpecificWindow {
   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(5, TimeUnit.SECONDS);
      //window handle of parent window
      String m = driver.getWindowHandle();
      // store window handles in Set
      Set w = driver.getWindowHandles();
      // iterate window handles
      for (String h: w){
         // switching to each window
         String s= driver.getTitle();
         // checking specific window title
         if(s.equalsIgnoreCase("Sign in - Google Accounts")){
            System.out.println("Window title to be closed: "+ driver.getTitle());
      // switching parent window