JavaScript监听浏览器窗口关闭事件

有个需求,在用户关闭浏览器窗口的时候稍作挽留一下,或者后台发个ajax到服务器。

网上许多方法试过都不能用了,各种测了之后,使用“添加事件”的方式成功在浏览器关闭窗口的时候监听并发送了ajax。

下面是代码

<!DOCTYPE HTML>
<html>

    <head>
        <meta charset="UTF-8">
        <title>colse ajax test</title> 
        <script type="text/javascript">

            //ajax
            function add() {
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                    }
                }
                xmlhttp.open("POST", "http://10.1.2.48:5000/marslite/close.do");
                xmlhttp.send();
            }

            //监听浏览器窗口关闭事件
            window.addEventListener("beforeunload", function (event) {
                // Cancel the event as stated by the standard.
                event.preventDefault();
                // Chrome requires returnValue to be set.
                event.returnValue = '??';
                add();
            });

        </script>

    </head>

    <body>
        <button onclick="add()">Add</button>
    </body>

</html>

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注