在Web浏览器中捕获选项卡关闭事件?

时间:2008-09-26 09:11:07

标签: asp-classic

有没有办法知道用户是否关闭了网络浏览器中的标签?特别是IE7,还有FireFox等。如果包含我们网站的当前选项卡关闭,我希望能够从我们的asp代码处理这种情况。

7 个答案:

答案 0 :(得分:6)

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.

因此,如果您在关闭选项卡或浏览器窗口时尝试注销用户,则每次单击链接或提交页面时,最终都会将其注销。

答案 1 :(得分:2)

附加“onbeforeunload”事件。它可以在浏览器/标签关闭之前执行代码。

答案 2 :(得分:1)

如果你的话,document.unload不会这样做吗?

答案 3 :(得分:0)

如果您需要知道服务器端的页面何时关闭,最好的办法是定期从页面ping服务器(例如,通过XMLHttpRequest)。当ping停止时,页面将关闭。如果浏览器崩溃,终止或计算机已关闭,这也可以使用。

答案 4 :(得分:0)

正如Eran Galperin建议的那样,使用onbeforeunload。特别是,返回一个字符串,该字符串将包含在一个确认对话框中,该对话框允许用户选择是否离开页面。每个浏览器在您返回的字符串之前和之后都包含一些文本,因此您应该在不同的浏览器中测试以查看用户将被呈现的内容。

答案 5 :(得分:0)

我确信OP正在从网页本身的上下文中询问,但对于遇到此问题的任何Firefox-addon开发人员,您可以使用TabClose事件。 https://developer.mozilla.org/en/Code_snippets/Tabbed_browser#Notification_when_a_tab_is_added_or_removed

答案 6 :(得分:0)

Santosh是对的,除了单击选项卡/浏览器的关闭按钮之外,此事件将在更多操作上触发。我已经创建了一个小hack来防止通过在文档就绪上添加以下函数来触发onb​​eforeunload操作。

       $(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?";       
    }
相关问题