Copyright © 2015 W3C® (MIT, ERCIM, Keio, Beihang). W3C liability, trademark and document use rules apply.
This specification defines an interface that web developers can use to schedule asynchronous and non-blocking delivery of data that minimizes resource contention with other time-critical operations, while ensuring that such requests are still processed and delivered to destination.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
The credential mode is now "include" instead of omit.
This document was published by the Web Performance Working Group as a Working Draft. This document is intended to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-web-perf@w3.org (subscribe, archives). All comments are welcome.
Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
This document is governed by the 1 September 2015 W3C Process Document.
This section is non-normative.
Web applications often need to issue requests that report events, state updates, and analytics to one or more servers. Such requests typically do not require response processing on the client (e.g. result in 204, or 200 HTTP response codes with an empty response body), and should not compete for network and compute resources with other high priority operations such as fetching critical resources, reacting to input, running animations, and so on. However, such one-way requests (beacons), are also responsible for delivering critical application and measurement data, forcing developers to use costly methods to ensure their delivery:
The mismatch between above delivery and processing requirements leaves most developers with a tough choice and widespread adoption of blocking techniques that hurt the user experience. This specification defines an interface that web developers can use to schedule asynchronous and non-blocking delivery of data that minimizes resource contention with other time-critical operations, while ensuring that such requests are still processed and delivered to destination:
The following example shows use of the sendBeacon
method to
deliver event, click, and analytics data:
<html> <script> // emit non-blocking beacon to record state update function reportEvent(eventData) { navigator.sendBeacon('/collector', eventData); } // emit non-blocking beacon to record click on a link function reportClick(url) { var clickData = JSON.stringify({ clickTo: url, clickAt: performance.now() }); navigator.sendBeacon('/collector', clickData); } // emit non-blocking beacon when page transitions to background state document.addEventListener('visibilitychange', function() { if (document.visiblityState === 'hidden') { var analyticsData = buildSessionReport(); navigator.sendBeacon('/collector', analyticsData); } }); </script> <body> <a href='http://www.w3.org/' onclick='reportClick(this)'> <button onclick="reportEvent('event!')">Click me</button> </body> </html>
Above example uses visibilitychange
event
defined in [PAGE-VISIBILITY] to trigger delivery of session data. This
event is the only event that is guaranteed to fire on mobile devices when
the page transitions to background state (e.g. when user switches to a
different application, goes to homescreen, etc), or is being unloaded.
Developers should avoid relying on unload
event because it
will not fire whenever a page in background state (i.e.
visiblityState
equal to hidden
) and the process
is terminated by the mobile OS.
The requests initiated via the sendBeacon
method do not
block or compete with time-critical work, may be prioritized by the user
agent to improve network efficiency, and eliminate the need to use blocking
operations to ensure delivery of beacon data.
What sendBeacon
does not do and is not intented to
solve:
sendBeacon
method does not provide special handling
for offline storage or delivery. A beacon request is like any other
request and may be combined with [SERVICE-WORKERS] to provide offline
functionality where necessary.sendBeacon
method is not intended to provide
background synchronization or transfer capabilities. The user agent is
allowed to restrict the maximum accepted payload size to ensure that
beacon requests are able to complete quickly and in a timely manner.All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in [RFC2119]. For readability, these words do not appear in all uppercase letters in this specification.
Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.
Some conformance requirements are phrased as requirements on attributes, methods or objects. Such requirements are to be interpreted as requirements on the user agent.
Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)
The following terms are defined in the DOM specification: [DOM]
SyntaxError
error nameThe following terms are defined in the HTML specification: [HTML5]
The following terms are defined in the HTML specification: [FETCH]
Origin
header flagThe following terms are defined in the File API specification: [FILEAPI]
The following terms are defined in the Typed Array specification: [TYPEDARRAY]
ArrayBufferView
interfaceArrayBuffer
interfaceThe following terms are defined in the URL specification: [URL]
The IDL fragments in this specification must be interpreted as required for conforming IDL fragments, as described in the Web IDL specification [WebIDL].
The following terms are defined in the Web IDL specification:
USVString
typeThe following term is defined in the XMLHttpRequest specification: [XMLHttpRequest]
FormData
interfacesendBeacon
MethodThe sendBeacon
method transmits data provided by the data
parameter to the URL provided by
the url
parameter, according to
the following rules:
data
size
to ensure that beacon requests are able to complete quickly and in a
timely manner.visiblityState
([PAGE-VISIBILITY]) transitions to hidden
, and must
allow all such requests to run to completion without blocking other
time-critical and high-priority work.url
The url
parameter indicates the URL where the data is
to be transmitted.
data
The data
parameter is the BodyInit data that is
to be transmitted.
The sendBeacon
method returns true if the user agent is able to successfully queue the
data for transfer. Otherwise it returns false.
If the user agent limits the amount of data that can be queued to be sent using this API and the size of data causes that limit to be exceeded, this method returns false. A return value of true implies the browser has queued the data for transfer. However, since the actual data transfer happens asynchronously, this method does not provide any information whether the data transfer has succeeded or not.
On calling the sendBeacon
method, the
following steps must be run:
Set requestTime to current time.
Set base to the entry settings object's API base URL.
Set origin to the entry settings object's origin.
Set referrer to the entry settings object's' API referrer source's URL if entry settings object's API referrer source is a document, and entry settings object's API referrer source otherwise
Set parsedUrl to the result of the URL parser
steps with url
and base. If the algorithm
returns an error, or if parsedUrl's scheme is not
"http" or "https", throw a
"SyntaxError
" exception and terminate these
steps.
If data is not null and if the user agent limits the amount of data that can be queued to be sent using this API and the size of data causes that limit to be exceeded, terminate these steps and set the return value to false.
If mimeType is not null, append a
Content-Type
header with value mimeType to
headerList. Append a Accept-Language
header
with an appropriate value to headerList. Append a
Accept
header with */*
as the value
to headerList.
sendBeacon()
call, but continue to runs the following
steps. These steps may be run even after the document has
unloaded.Let req be a new request, initialized as follows:
POST
Origin
header flag
Set age to current time minus requestTime
expressed in seconds. If age is non-zero, append a
Beacon-Age
header with value age
to header list field of req.
The Beacon-Age header field is used to communicate the time
delay, measured in seconds, between the time when the request is sent and
the requestTime set when sendBeacon
method is called. The
ABNF (Augmented Backus-Naur Form) syntax for the Beacon-Age header
field is as follows:
Beacon-Age = "Beacon-Age" ":" 1*DIGIT
This section is non-normative.
The sendBeacon
interface provides an asynchronous and
non-blocking mechanism for delivery of data. It is designed to eliminate
the need for the widespread use of expensive anti-patterns that block
user interaction, and to enable more efficient scheduling and use of
system resources. The same functionality is possible today, albeit with
high performance costs and degraged user experience.
sendBeacon
does not add new privacy considerations. However, implementers should take the following precautions:
The permanent message header field registry should be updated with the following registrations ([RFC3864]):
Sincere thanks to Jonas Sicking, Nick Doty, James Simonsen, William Chan, Jason Weber, Philippe Le Hegaret, Daniel Austin, Chase Douglas, and Anne van Kesteren for their helpful comments and contributions to this work.