basilikum
basilikum

Reputation: 10536

Skip beforeunload handler if user stays on page due to dialog within second handler

I have one beforeunload handler, that is called when the user actually navigates away from the page:

$(window).on("beforeunload", function () {
    cleanup();
});

Another part of my application might however add another beforeunload handler, that asks the user if he really wants to leave because of an ongoing operation:

$(window).on("beforeunload", function () {
    return "Do you really want to leave";
});

How can I assure, that the second handler will always be called first and that the first handler will not be called in case the user decides to stay on the page?

I already tried to use the unload event instead. But this doesn't work since it will not execute my clean-up function and the backend call within that function reliably.

Upvotes: 1

Views: 341

Answers (1)

Jeremy Rajan
Jeremy Rajan

Reputation: 662

You can use window.confirm in case. As in (pseudo-code)

$(window).on("beforeunload", function () {
 var result = window.confirm('Do you really want to quit?');
 if (result) {
  cleanup();
 }
}

This way, if the user wants to quit it will cleanup. Does that work?>

Upvotes: 1

Related Questions