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
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
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)Use fetch()
API +keepalive
flag - but this again works if you request headers are on the CORS-safelist. Basically if yourfetch()
request has certain request headers, then a preflight request can be made for security reasons. If such a preflight request is made, then thefetch()
+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 acontent-type=application/json
here. One workaround for this is to send data astext/plain
and get your server to handle it accordingly. Some more info on CORS simple vs preflight requests can be found here.