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.

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;
public class CloseSpecificWindow {
   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(5, TimeUnit.SECONDS);
      //window handle of parent window
      String m = driver.getWindowHandle();
      driver.findElement(By.id("login-google-button")).click();
      // store window handles in Set
      Set w = driver.getWindowHandles();
      // iterate window handles
      for (String h: w){
         // switching to each window
         driver.switchTo().window(h);
         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());
            driver.close();
         }
      }
      // switching parent window
      driver.switchTo().window(m);
      driver.quit();
   }
}

Output

Updated on: 26-Oct-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements