1

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 onbeforeunload JavaScript Dialog?

Goose
  • 4,764
  • 5
  • 45
  • 84

1 Answers1

2

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

window.addEventListener("unload", function() {
    console.log("Bye!");
});

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612