我有一个关于应用程序的查询。每当用户意外关闭浏览器窗口时,我希望在此之前进行一些清理操作。我已经使用了onunload事件,但问题是该事件有时会触发,有时不会触发。我该怎么办?有更好的方式来处理这种类型的问题吗。
我有一个关于应用程序的查询。每当用户意外关闭浏览器窗口时,我希望在此之前进行一些清理操作。我已经使用了onunload事件,但问题是该事件有时会触发,有时不会触发。我该怎么办?有更好的方式来处理这种类型的问题吗。
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
请参考 MSDN 关于 onbeforeunload 的文章
此外,SO 上也有一个类似的问题
尝试:
window.onbeforeunload = function() { ...your code... }
这是可行的:
window.onbeforeunload = function(){
console.log('closing shared worker port...');
return 'Take care now, bye-bye then.';
};
根据我的经验,onunload在不同的浏览器中有不同的工作方式。为什么不使用另一个事件处理程序称为onbeforeunload呢?它应该可以解决你的问题。onbeforeunload会在窗口关闭之前首先执行,因此应该可以解决你的问题。
由于安全原因,不允许这样做。onbeforeunload是一个浏览器API,在不同的浏览器上有不同的行为。
这是我的一个答案,只在用户想要关闭窗口并且为一定程度上劫持浏览器消息时才提供 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>
我认为这可能对任何人都有用,谢谢.....