yossi
yossi

Reputation: 3164

why beforeunload always triggered?

I have a form, which changes when -some- elements are focused.
I want to be warned when I'm leaving the page. so I keep a flag that tells me when those elements changed.
The problem is that the alert "this page is asking you to confirm that you want to leave” - is always prompt;

function checkSave(){
    return PageWasChanged; // it is correct, checked
}
$(window).on("beforeunload", function (eve) {
    if (checkSave()) {
        return true;
    }
    else {
        return false;
    }
});

Upvotes: 0

Views: 455

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074208

beforeunload is not like other events. Its handler is supposed to return undefined (don't show the prompt) or a string (which used to be used as the text of the prompt, but isn't on modern browsers).

So:

$(window).on.("beforeunload", function() {
    if (!checkSave()) {
        return "You have unsaved changes.";
    }
});

or without jQuery:

window.onbeforeunload = function() {
    if (!checkSave()) {
        return "You have unsaved changes.";
    }
};

Upvotes: 1

Related Questions