30

我对我的申请有疑问。每当用户意外关闭浏览器窗口时,我都想在此之前进行一些清理操作。我使用过 onunload 事件,但问题是这个事件有时会触发,有时不会。我该怎么办,有没有更好的方法来处理这类问题。

4

6 回答 6

35
window.onbeforeunload = function() {
    return 'You have unsaved changes!';
}

请参阅关于 onbeforeunload 的 MSDN 文章

SO中也有类似的问题

于 2009-08-13T06:54:52.083 回答
7

尝试:

window.onbeforeunload = function() { ...your code... }
于 2009-08-13T06:52:12.133 回答
4

根据我的经验,onunload 在不同的浏览器中的工作方式不同。为什么不使用另一个名为 onbeforeunload 的事件处理程序。它应该工作。Onbeforeunload 将在窗口关闭之前首先执行,这样应该可以解决您的问题。

于 2009-08-13T06:50:04.587 回答
4

这有效:

window.onbeforeunload = function(){
    console.log('closing shared worker port...');
    return 'Take care now, bye-bye then.';
  };

例如,如果您正在使用 SharedWorkers 并且您需要告诉工作人员少一个端口要管理,这会很方便——否则,您最终可能会刷新一个浏览器选项卡并获得类似“成功连接: 10 个其他选项卡”,因为一个选项卡使工作人员保持活动状态,而另一个选项卡的刷新不断将新端口连接推送到您的阵列。

希望这可以帮助。

于 2013-07-23T06:32:54.857 回答
2

由于安全原因,这是不允许的。onbeforeunload 是一个浏览器 API,在不同的浏览器上有不同的行为。

于 2015-10-05T08:40:53.190 回答
1

这是我的答案之一,只有当用户想要关闭窗口并在某种程度上劫持浏览器消息时才给你 onbeforeunload .....

<html>
<head>
<script src='http://code.jquery.com/jquery-1.6.2.min.js'></script> <!--this is get jquery header file its not required but i have used jquery for minor correction-->
<script type="text/javascript" src="http://fbug.googlecode.com/svn/lite/branches/firebug1.4/content/firebug-lite-dev.js"></script><!--this will give a firebug to check the console in IE-->
<script language='javascript'>
window.onbeforeunload = function(evt){
  var message = "";
  var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;  //validating the browser where its chrome or not
  if(is_chrome){
    message = "Do you want to close the browser or not?";
  }
  if(this.flag == 1 || $('#help').css('background-color') == 'red'){
    console.log("red");
    return message;
  } else { console.log("blue"); return NULL;}
}
function change(){
  $('#help').css('background-color','red');
  this.flag = 1;
}
</script>

</head>
<body> 
  <a id='help' onclick=change() title="please click on Links">Links</a> 
</body>
</html>

我认为它可能对任何身体都有用谢谢.....

于 2011-07-23T03:33:26.450 回答