Confirm () on window.onbeforeunload

I want to show a confirmation dialog if the user wants to leave a page with unsaved form data. I have:

window.onbeforeunload = function() {
    if (not_saved) if (confirm('Changes will not be saved')) return true;
    return false;
}

But no matter what the user clicks, the result remains the same - a silly hard-coded dialog box that asks them if they want to leave the page or stay on the page. I want to ask them if they want to stay or leave, and if they want to stay, nothing happens, if they want to leave, they leave. Is it possible? I see how browsers want to limit what websites can do with keeping users on the page, but I think I saw some websites (Google docs that I think) with beautiful civilized dialog boxes.

+5
source share
2 answers
window.onbeforeunload = function(e) {
    return 'Dialog text here.';
};

Documents:

Please note that in Firefox 4 and later, the returned string is not displayed to the user.

If the returnValue attribute of the event object is not an empty string, or if the event has been canceled, then the user agent must ask the user to confirm that they want to upload the document. The tooltip displayed by the user agent may indicate the attribute string returnValue or some of its main subset. (The user agent may want to truncate the string to 1024 characters for display, for instance.)

+7
source

window.onbeforeunload , . - :

if (typeof window.addEventListener === 'undefined') {
    window.addEventListener = function(e, callback) {
        return window.attachEvent('on' + e, callback);
    }
}

window.addEventListener('beforeunload', function() {
    return 'Dialog Text Here';
});

, window.addEventListener, IE, polyfill , .

+9

All Articles