Testing onbeforeunload events from Selenium

I’m trying to write a Selenium test for a web page that uses an onbeforeunload event to prompt the user before leaving. Selenium doesn’t seem to recognize the confirmation dialog that comes up, or to provide a way to hit OK or Cancel. Is there any way to do this? I’m using the Java Selenium driver, if that’s relevant.

You could write a user extension (or just some JavaScript in a storeEval etc) that tests that window.onbeforeunload is set, and then replaces it with null before continuing on from the page. Ugly, but ought to get you off the page.

I’ve just had to do this for an application of mine where the onbeforeunload handler brings up a prompt if a user leaves a page while a document is in an unsaved state. Python code:

driver.switch_to.alert.accept()

The Java equivalent would be:

driver.switchTo().alert().accept();

If the alert does not exist, the code above will fail with a NoAlertPresentException so there is no need for a separate test to check the existence before accepting the prompt.

I’m running Selenium 2.43.0 but I think this has been doable for a while now.

In cases where I don’t want the prompt to come up at all because that’s not what I’m testing, I run custom JavaScript in the browser to set window.onbeforeunload to null before leaving the page. I put this in the test teardown code