Abstract

This specification defines an interoperable means for site developers to asynchronously transfer small HTTP data from the User Agent to a web server.

Status of This Document

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.

Table of Contents

1. Introduction

This section is non-normative.

The Beacon specification defines an interface that web developers can use to asynchronously transfer small HTTP data from the User Agent to a web server.

The specification addresses the needs of analytics and diagnostics code that typically attempt to send data to a web server prior to the unloading of the document. Sending the data any sooner may result in a missed opportunity to gather data. However, ensuring that the data has been sent during the unloading of a document is something that has traditionally been difficult for developers.

User agents will typically ignore asynchronous XMLHttpRequests made in an unload handler. To solve this problem, analytics and diagnostics code will typically make a synchronous XMLHttpRequest in an unload or beforeunload handler to submit the data. The synchronous XMLHttpRequest forces the User Agent to delay unloading the document, and makes the next navigation appear to be slower. There is nothing the next page can do to avoid this perception of poor page load performance.

There are other techniques used to ensure that data is submitted. One such technique is to delay the unload in order to submit data by creating an Image element and setting its src attribute within the unload handler. As most user agents will delay the unload to complete the pending image load, data can be submitted during the unload. Another technique is to create a no-op loop for several seconds within the unload handler to delay the unload and submit data to a server.

Not only do these techniques represent poor coding patterns, some of them are unreliable and also result in the perception of poor page load performance for the next navigation.

The following example shows a theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unload of the page to be delayed.

Example 1
window.addEventListener('unload', logData, false);

function logData() {
    var client = new XMLHttpRequest();
    client.open("POST", "/log", false); // third parameter indicates sync xhr
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send(analyticsData);
}

Using the sendBeacon method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation.

The following example shows a theoretical analytics code pattern that submits data to a server using the by using the sendBeacon method.

Example 2
window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);
}

2. Conformance requirements

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 user agents.

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

2.1 Dependencies

DOM

The following terms are defined in the DOM specification: [DOM]

HTML5

The following terms are defined in the HTML specification: [HTML5]

Fetch

The following terms are defined in the HTML specification: [FETCH]

File API

The following terms are defined in the File API specification: [FILEAPI]

Typed Array

The following terms are defined in the Typed Array specification: [TYPEDARRAY]

URL

The following terms are defined in the URL specification: [URL]

Web IDL

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:

XMLHttpRequest

The following term is defined in the XMLHttpRequest specification: [XMLHttpRequest]

3. Beacon

3.1 Introduction

This section is non-normative.

This specification defines an interoperable means for site developers to asynchronously transfer small HTTP data from the User Agent to a web server.

3.2 sendBeacon Method

partial interface Navigator {
    boolean sendBeacon(USVString url, optional BodyInit? data = null);
};

partial interface WorkerNavigator {
    boolean sendBeacon(USVString url, optional BodyInit? data = null);
};

The sendBeacon method transmits data provided by the data parameter to the URL provided by the url parameter. User agents MUST ignore any entity bodies returned in the response. User agents MAY close the connection prematurely once they start receiving an entity body. The User Agent SHOULD transmit data at the earliest available opportunity, but MAY prioritize the transmission of data lower compared to other network traffic. The User Agent SHOULD make a best effort attempt to eventually transmit the data.

Parameters

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.

Return Value

The sendBeacon method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.

Note

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. The actual data transfer may occur after the page has unloaded. To be still an effective mechanism for developers, the User Agent should make the best effort to transmit the data including making multiple attempts to transmit the data in presence of transient network or server errors, even though it uses POST to transmit the data.

3.3 Processing Model

On calling the sendBeacon method, the following steps must be run:

  1. Set requestTime to current time.

  2. Set base to the entry settings object's API base URL.

  3. Set origin to the entry settings object's origin.

  4. 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

  5. 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.

  6. 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.

  7. Otherwise, create the following temporary variables:
    • Extract object's byte stream (transmittedData) and MIME type (mimeType).
    • Let headerList be null.
  8. 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.

  9. Set the return value to true and return the sendBeacon() call, but continue to runs the following steps. These steps may be run even after the document has unloaded.
  10. Let req be a new request, initialized as follows:

    method
    POST
    url
    parsedUrl
    header list
    headerList
    origin
    origin
    force Origin header flag
    set
    context
    beacon
    referrer
    referrer
    body
    transmittedData
    mode
    CORS
    credentials mode
    include
  11. 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.

  12. Fetch 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

3.4 Privacy

This section is non-normative.

This specification does not add extra security or privacy considerations in addition to the ones associated with forms submissions in HTML, as noted here.

3.5 IANA Considerations

The permanent message header field registry should be updated with the following registrations ([RFC3864]):

3.5.1 Beacon-Age

Header field name
Beacon-Age
Applicable protocol
http
Status
standard
Author/Change controller
W3C
Specification document
This specification (see Beacon-Age Header Field)

3.6 Acknowledgments

We would like to sincerely thank Jonas Sicking, Ilya Grigorik, James Simonsen, William Chan, Jason Weber, Philippe Le Hegaret, Daniel Austin, Chase Douglas, and others who have helped refine this specification to acknowledge their contributions to this work.

A. References

A.1 Normative references

[DOM]
Anne van Kesteren; Aryeh Gregor; Ms2ger; Alex Russell; Robin Berjon. W3C DOM4. 18 June 2015. W3C Last Call Working Draft. URL: http://www.w3.org/TR/dom/
[FETCH]
Anne van Kesteren. Fetch Standard. Living Standard. URL: https://fetch.spec.whatwg.org/
[FILEAPI]
Arun Ranganathan; Jonas Sicking. File API. 21 April 2015. W3C Working Draft. URL: http://www.w3.org/TR/FileAPI/
[HTML5]
Ian Hickson; Robin Berjon; Steve Faulkner; Travis Leithead; Erika Doyle Navara; Edward O'Connor; Silvia Pfeiffer. HTML5. 28 October 2014. W3C Recommendation. URL: http://www.w3.org/TR/html5/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[TYPEDARRAY]
David Herman; Kenneth Russell. Typed Array Specification. 26 June 2013. Khronos Working Draft. URL: https://www.khronos.org/registry/typedarray/specs/latest/
[URL]
Anne van Kesteren; Sam Ruby. URL. 9 December 2014. W3C Working Draft. URL: http://www.w3.org/TR/url-1/
[WebIDL]
Cameron McCormack; Boris Zbarsky. WebIDL Level 1. 4 August 2015. W3C Working Draft. URL: http://www.w3.org/TR/WebIDL-1/
[XMLHttpRequest]
Anne van Kesteren; Julian Aubourg; Jungkee Song; Hallvord Steen et al. XMLHttpRequest Level 1. 30 January 2014. W3C Working Draft. URL: http://www.w3.org/TR/XMLHttpRequest/

A.2 Informative references

[RFC3864]
G. Klyne; M. Nottingham; J. Mogul. Registration Procedures for Message Header Fields. September 2004. Best Current Practice. URL: https://tools.ietf.org/html/rfc3864