是否有任何跨浏览器的JavaScript/jQuery代码来检测浏览器或浏览器标签是否正在关闭,但不是由于链接被单击?
当前回答
来自MDN文档
由于某些原因,基于webkit的浏览器不符合对话框的规范。一个几乎交叉工作的例子与下面的例子很接近。
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
本例处理所有浏览器。
其他回答
I have tried all above solutions, none of them really worked for me, specially because there are some Telerik components in my project which have 'Close' button for popup windows, and it calls 'beforeunload' event. Also, button selector does not work properly when you have Telerik grid in your page (I mean buttons inside the grid) So, I couldn't use any of above suggestions. Finally this is the solution worked for me. I have added an onUnload event on the body tag of _Layout.cshtml. Something like this:
<body onUnload="LogOff()">
然后添加LogOff函数重定向到Account/LogOff,这是Asp中的内置方法。净MVC。现在,当我关闭浏览器或选项卡,它重定向到LogOff方法和用户必须登录时返回。我已经在Chrome和Firefox中进行了测试。它确实有效!
function LogOff() {
$.ajax({
url: "/Account/LogOff",
success: function (result) {
}
});
}
window.onbeforeunload = function() {
console.log('event');
return false; //here also can be string, that will be shown to the user
}
它可以用来提醒用户是否有数据未保存或类似的事情。当标签页关闭或浏览器关闭或网页刷新时,此方法有效。
除非用户没有与网页进行交互,否则它不会工作,这是一种对抗恶意网站.....的机制除非你至少在网站窗口上点击或触摸,否则不会弹出窗口。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<textarea placeholder = "Write...."></textarea>
</form>
<script type="text/javascript">
window.addEventListener('beforeunload', function (e) {
e.returnValue = '';
});
</script>
</body>
</html>
我找到了一个方法,在我所有的浏览器上都能运行。
测试在以下版本: Firefox 57, Internet Explorer 11, Edge 41,最新的Chrome浏览器之一(无法显示我的版本)
注意:onbeforeunload火灾如果你离开页面以任何可能的方式(刷新,关闭浏览器,重定向,链接,提交..)。如果只希望它在浏览器关闭时发生,只需绑定事件处理程序。
$(document).ready(function(){
var validNavigation = false;
// Attach the event keypress to exclude the F5 refresh (includes normal refresh)
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
window.onbeforeunload = function() {
if (!validNavigation) {
// -------> code comes here
}
};
});
由于没有人提到它(8年多以后):WebSocket可以是检测关闭选项卡的另一种有效方法。只要选项卡打开并指向主机,客户端就能够保持到主机的活动WebSocket连接。
警告:请注意,这个解决方案只适用于WebSocket不需要任何额外的重大开销的项目。
在合理的超时时间内(例如2分钟),服务器端可以在WebSocket断开连接后确定客户端已经离开,并执行所需的任何操作,例如删除上传的临时文件。(在我非常专业的用例中,我的目标是在WebSocket连接断开和所有CGI/FastCGI活动终止三秒钟后终止本地主机应用服务器-任何其他保持活动的连接都不会影响我。)
我有问题让onunload事件处理程序正确地与信标一起工作(正如这个答案所推荐的)。关闭选项卡似乎不会触发信标,而打开选项卡则会以可能导致问题的方式触发信标。WebSocket更干净地解决了我遇到的问题,因为连接关闭的时间与选项卡关闭的时间大致相同,在应用程序中切换页面只是在延迟窗口内打开一个新的WebSocket连接。