I've seen quite a few docs/articles suggesting that fetch
with the keepAlive
flag is equivalent to sendBeacon
.
fetch('/track', {
method: 'POST',
body: getData(),
keepalive: true,
});
// Same as
navigator.sendBeacon('/track', getData());
However, sendBeacon
actually returns a Promise<Boolean>
. According to the MDN docs:
The sendBeacon() method returns true if the user agent successfully queued the data for transfer. Otherwise, it returns false
Is there a way to mimic this with a fetch call? A fetch call always returns a Promise<Response>
. So the return value is not identical. Is there a way to make a fetch call return true
or false
based on the same "data queue" heuristic as sendBeacon
? Traditionally sendBeacon
is not concerned with the response, only whether or not the data was emitted or not.