Goose Goose -4 years ago 144
Javascript Question

Detect if user did NOT cancel on a Javascript onbeforeunload Dialog?

There's lots of questions on how to raise a dialog before a user leaves, and how to detect if the user decided not to leave.

javascript before leaving the page

Detecting whether user stayed after prompting onBeforeUnload

What if I want to do an action only if the user confirms that he wants to leave.

But I don't want to run action() if the user cancels the leave dialog and ends up staying on the page.

How can I detect confirm for

JavaScript Dialog?

Answer Source

Use the unload event. This event will be fired after they confirm the dialogue displayed because of the onbeforeunload event.

window.addEventListener("unload", function() {

Note that there are restrictions on what you can do in beforeunload and unload event handlers, to prevent malware that completely prevents you from closing the window/tab.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download