Sending A Post Request With Javascript On Unload/beforeunload. Is That Possible?
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 th
Solution 1:
Here is one way to do it:
<bodyonunload="Exit()"onbeforeunload="Exit()"><scripttype="text/javascript">functionExit()
{
Stop();
document.body.onunload = "";
document.body.onbeforeunload = "";
// Make sure it is not sent twice
}
functionStop()
{
var request = newXMLHttpRequest();
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.
Post a Comment for "Sending A Post Request With Javascript On Unload/beforeunload. Is That Possible?"