如何检测浏览器窗口/标签关闭事件? [英] How to Detect Browser Window /Tab Close Event?

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

问题描述

我与onbeforeunload尝试,和卸载功能。但是,这是行不通的。当点击一个链接或还有提神醒脑此事件被触发。我要当一个浏览器窗口或标签被关闭了时才会触发事件。在code必须在所有浏览器。

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

我使用的继母版code。

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>

在我的身体标记:

and in my body tag:

以上code工作在IE浏览器,但不是在铬...

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

推荐答案

这code prevents的复选框事件。当用户点击浏览器的关闭按钮,但点击复选框不起作用它的工作原理。你可以修改它其他控件(texbox,单选按钮等)

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 () { };
        });
    });

这篇关于如何检测浏览器窗口/标签关闭事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆