Use Case:
I want to trigger an reliably POST Request to my backend when the user is closing the browser. Only an successful request. I don't need response code or similiar. Important: No noticable delay for the user experience.
My Code:
window.onbeforeunload = function () {
var async = true;
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open('POST', URL, async);
xmlHttpRequest.setRequestHeader(HEADERS);
xmlHttpRequest.send(CONTENT);
var start = new Date().getTime();
while (new Date().getTime() < start + 500) {
}
};
My observations:
On my systems the code works "reliably" in Chrome and Edge Browser but in FireFox and IE only partially.
My questions:
1. Are my observations coincidence?
2. What happens in the code above under the hood (EventLoop etc.) and when will the Request triggerd?
3. Are there reliably alternatives?
BTW: Sync XMLHttpRequest is no option because sends() waits so long until server response is available.