The navigator.sendBeacon()
method asynchronously sends a small amount of data over HTTP to a web server.
Syntax
navigator.sendBeacon(url, data);
Parameters
url
- The URL that will receive the data. Can be relative or absolute.
data
- A
ArrayBuffer
,ArrayBufferView
,Blob
,DOMString
,FormData
, orURLSearchParams
object containing the data to send.
Return values
The sendBeacon()
method returns true
if the user agent successfully queued the data
for transfer. Otherwise, it returns false
.
Description
This method is for analytics and diagnostics that send data to a server before the document is unloaded, where sending the data any sooner may miss some possible data collection. For example, which link the user clicked before navigating away and unloading the page.
Ensuring that data has been sent during the unloading of a document has traditionally been difficult, because user agents typically ignore asynchronous XMLHttpRequest
s made in an unload
handler.
Historically, this was addressed with some of the following workarounds to delay the page unload long enough to send data to some URL:
- Submitting the data with a blocking synchronous
XMLHttpRequest
call inunload
orbeforeunload
event handlers. - Creating an
<img>
element and setting itssrc
in theunload
handler. Most user agents will delay the unload to load the image. - Creating a no-op loop for several seconds in the
unload
handler.
All of these methods block unloading the document, which slows down the next navigation. There is nothing the next page can do to avoid this, so the new page seems slow, even though it's the previous page's fault.
The following example shows theoretical analytics code that attempts to submit data to a server with a synchronous XMLHttpRequest
in an unload
handler. This results in the next page load to be delayed.
window.addEventListener("unload", function logData() { var xhr = new XMLHttpRequest(); xhr.open("POST", "/log", false); // third parameter of `false` means synchronous xhr.send(analyticsData); });
This is what sendBeacon()
replaces. With the sendBeacon()
method, the data is transmitted asynchronously when the User Agent has an opportunity to do so, without delaying unload or the next navigation. This solves all of the problems with submission of analytics data:
- The data is sent reliably
- It's sent asynchronously
- It doesn't impact the loading of the next page
- In addition, the code is simpler to write than any of the older techniques!
The following example shows a theoretical analytics code pattern that submits data to a server using the sendBeacon()
method.
window.addEventListener("unload", function logData() { navigator.sendBeacon("/log", analyticsData); });
The beacon sends an HTTP request via the POST method, with all relevant cookies available when called.
Specifications
Specification | Status | Comment |
---|---|---|
Beacon The definition of 'sendBeacon()' in that specification. |
Candidate Recommendation | Initial definition |