Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any bad side effects to window.onbeforeunload returning no value?

I know that in Chrome and FF, if window.onbeforeunload returns null, then the dialog box will not pop up. But in IE, it pops up with the message 'null'. In order to make IE not create a pop-up, window.onbeforeunload should return nothing. But does returning nothing have any other side effects in Chrome and FF? If not, why would anyone bother to write 'return null;' in the first place?

For example, do this:

window.onbeforeunload = function() { 
  if (shouldNotWarnBeforeUnload)
    { return null; }
  else 
    { return ('Are you sure you want to leave the page?'); }
  return null;
};

and this

window.onbeforeunload = function() { 
  if (shouldNotWarnBeforeUnload)
    {  }
  else 
    { return ('Are you sure you want to leave the page?'); }
};

behave differently in Chrome?

like image 481
JYX Avatar asked Sep 17 '25 13:09

JYX


1 Answers

In Chrome, returning null is equivalent to returning nothing or undefined.
When nothing is returned, the dialog will not pop up.

Note: In your first example, the last line of the event listener is never reached, because either the if or else block returned.

Instead of returning null, undefined etc, just negate the condition : http://jsfiddle.net/f6uTw/

window.onbeforeunload = function() { 
    if (!shouldNotWarnBeforeUnload) {
        return 'Are you sure you want to leave the page?';
    }
};
like image 164
Rob W Avatar answered Sep 20 '25 02:09

Rob W