Sending a post Request with Javascript on unload/beforeunload. Is that possible? [duplicate]

浪尽此生 提交于 2019-11-30 11:42:44

Here is one way to do it:

<body onunload="Exit()" onbeforeunload="Exit()">
    <script type="text/javascript">
        function Exit()
        {
            Stop();
            document.body.onunload       = "";
            document.body.onbeforeunload = "";
            // Make sure it is not sent twice
        }
        function Stop()
        {
            var request = new XMLHttpRequest();
            request.open("POST","some_path",false);
            request.setRequestHeader("content-type","application/x-www-form-urlencoded");
            request.send("some_arg="+some_arg);
        }
    </script>
</body>

Note that the request probably has to be synchronous (call request.open with async=false).

One additional notable point of attention:

If the client is terminated abruptly (e.g., browser is closed with "End Process" or "Power Down"), then neither the onunload event nor the onbeforeunload will be triggered, and the request will not be sent to the server.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!