2

Recently chrome stop support for synchronos xmlhttprequest on page unload or beforeunload event https://www.chromestatus.com/feature/4664843055398912

i try this solution Perform an asynchronous service get when closing browser window / tab with Angular but not seems to be working in latest chrome versions

Now i am using navigator.sendbeacon api like this

let headers = {
       type: 'application/json; charset=utf-8',
       'authorization': `bearer ${token}`
  }
   let blob = new blob([json.stringify({a:"9"})], headers);

    navigator.sendbeacon(uri, blob);

Api is throwing 401 so seems like authorization is not working, Is there any other alternative to navigator.sendBeacon

Buzz
  • 6,030
  • 4
  • 33
  • 47
  • Eagerly waiting for this feature- HTTP header to be available so that it can be adapted in [timeonsite JS](https://saleemkce.github.io/timeonsite) tracker. Will browser vendors facilitate it early; it's already been long 2 years post COVID? – webblover Jun 22 '22 at 07:37

1 Answers1

3

At time of this writing, no. Chrome (and probably other browsers too more sooner than later) will disallow XHR-sync because of bad UX to the user (the browser hangs if user is closing the tab and an XHR-sync request is made).

There are a few workarounds though, but each have their drawbacks as well

  1. Use the new (and experimental) sendBeacon API - sendBeacon simply "queues" the request and this guarantees that the request will be fired even on page unload. That too without blocking the UX. Some limitations with this are that you cannot change request headers by default. If you DO need to add custom headers, you will have to use a blob, and that too the headers should be CORS-friendly. And will not work on older browsers (looking at you, IE)
  2. Use fetch() API + keepalive flag - but this again works if you request headers are on the CORS-safelist. Basically if your fetch() request has certain request headers, then a preflight request can be made for security reasons. If such a preflight request is made, then the fetch() + keepalive is disallowed by some browsers. Basically you need to keep your request simple for this to work. For example, Such as you cannot use a content-type=application/json here. One workaround for this is to send data as text/plain and get your server to handle it accordingly. Some more info on CORS simple vs preflight requests can be found here.
  3. Chrome does allow a temporary workaround but this will work only till Oct 2020. More info on that here.
rodiwa
  • 1,690
  • 2
  • 17
  • 35