user83950
user83950

Reputation:

onBeforeUnload handler says null in IE

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';
   }
});

Upvotes: 15

Views: 10467

Answers (2)

Chris
Chris

Reputation: 27394

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';
}

Upvotes: 0

Jon
Jon

Reputation: 437854

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.

Upvotes: 21

Related Questions