15
votes

my web-app has this:

$(window).bind('beforeunload', function() {
    if(unSavedChanges == true)
    {
        return 'You have unsaved changes';
    }
    return null;
});

this works fine in Safari and Firefox (with the exception that firefox does not show my custom message in it's onBeforeUnload dialog). However on IE 8 on Windows 7, it always shows the onBeforeUnload notification, specifically if there are no unsaved changes, it would just say "null". How can I prevent IE from showing onBeforeUnload notification when user has saved everything and wants to navigate away?

as per Jon's suggestion, I have removed the return null line, the code now reads

$(window).bind('beforeunload', function() {
   if(unSavedChanges == true)
   {
       return 'You have unsaved changes';
   }
});
2
The second block if code is already the solution, which works correctly, right? To me it's honestly a little confusing if we edit the question so that we cannot make out on first sight which code has problems and which one doesn't. - NilsB

2 Answers

21
votes

Remove the return null line and it should be fine (in Javascript null and undefined are different things).

By the way, MDN says that for maximum compatibility you should be accepting an event parameter and setting event.returnValue as well.

0
votes

I use normal javascript for this and works fine

function setConfirmUnload(on) {
     window.onbeforeunload = (on) ? unloadMessage : null;
}

function unloadMessage() {
     return 'Please stay on the page';
}