HTTP request beforeunload: sendBeacon vs img.src
Asked Answered
M

1

16

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?

Myopic answered 29/3, 2019 at 16:11 Comment(0)
A
11

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

Anvers answered 30/3, 2019 at 19:39 Comment(4)
What's the relation of img.src to sendBeacon, specifically regarding keepalive and its usefulness during page unload?Myopic
Legacy behavior that likely cannot be removed.Anvers
Sounds like you're saying that img.src and sendBeacon are indeed functionally equivalent in the context of beforeunload handlers. Mind explicitly confirming this and editing your answer as such?Myopic
As img isn't completely ratified as such, it's not clear to me it's safe to assume it will always be the same going forward.Anvers

© 2022 - 2024 — McMap. All rights reserved.