Beacon

Editor's Draft February 12, 2014

This version:
http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/Beacon/Overview.html
Latest published version:
http://www.w3.org/TR/beacon/
Editors:
Arvind Jain, Google Inc., <>
Jatinder Mann, Microsoft Corp., <> (Until February 2014)

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

This is an editor's draft and may change without any notices.

Please send comments to public-web-perf@w3.org (archived) with [Beacon] at the start of the subject line.

This document is produced by the Web Performance Working Group.

Table of Contents

  1. 1 Introduction
  2. 2 Conformance requirements
  3. 3 Terminology
  4. 4 Beacon
    1. 4.1 Introduction
    2. 4.2 sendBeacon Method
    3. 4.3 Processing Model
  5. 6 References
  6. Acknowledgements

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.

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.

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

The IDL fragments in this specification must be interpreted as required for conforming IDL fragments, as described in the Web IDL specification. [Web IDL]

3 Terminology

The construction "a Foo object", where Foo is actually an interface, is sometimes used instead of the more accurate "an object implementing the interface Foo".

The terms origin and same origin are defined by The HTTP Origin Header. [IETF RFC 6454]

4 Beacon

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

4.2 sendBeacon Method

partial interface Navigator {
    boolean sendBeacon(DOMString url, optional (ArrayBufferView or Blob or DOMString or FormData)? data = null);
};

partial interface WorkerNavigator {
    boolean sendBeacon(DOMString url, optional (ArrayBufferView or Blob or DOMString or FormData)? data = null);
};

The sendBeacon method MUST asynchronously transmit data provided by the data parameter to the resolved URL provided by the url parameter. The User Agent MUST use the POST HTTP method to fetch the url for transmitting the data. All relevant cookie headers MUST be included in the request. User agents MUST honor the HTTP headers (including, in particular, redirects and HTTP cookie headers), but 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. To avoid the target confusion security risk, the User Agent MUST NOT display HTTP authorization prompts as a result of a sendBeacon method call.

Parameters

url

The url parameter indicates the resolved URL where the data is to be transmitted.

data

The data parameter is the ArrayBufferView, Blob, DOMString, or FormData 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.

4.3 Processing Model

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

  1. Set base to the entry setting object's API base URL.

  2. Set source origin to the entry setting object's origin.

  3. Let url be a URL with character encoding UTF-8.

  4. Resolve url relative to base. If the algorithm returns an error, throw a "SyntaxError" exception and terminate these steps.

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

  6. Otherwise, create the following temporary variable and then follow the rules below: let encoding be null, mime type be null, and transmittedData be null.

    If data is a ArrayBuffer

    Let the transmittedData be the raw data represented by data.

    If data is a Blob

    If the object's type attribute is not the empty string let mime type be its value.

    Let transmittedData be the raw data represented by data.

    If data is a string

    Let encoding be UTF-8.

    Let mime type be "text/plain;charset=UTF-8".

    Let the transmittedData be data converted to Unicode and encoded as UTF-8.

    If data is a FormData

    Let transmittedData be the result of running the multipart/form-data encoding algorithm with data as form data set and with UTF-8 as the explicit character encoding.

    Let mime type be the concatenation of "multipart/form-data;", a U+0020 SPACE character, "boundary=", and the multipart/form-data boundary string generated by the multipart/form-data encoding algorithm.

  7. 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.
  8. If url is of the same origin as base, fetch url from the base origin using the POST HTTP method with transmittedData, encoding, and mime type.

    Otherwise, make a cross-origin request to url, using the POST HTTP method with transmittedData, encoding, and mime type.

6 References

[CORS]
Cross-Origin Resource Sharing, Anne van Kesteren, Editor. World Wide Web Consortium, January 2013. This version of the CORS specification is available from http://www.w3.org/TR/cors/.
[DOM]
DOM4, Anne van Kesteren, Editor. World Wide Web Consortium, December 2012. This version of the DOM4 specification is available from http://www.w3.org/TR/dom/.
[IETF RFC 2119]
Key words for use in RFCs to Indicate Requirement Levels, Scott Bradner, Author. Internet Engineering Task Force, March 1997. Available at http://www.ietf.org/rfc/rfc2119.txt.
[IETF RFC 6454]
The Web Origin Concept, Adam Barth, Author. Internet Engineering Task Force, December 2011. Available at http://www.ietf.org/rfc/rfc6454.txt.
[HTML5]
HTML5, Robin Berjon, et al, Editors. World Wide Web Consortium, August 2013. This version of the HTML5 is available from http://www.w3.org/TR/html5/. The latest editor's draft of the HTML is available from latest editor's draft is available at http://www.w3.org/html/wg/drafts/html/master/.
[XMLHttpRequest]
XMLHttpRequest, Anne van Kesteren, Author. World Wide Web Consortium, December 2012. This version of the XMLHttpRequest specification is http://www.w3.org/TR/XMLHttpRequest/. The latest version of XMLHttpRequest is available at http://www.w3.org/TR/XMLHttpRequest/.
[Web IDL]
Web IDL, Cameron McCormack, Editor. World Wide Web Consortium, April 2012. This version of the Web IDL specification is available from http://www.w3.org/TR/2012/CR-WebIDL-20120419/. The latest version of Web IDL is available at http://www.w3.org/TR/WebIDL/.
[TYPEDARRAY]
Typed Array, David Herman and Kenneth Russell. Khronos.

Acknowledgements

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.