Search code examples
javascriptjqueryonbeforeunload

Why is jquery beforeunload showing a message even when returning null in Internet Explorer


This code will cause Internet Explorer to show the 'Are you sure you want to leave?' message every time, even when dirtyMessage is null. What am I doing wrong?

$(window).bind('beforeunload', function() {
  var dirty = didUserUpdateSomething();  

  if (dirty) {
    return "You will lose your changes.";
  }
  return null;
});

Solution

  • Apparently returning null is the problem. Works in all other browsers except good old IE. The solution is not to return anything (undefined):

    $(window).bind('beforeunload', function() {
      var dirty = didUserUpdateSomething();  
    
      if (dirty) {
        return "You will lose your changes.";
      }
      // notice that in case of no dirty message we do not return anything. 
      // having 'return null;' will make IE show a popup with 'null'.
    });