用JavaScript在页面卸载/关闭之前发送POST请求,这是否可能?

18

补充说明:我无法使用jQuery。我正在使用西门子S7控制器,它有一个微小的Web服务器,甚至不能处理80KB的jQuery文件,因此我只能使用本机Javascript。从这个链接Ajax request with JQuery on page unload中,我得知需要将请求同步而不是异步。是否可以使用本机Javascript完成?

我从这里复制了代码:JavaScript post request like a form submit

我想知道在使用jquery的beforeunload或unload关闭窗口/选项卡/离开站点时是否可以调用此代码。这应该是可能的,对吧?

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}
1个回答

11

这里是一个实现方法:

<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>

请注意,请求可能需要同步进行(使用 async=false 调用 request.open)。

另外需要注意的一点是:

如果客户端突然终止(例如,浏览器被关闭,或者使用“结束进程”或“关机”),则既不会触发 onunload 事件,也不会触发 onbeforeunload 事件,请求也不会发送到服务器。


5
现在这个功能在Chrome中被阻止了。对于简单的用例(例如从主要浏览器发布分析数据),可以使用navigator.sendBeacon()。 - zhark
1
注意:MDN文档明确建议不要在beforeunloadunload事件中使用sendBeacon - Alec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接