You can’t use async/await or Promises in beforeunload
handlers.
Option 1: Use sendBeacon
+ server-side token recognition
If possible, send a token
or userId
as part of the payload (not header), e.g.:
navigator.sendBeacon('/api/unlock', JSON.stringify({ userId, token }));
Option 2: Use fetch with keepalive: true
(limited support):
fetch('/api/unlock', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer yourTokenHere'
},
body: JSON.stringify({ userId }),
keepalive: true
});enter image description here
enter image description here Summary