16

Added: I cannot use jQuery. I am using a Siemens S7 control unit which has a tiny webserver that cannot even handle a 80kB jQuery file, so I can only use native Javascript. from this link Ajax request with JQuery on page unload I get that I need to make the request synchronous instead of asynchronous. Can that be done with native Javascript?

I copied the code from here: JavaScript post request like a form submit

I was wondering if I could call this on closing the window/tab/leaving the site with jquery beforeunload or unload. Should be possible, right?

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();
}
Community
  • 1
  • 1
Coffeehouse
  • 485
  • 3
  • 15

1 Answers1

9

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.

barak manos
  • 27,530
  • 9
  • 49
  • 106
  • 5
    This is now [blocked in Chrome](https://www.chromestatus.com/feature/4664843055398912). For simple use cases (i.e. posting analytics from a major browser) you can now use navigator.sendBeacon(). – zhark Apr 25 '20 at 03:26
  • NB: The [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon) explicitly advise _against_ using `sendBeacon` with `beforeunload` and `unload` events – Alec Dec 18 '20 at 15:16