12

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.

DMIL
  • 693
  • 3
  • 7
  • 18

3 Answers3

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

Docs:

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.)

Peter
  • 16,453
  • 8
  • 51
  • 77
13

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.

Nate Higgins
  • 2,104
  • 16
  • 21
  • 1
    Setting the event just by setting `window.onbeforeuload` is a really bad idea as it may mess with any other events that have been set. Instead, we "listen" for the event by adding an event listener. But in Internet Explorer, `window.addEventListener` doesn't exist, so we fake it using window.attachEvent, which does exist but with a slightly different syntax. – Nate Higgins Aug 26 '12 at 17:11
  • 2
    Well that's another problem I didn't even know I had. Th... thanks. – DMIL Aug 26 '12 at 17:13
  • won't change dialog text for me, any solution now? 2019? – Jiel Nov 19 '19 at 08:36
0

With jQuery, you can set the same handlers. The code may defer based on your version.

    function AnyFunction(e){ /**** your code *****/ };

    $(function () {
      $(window).bind('unload', function (e) { return AnyFunction(e); });
      $(window).bind('beforeunload', function (e) { return AnyFunction(e); });
    });

You can also change the confirm or alert function using plugins as bootbox.

nicotina
  • 31
  • 2