使用onbeforeunload没有对话框?

use*_*989 20 javascript jquery onbeforeunload

我正试图在用户离开我的页面时发布数据.我终于找到了一个可行的解决方案,但是,当用户离开时,它会显示一个确认对话框.我试过return null;但它没有用.是否可以禁用对话框?

window.onbeforeunload = function() {
    $.post("track.php", {
        async: false,
        refid: refid,
        country: country, 
        type: type,
    });

    return '';
}
Run Code Online (Sandbox Code Playgroud)

mee*_*ern 41

Mozilla Developer Network页面:

当此事件返回非void值时,将提示用户确认页面卸载.

这意味着处理程序的返回值必须是undefined(未'',falsenull),以避免触发的确认提示.

window.onbeforeunload = function() {

  $.post("track.php", {
  ...
  });

  return undefined;
}
Run Code Online (Sandbox Code Playgroud)

在javascript中,您可以完全跳过返回值以获得相同的结果.

在带有jquery的coffeescript中,它就像是

$(document).ready ->
  $(window).bind('beforeunload', ->
    #put your cleanup code here
    undefined
  )
Run Code Online (Sandbox Code Playgroud)


小智 5

如果要禁用该对话框,请只写

window.onbeforeunload = function() { ... return; }

代替

window.onbeforeunload = function() { ... return ''; }

希望对您有帮助。