In the context of a beforeunload
handler, what is the functional difference between fetch(keep-alive: true)
and setting the src
attribute of an img
tag, and which of these is the preferred method for making GET requests?
Background:
I want to send an HTTP GET request in a beforeunload
handler in JavaScript code. Navigator.sendBeacon
's documentation discusses how good it is for this use case, but
The sendBeacon() method does not provide ability to customize the request method
Apparently there were a lot of requests for such functionality a few years ago, which culminated in the recommendation to use fetch()
, the browser method called internally by sendBeacon
, with some specific flags set to solve the unload
request problem:
Applications that require non-default settings for such requests should use the
FETCH
API with keep-alive flag set to true
fetch(url, {
method: ...,
body: ...,
headers: ...,
credentials: 'include',
mode: 'cors',
keep-alive: true,
})
As far as I can tell, this type of call would be functionally equivalent to Navigator.sendBeacon
, the key setting being keep-alive: true
.
Apparently the HTML <img>
tag also uses keep-alive: true
according to the spec (emphasis mine):
A request has an associated keepalive flag...This can be used to allow the request to outlive the environment settings object, e.g., navigator.sendBeacon and the HTML img element set this flag
My understanding of this documentation is that making a GET
request on unload
via an img
element's src
attribute is functionally equivalent to calling fetch()
with keep-alive: true
, which is itself functionally equivalent to calling sendBeacon
(if sendBeacon
could make GET
requests).
Is this accurate?
sendBeacon is particularly useful if you want to send a small amount of data and do not particularly care about a response. navigator. sendBeacon(url, data); One of — if not the — main use for sendBeacon is to solve the issue of asynchronous requests being cancelled by the browser.
sendBeacon() method asynchronously sends an HTTP POST request containing a small amount of data to a web server. It's intended to be used for sending analytics data to a web server, and avoids some of the problems with legacy techniques for sending analytics, such as the use of XMLHttpRequest .
The Beacon API is used to send an asynchronous and non-blocking request to a web server. The request does not expect a response. Unlike requests made using XMLHttpRequest or the Fetch API, the browser guarantees to initiate beacon requests before the page is unloaded and to run them to completion.
As per https://fetch.spec.whatwg.org/#request-class it's keepalive
, not keep-alive
.
Other than that, yes. This feature was added to fetch()
to obsolete the need for sendBeacon()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With