对window.onbeforeunload的任何不良副作用都没有返回值?

时间:2012-04-05 14:13:18

标签: javascript internet-explorer firefox google-chrome browser

我知道在Chrome和FF中,如果window.onbeforeunload返回null,则不会弹出对话框。但在IE中,它会弹出消息“null”。为了使IE不创建弹出窗口,window.onbeforeunload应该不返回任何内容。但是在Chrome和FF中没有任何其他副作用吗?如果没有,为什么有人会费心去写'return null;'首先是什么?

例如,执行此操作:

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

和这个

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

在Chrome中表现不同?

2 个答案:

答案 0 :(得分:2)

在Chrome中,返回null相当于不返回任何内容或undefined 如果没有返回任何内容,则不会弹出对话框。

注意:在第一个示例中,从未到达事件侦听器的最后一行,因为返回了ifelse块。

而不是返回nullundefined等,只是否定条件http://jsfiddle.net/f6uTw/

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

答案 1 :(得分:1)

在Internet Explorer 11上,null仍会创建beforeunload弹出窗口。 undefinednull工作方式不同的罕见情况之一。

ie11 shows onbeforeunload popup with a value of null

相关问题