简体   繁体   中英

How to close child browser window in Selenium WebDriver using Java

After I switch to a new window and complete the task, I want to close that new window and switch to the old window,

so here i written like code:

// Perform the click operation that opens new window

String winHandleBefore = driver.getWindowHandle();

    // Switch to new window opened

    for (String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle);
    }

    // Perform the actions on new window


    driver.findElement(By.id("edit-name")).clear();
    WebElement userName = driver.findElement(By.id("edit-name"));
    userName.clear();
              try
    {
        driver.quit();
    }

    catch(Exception e)
    {
        e.printStackTrace();
        System.out.println("not close");
                }

driver.switchTo().window(winHandleBefore);// Again I want to start code this old window

Above I written code driver.quit() or driver.close() . But I am getting error. Can anybody help me...?

org.openqa.selenium.remote.SessionNotFoundException: The FirefoxDriver cannot be used after quit() was called.

To close a single browser window:

driver.close();

To close all (parent+child) browser windows and end the whole session:

driver.quit();

The logic you've used for switching the control to popup is wrong

 for (String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle);
    }

How the above logic will swtich the control to new window ?


Use below logic to switch the control to new window

// get all the window handles before the popup window appears
 Set beforePopup = driver.getWindowHandles();

// click the link which creates the popup window
driver.findElement(by).click();

// get all the window handles after the popup window appears
Set afterPopup = driver.getWindowHandles();

// remove all the handles from before the popup window appears
afterPopup.removeAll(beforePopup);

// there should be only one window handle left
if(afterPopup.size() == 1) {
          driver.switchTo().window((String)afterPopup.toArray()[0]);
 }

// Perform the actions on new window

  **`//Close the new window`** 
    driver.close();

//perform remain operations in main window

   //close entire webDriver session
    driver.quit();
//store instance of main window first using below code
String winHandleBefore = driver.getWindowHandle(); 

Perform the click operation that opens new window

//Switch to new window opened
for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle);
}

// Perform the actions on new window
driver.close(); //this will close new opened window

//switch back to main window using this code
driver.switchTo().window(winHandleBefore);

// perform operation then close and quit
driver.close();
driver.quit();

There are some instances where a window will close itself after a valid window handle has been obtained from getWindowHandle() or getWindowHandles().

There is even a possibility that a window will close itself while getWindowHandles() is running, unless you create some critical section type code (ie freeze the browser while running the test code, until all window management operations are complete)

A quicker way to check the validity of the current driver is to check the sessionId, which is made null by driver.close() or by the window closing itself.

The WebDriver needs to be cast to the remote driver interface (RemoteWebDriver) in order to obtain the sessionId, as follows:

if (null == ((RemoteWebDriver)driver).sessionId) {
    // current window is closed, switch to another or quit
} else {
    // current window is open, send commands or close
}

Also note that closing the last window is equivalent to quit().

There are 2 ways to close the single child window:

Way 1:

driver.close();

Way 2: By using Ctrl+w keys from keyboard:

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "w");
public class First {
    public static void main(String[] args) {
        System.out.println("Welcome to Selenium");
        WebDriver wd= new FirefoxDriver();
        wd.manage().window().maximize();
        wd.get("http://opensource.demo.orangehrmlive.com/");
        wd.findElement(By.id("txtUsername")).sendKeys("Admin");
        wd.findElement(By.id("txtPassword")).sendKeys("admin");
        wd.findElement(By.id("btnLogin")).submit();
        **wd.quit(); //--> this helps to close the web window automatically** 
        System.out.println("Tested Sucessfully ");
    }
}

I've also tried

1)driver.close();
2)driver.quit();

apparently, these methods don't work as expected!(not saying it don't work though) I've even tried making the driver class singleton and it didn't help me with running test cases parallel.so it was also not the optimal solution.finally, i came up creating a separate class to run a bat file.which the bat file contains commands of grouping all the chrome driver process and all the child processes of it.and from the java class I've executed it using Runtime.

The class file that runs the bat file

public class KillChromeDrivers {

    public static void main(String args[]) {


        try {

            Runtime.getRuntime().exec("cmd /c start E:\\Work_Folder\\SelTools\\KillDrivers.bat");
            //Runtime.getRuntime().exec()
        } catch (Exception ex) {



        }
    }

}

The command that you have to put in the [ .bat ] file

taskkill /IM "chromedriver.exe" /T /F

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM