0

I can't close a window using driver.close() method. When it gets executed, an alert appears.

The alert that comes after driver.close() is executed

I tried

JavascriptExecutor js = (JavascriptExecutor) driver;

String script = "window.onbeforeunload = null;";

js.executeScript(script);

driver.close();

I can't even accept the alert. driver.switchTo().alert().accept() is not executed.

I also tried

driver.close();

System.out.println("After closing the window");//This line is not executed.

Control just stops at driver.close() and no exception is thrown and the following lines are not executed.

Code Enthusiastic
  • 2,827
  • 5
  • 25
  • 39
  • the alert is due to browser behaviour which I guess you cannot control – AurA Sep 02 '13 at 09:50
  • @AurA I need to close the window. If I can't then I can't execute the next testcases. – Code Enthusiastic Sep 02 '13 at 09:52
  • 1
    A previous post does handle this alert issue http://stackoverflow.com/questions/5164894/selenium2-and-webdriver-alert – AurA Sep 02 '13 at 10:02
  • @AurA The code following the `driver.close()` is not executed. Please find the edited question. – Code Enthusiastic Sep 02 '13 at 10:10
  • hope you are initializing the WebDriver properly for the browser you use ... a cross platform solution is http://stackoverflow.com/questions/11823150/how-to-initialize-multiple-browsers-in-webdriver-using-java but if that is not the case then you must refer to another previous post http://stackoverflow.com/questions/16839075/selenium-webdriver-driver-close. You must also tell us about the stacktrace if you are getting an exception at driver.close() – AurA Sep 02 '13 at 10:30
  • @CodeEnthusiastic Go to Internet Settings / Security and try lowering the security level. – JacekM Sep 03 '13 at 20:24

1 Answers1

3

Well, the following method did the job.

public void closeWindowByJS(WebDriver driver) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    String script = "window.onbeforeunload = null;" + "window.close();";
    js.executeScript(script);
}
Code Enthusiastic
  • 2,827
  • 5
  • 25
  • 39