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.