confirm() on window.onbeforeunload

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

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 is the same - the stupid hardcoded dialog box that asks them whether they want to leave the page or stay on page. What I want to ask them is whether they want to stay or leave, and if they want to stay nothing happens, if they want to leave, they leave. Is this even possible? I can see how browsers want to limit what websites can do about keeping the users on the page, but I think I've seen some websites (Google Docs I think) having nice civilized dialog boxes.


Solution 1:

window.onbeforeunload = function(e) {
    return 'Dialog text here.';
};

Docs:

  • https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
  • http://dev.w3.org/html5/spec-LC/history.html#unloading-documents

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 the empty string, or if the event was canceled, then the user agent should ask the user to confirm that they wish to unload the document. The prompt shown by the user agent may include the string of the returnValue attribute, or some leading subset thereof. (A user agent may want to truncate the string to 1024 characters for display, for instance.)

Solution 2:

Although window.onbeforeunload works, it's considered bad practice. It's better to use something like the following:

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

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

First we check if window.addEventListener exists, which it does not in IE, else we polyfill it, and then we attach the event.