fetch()
's keepalive is a new option parameter in Web API spec to replace the Navigator.sendBeacon()
API for usecases where requests should outlive the current page, like tracking clicks.
This new fetch option is supported in all modern browsers except Firefox (at time of writing, Firefox 110):
https://caniuse.com/mdn-api_request_keepalive
const isFetchKeepaliveSupported = 'keepalive' in new Request('file:///')
// Fetch with the keepalive flag is a replacement for the Navigator.sendBeacon() API
if(isFetchKeepaliveSupported) {
fetch(myUrl, {
method: 'post',
body: payload,
keepalive: true // The keepalive option can be used to allow the request to outlive the page.
})
} else {
// if sendBeacon request was "queued" to send by the browser it will return true
navigator.sendBeacon(myUrl, payload)
}