3

I'm automating tests on a web page which pops an Alert window upon clouser using driver.close(). The alert is for confirmation asking if i'm sure and exposes "stay" or "leave" buttons.

Now, when driver.close() is executed, the popup shows and driver.close() is "stuck", waiting for response, BUT I cannot executed driver.switchto().alert() to response (accept() or dismiss() ) since the driver is waiting... Working with additional thread didn't help. Eventually, after a long timeout, close throws an exception....

Any ideas? It is so trivial scenario, yet very hard to deal with from code with selenium api.

acikojevic
  • 915
  • 1
  • 7
  • 16
ClimbingLung
  • 219
  • 2
  • 8
  • Do you want to test that the alert is there? I would first try to call `driver.dispose()` or `driver.quit()` if you don't care about the alert and see if that takes care of it. That being said, if you are calling `driver.close()` intentially to keep the driver alive and just close the current window, this wouldn't be what you want. – mrfreester Jan 20 '17 at 17:42
  • If you want to acknowledge the alert is there, the answer here applies: http://stackoverflow.com/questions/29054134/how-to-close-the-browser-by-rejecting-popup-window-in-selenium-webdriver Basically just use `((JavascriptExecutor)driver).executeScript("window.close()" );` to close the browser, then you can accept or reject the alert, or check if it's there before calling `driver.quit()` – mrfreester Jan 20 '17 at 17:58

2 Answers2

2

The solution is eventually as mrfreester suggested. Since I want to test the alert as well, I first initiate the Alert by calling the JS for closing the window. Next, I interact with the alert using web driver.

Step 1:

((JavascriptExecutor)driver).executeScript("window.close()" )

Step 2:

Wait for the alert and interact (see Java example here: Alert handling in Selenium WebDriver (selenium 2) with Java )

 Alert alert = driver.switchTo().alert();
 alert.accept(); // or alert.dismiss()
Community
  • 1
  • 1
ClimbingLung
  • 219
  • 2
  • 8
1

You can just execute following code lines before closing browser (driver.close()) to avoid pop-up appearance:

IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("window.onbeforeunload = null;");
Andersson
  • 51,635
  • 17
  • 77
  • 129