是否有任何跨浏览器的JavaScript/jQuery代码来检测浏览器或浏览器标签是否正在关闭,但不是由于链接被单击?
当前回答
在window的帮助下可以检查。在'unload'事件的事件处理程序中关闭,但超时使用是必需的(所以结果不能保证如果SMTH延迟或阻止窗口关闭):
JSFiddle的例子(测试在最新的Safari, FF, Chrome, Edge和IE11)
var win = window.open('', '', 'width=200,height=50,left=200,top=50');
win.document.write(`<html>
<head><title>CHILD WINDOW/TAB</title></head>
<body><h2>CHILD WINDOW/TAB</h2></body>
</html>`);
win.addEventListener('load',() => {
document.querySelector('.status').innerHTML += '<p>Child was loaded!</p>';
});
win.addEventListener('unload',() => {
document.querySelector('.status').innerHTML += '<p>Child was unloaded!</p>';
setTimeout(()=>{
document.querySelector('.status').innerHTML += getChildWindowStatus();
},1000);
});
win.document.close()
document.querySelector('.check-child-window').onclick = ()=> {
alert(getChildWindowStatus());
}
function getChildWindowStatus() {
if (win.closed) {
return 'Child window has been closed!';
} else {
return 'Child window has not been closed!';
}
}
其他回答
简单的解决方案
window.onbeforeunload = function () {
return "Do you really want to close?";
};
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>
来自MDN文档
由于某些原因,基于webkit的浏览器不符合对话框的规范。一个几乎交叉工作的例子与下面的例子很接近。
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
本例处理所有浏览器。
onunload是Chrome的答案。根据caniuse它的交叉浏览器。但并非所有浏览器的反应都一样。
window.onunload = function(){
alert("The window is closing now!");
}
developer.mozilla.org
这些事件在窗口卸载其内容和资源时触发。
铬:
Onunload只在页面关闭时执行。它甚至不会在页面刷新和导航到另一个页面时执行。
Firefox v86.0版本:
它根本不会执行。页面刷新,导航离开,关闭浏览器标签,关闭浏览器,什么都没有。