Browsers now offer the Fetch API, which you can make network requests from JavaScript like this:
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();
What happens if the user closes the tab between the call to fetch
and the fulfilment of the promise? Will the browser drop the request? What if the call to fetch
happens in the unload
or beforeunload
events?
I know sendBeacon
is the API call that is meant for this purpose, but I am wondering if sendBeacon
is obsolete now that we have fetch
.
Have a look at the keepalive
option of fetch
:
The
keepalive
option can be used to allow the request to outlive the page. Fetch with thekeepalive
flag is a replacement for theNavigator.sendBeacon()
API.
Here is an example:
await fetch("/example", {keepalive: true});
Requests sent with fetch
and the keepalive
option get a high priority compared to requests sent with navigator.sendBeacon
. The fetch
API is also much more flexible and provides more options. Without keepalive
, there is no guarantee that the request will be completed if the user closes the page.
fetch()
on MDN