如何检测浏览器窗口/选项卡关闭事件?

How to Detect Browser Window /Tab Close Event?(如何检测浏览器窗口/选项卡关闭事件?)

本文介绍了如何检测浏览器窗口/选项卡关闭事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 onbeforeunload 和 Unload 功能.但它没有用.单击链接或刷新时,会触发此事件.我想要一个仅在浏览器窗口或选项卡关闭时触发的事件.该代码必须适用于所有浏览器.

I am Trying with onbeforeunload, and Unload function. But it didn't work. When clicking a link or refreshing, this event got triggered. I want an event that is triggered only when a browser window or tab is closed. The code must work in all browsers.

我在 Masterpage 中使用以下代码.

I am using Following code in Masterpage.

<script type="text/jscript">

    var leaving = true;
    var isClose = false;

    function EndChatSession() {
        var request = GetRequest();
        request.open("GET", "../Chat.aspx", true);
        request.send();
    }
    document.onkeydown = checkKeycode
    function checkKeycode(e) {
        var keycode;
        if (window.event)
            keycode = window.event.keyCode;
        else if (e)
            keycode = e.which;
        if (keycode == 116) {
            isClose = true;
        }
    }
    function somefunction() {
        isClose = true;
    }
    window.onbeforeunload = function (e) {
       if (!e) e = event;
        if (leaving) {
             EndChatSession();
             e.returnValue = "Are You Sure";

        }
    }
    function GetRequest() {
        var xmlHttp = null;
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        }
        catch (e) {
            //Internet Explorer
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return xmlHttp;
    }    
</script>

在我的身体标签中:

以上代码在 IE 中有效,但在 chrome 中无效...

The Above code works in IE but not in chrome...

推荐答案

此代码可防止复选框事件.它在用户单击浏览器关闭按钮时起作用,但在单击复选框时不起作用.您可以为其他控件(texbox、radiobutton 等)修改它

This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)

    window.onbeforeunload = function () {
        return "Are you sure?";
    }

    $(function () {
        $('input[type="checkbox"]').click(function () {
            window.onbeforeunload = function () { };
        });
    });

这篇关于如何检测浏览器窗口/选项卡关闭事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何检测浏览器窗口/选项卡关闭事件?

基础教程推荐