Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigator.sendBeacon not working with Authorization Headers

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

like image 418
Buzz Avatar asked Nov 16 '25 05:11

Buzz


1 Answers

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.
like image 74
rodiwa Avatar answered Nov 17 '25 22:11

rodiwa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!