mr. Holiday
mr. Holiday

Reputation: 1800

How to differentiate between Stay On Page and Leave Page

In JavaScript when beforeunload event is executed and the warning box pops up, is it possible to get information what button was clicked?

Upvotes: 0

Views: 176

Answers (1)

KRONWALLED
KRONWALLED

Reputation: 1442

You can't do this directly unfortunately as onbeforeunload asks the browser to create the dialog and doesn't tell you the return value but you can use a global variable which you set in the event and check it via setInterval for example.

JSFiddle

var confirmUnload = false;

window.addEventListener("beforeunload", function(event) {
    confirmUnload = true;
    event.returnValue = "Really leave?";
});

window.addEventListener("unload", function(event) {
    console.log("User left");
});

setInterval(function(){
    if(confirmUnload) {
        confirmUnload = false;

        setTimeout(function() {
            console.log('Still here');
        }, 500);
    }
}, 400);

Upvotes: 1

Related Questions