是否有任何跨浏览器的JavaScript/jQuery代码来检测浏览器或浏览器标签是否正在关闭,但不是由于链接被单击?
当前回答
window.onbeforeunload = function() {
console.log('event');
return false; //here also can be string, that will be shown to the user
}
其他回答
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "tab close";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
sendkeylog(confirmationMessage);
return confirmationMessage; //Webkit, Safari, Chrome etc.
});
如果我没说错,你想知道什么时候一个标签/窗口是有效关闭的。好吧,在JavaScript中检测这个的唯一方法是使用onunload或onbeforeunload事件。
不幸的是(或幸运的是?),当您通过链接或浏览器的后退按钮离开网站时,这些事件也会被触发。这是我能给出的最好答案,我不认为你能在JavaScript中原生检测纯close。如果我说错了,请指正。
在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?";
};
onunload是Chrome的答案。根据caniuse它的交叉浏览器。但并非所有浏览器的反应都一样。
window.onunload = function(){
alert("The window is closing now!");
}
developer.mozilla.org
这些事件在窗口卸载其内容和资源时触发。
铬:
Onunload只在页面关闭时执行。它甚至不会在页面刷新和导航到另一个页面时执行。
Firefox v86.0版本:
它根本不会执行。页面刷新,导航离开,关闭浏览器标签,关闭浏览器,什么都没有。