是否有任何跨浏览器的JavaScript/jQuery代码来检测浏览器或浏览器标签是否正在关闭,但不是由于链接被单击?


当前回答

onunload是Chrome的答案。根据caniuse它的交叉浏览器。但并非所有浏览器的反应都一样。

window.onunload = function(){
    alert("The window is closing now!");
}

developer.mozilla.org

这些事件在窗口卸载其内容和资源时触发。

铬:

Onunload只在页面关闭时执行。它甚至不会在页面刷新和导航到另一个页面时执行。

Firefox v86.0版本:

它根本不会执行。页面刷新,导航离开,关闭浏览器标签,关闭浏览器,什么都没有。

其他回答

$(window).unload( function () { alert("Bye now!"); } );

如果我没说错,你想知道什么时候一个标签/窗口是有效关闭的。好吧,在JavaScript中检测这个的唯一方法是使用onunload或onbeforeunload事件。

不幸的是(或幸运的是?),当您通过链接或浏览器的后退按钮离开网站时,这些事件也会被触发。这是我能给出的最好答案,我不认为你能在JavaScript中原生检测纯close。如果我说错了,请指正。

window.addEventListener("beforeunload", function (e) {
 var confirmationMessage = "tab close";

 (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
 sendkeylog(confirmationMessage);
 return confirmationMessage;                                //Webkit, Safari, Chrome etc.
}); 

Sorry, I was not able to add a comment to one of existing answers, but in case you wanted to implement a kind of warning dialog, I just wanted to mention that any event handler function has an argument - event. In your case you can call event.preventDefault() to disallow leaving the page automatically, then issue your own dialog. I consider this a way better option than using standard ugly and insecure alert(). I personally implemented my own set of dialog boxes based on kendoWindow object (Telerik's Kendo UI, which is almost fully open-sourced, except of kendoGrid and kendoEditor). You can also use dialog boxes from jQuery UI. Please note though, that such things are asynchronous, and you will need to bind a handler to onclick event of every button, but this is all quite easy to implement.

然而,我同意缺少真正的关闭事件是很糟糕的:例如,如果你想在真正关闭的情况下才在后端重置会话状态,这是一个问题。

onunload是Chrome的答案。根据caniuse它的交叉浏览器。但并非所有浏览器的反应都一样。

window.onunload = function(){
    alert("The window is closing now!");
}

developer.mozilla.org

这些事件在窗口卸载其内容和资源时触发。

铬:

Onunload只在页面关闭时执行。它甚至不会在页面刷新和导航到另一个页面时执行。

Firefox v86.0版本:

它根本不会执行。页面刷新,导航离开,关闭浏览器标签,关闭浏览器,什么都没有。