有没有办法知道用户是否关闭了网络浏览器中的选项卡?特别是 IE7,还有 FireFox 等。如果包含我们网站的当前选项卡关闭,我希望能够从我们的 asp 代码中处理这种情况。
7 回答
onbeforeunload 还会在以下事件中被调用 -
* Close the current browser window.
* Navigate to another location by entering a new address or selecting a Favorite.
* Click the Back, Forward, Refresh, or Home button.
* Click an anchor that refers the browser to another Web page.
* Invoke the anchor.click method.
* Invoke the document.write method.
* Invoke the document.open method.
* Invoke the document.close method.
* Invoke the window.close method.
* Invoke the window.open method, providing the possible value _self for the window name.
* Invoke the window.navigate or NavigateAndFind method.
* Invoke the location.replace method.
* Invoke the location.reload method.
* Specify a new value for the location.href property.
* Submit a form to the address specified in the ACTION attribute via the INPUT type=submit control, or invoke the form.submit method.
因此,如果您在用户关闭选项卡或浏览器窗口时尝试注销用户,那么每次他们单击链接或提交页面时,您最终都会将他们注销。
附加一个“ onbeforeunload ”事件。它可以在浏览器/选项卡关闭之前执行代码。
如果你不这样做 document.unload 吗?
如果您需要知道页面何时在服务器端关闭,最好的办法是定期从页面 ping 服务器(XMLHttpRequest
例如,通过 )。当 ping 停止时,页面关闭。如果浏览器崩溃、被终止或计算机关闭,这也将起作用。
正如 Eran Galperin 建议的那样,使用onbeforeunload
. 特别是,返回一个字符串,该字符串将包含在确认对话框中,允许用户选择是否离开页面。每个浏览器在您返回的字符串之前和之后都包含一些文本,因此您应该在不同的浏览器中进行测试以查看用户会看到什么。
我确定 OP 是从网页本身的上下文中询问的,但是对于遇到此问题的任何 Firefox 插件开发人员,您可以使用该TabClose
事件。https://developer.mozilla.org/en/Code_snippets/Tabbed_browser#Notification_when_a_tab_is_added_or_removed
Santosh 是对的,此事件将在更多操作上触发,而不仅仅是单击选项卡/浏览器的关闭按钮。我创建了一个小技巧,以防止通过在文档就绪时添加以下功能来触发 onbeforeunload 操作。
$(function () {
window.onbeforeunload = OnBeforeUnload;
$(window).data('beforeunload', window.onbeforeunload);
$('body').delegate('a', 'hover', function (event) {
if (event.type === 'mouseenter' || event.type === "mouseover")
window.onbeforeunload = null;
else
window.onbeforeunload = $(window).data('beforeunload');
});
});
此外,在触发 Santosh 提到的任何事件之前,您需要运行以下行:
window.onbeforeunload = null;
如果您不希望触发事件。
这是最终的代码片段:
function OnBeforeUnload(oEvent) {
// return a string to show the warning message (not every browser will use this string in the dialog)
// or run the code you need when the user closes your page
return "Are you sure you want to close this window?";
}