1

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.

Räuber
  • 11
  • 2
  • 1
    This seems like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378). Why do you need a post request when the tab is closed? What is the problem you are trying to solve? – VLAZ Oct 27 '19 at 07:40
  • I want to send some informations from the current state of my app. My problem is that my code not works reliably. I search an answer for this, can it even work?, and what happens unter the hood to understand why is that so? – Räuber Oct 27 '19 at 07:48
  • 1
    use the [Beacon API](https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API) if available – Bravo Oct 27 '19 at 07:50
  • Beacon API is unfortunately too limited. No custom headers e.g. ;-(. – Räuber Oct 27 '19 at 07:56
  • 1
    then you're out of luck - change the backend to work without the custom headers – Bravo Oct 27 '19 at 07:56

1 Answers1

0

After a little recherche i think i understand what happens under the hood. The reason that my code sometimes runs reliably is only luck. The async code comes in the callback queue and maybe the JavaScript interpreter has time for execute it or not. See also here: What are the limitation using before unload event?

For my use case i have also found informations. For this it gives 2 alternatives:

  1. Yes, BeaconAPI but with limitation (e.g. Custom Headers)
  2. Fetch keep-alive, but also with limitation (e.g. no IE or Safari) and in my case no Chrome because no preflight support (https://bugs.chromium.org/p/chromium/issues/detail?id=835821#c1)
Räuber
  • 11
  • 2