Skip to content

Instantly share code, notes, and snippets.

@paulcollett
Last active January 16, 2023 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulcollett/a9294ab8290626cad2e2cee9b45fa1b3 to your computer and use it in GitHub Desktop.
Save paulcollett/a9294ab8290626cad2e2cee9b45fa1b3 to your computer and use it in GitHub Desktop.
Fetch "keepalive" Javascript Web feature detection

Fetch "keepalive" Javascript Web feature detection

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.

Current Support

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

Feature detection

const isFetchKeepaliveSupported = 'keepalive' in new Request('file:///')

Usage with fallback for Firefox

// 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)
}

See Also

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment