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

Kub*_*ran 24 javascript asp.net session

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

我在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>
Run Code Online (Sandbox Code Playgroud)

并在我的身体标签:

以上代码适用于IE但不适用于Chrome ...

小智 21

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

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

    $(function () {
        $('input[type="checkbox"]').click(function () {
            window.onbeforeunload = function () { };
        });
    });
Run Code Online (Sandbox Code Playgroud)

  • 在刷新也警告称....任何想要排除刷新事件的想法 (2认同)

ras*_*usx 17

您无法使用javascript检测到它.

只检测页面卸载/关闭的事件是window.onbeforeunloadwindow.unload.这些事件都不能告诉您关闭页面的方式.