Search code examples
javascripthttpbrowseranalyticssendbeacon

HTTP request beforeunload: sendBeacon vs img.src


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?


Solution

  • 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().