Movatterモバイル変換


[0]ホーム

URL:


W3C

Beacon

W3C Candidate Recommendation Draft

More details about this document
This version:
https://www.w3.org/TR/2022/CRD-beacon-20220803/
Latest published version:
https://www.w3.org/TR/beacon/
Latest editor's draft:
https://w3c.github.io/beacon/
History:
https://www.w3.org/standards/history/beacon
Commit history
Test suite:
https://w3c-test.org/beacon/
Implementation report:
https://w3c.github.io/test-results/beacon/
Editors:
Ilya Grigorik (Shopify)
Alois Reitbauer (Compuware Corp.)
Former editors:
Arvind Jain (Google Inc.) - Until
Jatinder Mann (Microsoft Corp.) - Until
Feedback:
GitHub w3c/beacon (pull requests,new issue,open issues)
public-web-perf@w3.org with subject line[beacon]… message topic … (archives)
Implementation
Can I use Beacon?

Copyright © 2022W3C® (MIT,ERCIM,Keio,Beihang). W3Cliability,trademark andpermissive document license rules apply.


Abstract

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.

Status of This Document

This section describes the status of this document at the time of its publication. A list of currentW3C publications and the latest revision of this technical report can be found in theW3C technical reports index at https://www.w3.org/TR/.

This document was published by theWeb Performance Working Group as a Candidate Recommendation Draft using theRecommendation track.

Publication as a Candidate Recommendation does not imply endorsement byW3C and its Members. A Candidate Recommendation Draft integrates changes from the previous Candidate Recommendation that the Working Group intends to include in a subsequent Candidate Recommendation Snapshot.

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 theW3C Patent Policy.W3C maintains apublic 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 containsEssential Claim(s) must disclose the information in accordance withsection 6 of theW3C Patent Policy.

This document is governed by the2 November 2021W3C Process Document.

1.Introduction

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 thesendBeacon() method to deliver event, click, and analytics data:

Example 1
<html><script>// emit non-blocking beacon to record client-side eventfunctionreportEvent(event){var data =JSON.stringify({event: event,time: performance.now()    });    navigator.sendBeacon('/collector', data);  }// emit non-blocking beacon with session analytics as the page// transitions to background state (Page Visibility API)document.addEventListener('visibilitychange',function(){if (document.visibilityState ==='hidden') {var sessionData = buildSessionReport();      navigator.sendBeacon('/collector', sessionData);    }  });</script><body><ahref='http://www.w3.org/'onclick='reportEvent(this)'><buttononclick="reportEvent('some event')">Click me</button></body></html>
Note

Above example usesvisibilitychange event defined in [PAGE-VISIBILITY-2] 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 onunload event because it will not fire whenever a page is in a background state (i.e.visibilityState equal tohidden and the process is terminated by the mobile OS.

The requests initiated via thesendBeacon() 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.

WhatsendBeacon() does not do and is not intended to solve:

2.Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key wordsMAY,MUST,SHOULD, andSHOULD NOT in this document are to be interpreted as described inBCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.

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

3.Beacon

3.1sendBeacon() Method

WebIDLpartial interfaceNavigator {booleansendBeacon(USVStringurl, optionalBodyInit?data = null);};

ThesendBeacon() method transmits data provided by thedata parameter to the URL provided by theurl parameter:

Note
Beacon API does not provide a response callback. The server is encouraged to omit returning a response body for such requests (e.g. respond with204 No Content).

Parameters

url

Theurl parameter indicates the URL where the data is to be transmitted.

data

Thedata parameter is theBodyInit data that is to be transmitted.

Return Value

ThesendBeacon() method returns true if the user agent is able to successfully queue the data for transfer. Otherwise it returns false.

Note

The user agent imposes limits on the amount of data that can be sent via this API: this helps ensure that such requests are delivered successfully and with minimal impact on other user and browser activity. If the amount ofdata to be queued exceeds the user agent limit (as defined inHTTP-network-or-cache fetch), this method returnsfalse; a return value oftrue 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.

3.2Processing Model

On calling thesendBeacon() method withurl and optionaldata, the following steps must be run:

  1. Setbase tothis'srelevant settings object'sAPI base URL.

  2. Setorigin tothis'srelevant settings object'sorigin.

  3. SetparsedUrl to the result of theURL parser steps withurl andbase. If the algorithm returns an error, or ifparsedUrl'sscheme is not "http" or "https",throw a "TypeError" exception and terminate these steps.

  4. LetheaderList be an empty list.
  5. LetcorsMode be "no-cors".
  6. Ifdata is notnull:

    1. SettransmittedData andcontentType to the result ofextractingdata's byte stream with thekeepalive flag set.
    2. If the amount of data that can be queued to be sent bykeepalive enabled requests is exceeded by the size oftransmittedData (as defined inHTTP-network-or-cache fetch), set the return value tofalse and terminate these steps.
      Note

      Requests initiated via the Beacon API automatically set thekeepalive flag, and developers can similarly set the same flag manually when using the Fetch API. All requests with this flag set share the same in-flight quota restrictions that is enforced within the Fetch API.

    3. IfcontentType is not null:
      • SetcorsMode to "cors".
      • IfcontentType value is aCORS-safelisted request-header value for theContent-Type header, setcorsMode to "no-cors".
      • Append aContent-Type header with valuecontentType toheaderList.
  7. Set the return value totrue, return thesendBeacon() call, and continue to run the following steps in parallel:
    1. Letreq be a newrequest, initialized as follows:

      method
      POST
      client
      this'srelevant settings object
      url
      parsedUrl
      header list
      headerList
      origin
      origin
      keepalive
      true
      body
      transmittedData
      mode
      corsMode
      credentials mode
      include
      initiator type
      "beacon"
    2. Fetchreq.

4.Privacy and Security

ThesendBeacon() interface provides an asynchronous and non-blocking mechanism for delivery of data. This API can be used to:

The delivered data might contain potentially sensitive information, for example, data about a user's activity on a web page, to a server. While this can have privacy implications for the user, existing methods, such as scripted form-submit, image beacons, and XHR/fetch requests provide similar capabilities, but come with various and costly performance tradeoffs: the requests can be aborted by the user agent unless the developer blocks the user agent from processing other events (e.g. by invoking a synchronous request, or spinning in an empty loop), and the user agent is unable to prioritize and coalesce such requests to optimize use of system resources.

A request initiated bysendBeacon() is subject to following properties:

As such, from the security perspective, the Beacon API is subject to same security policies as the current methods in use by developers. Similarly, from the privacy perspective, the resulting requests are initiated immediately when the API is called, or upon a page visibility change, which restricts the exposed information (e.g. user's IP address) to existing lifecycle events accessible to the developers. However, user agents might consider alternative methods to surface such requests to provide transparency to users.

Compared to the alternatives, thesendBeacon() API does apply two restrictions: there is no callback method, and the payload size can be restricted by the user agent. Otherwise, thesendBeacon() API is not subject to any additional restrictions. The user agent ought not skip or throttle processing ofsendBeacon() calls, as they can contain critical application state, events, and analytics data. Similarly, the user agent ought not disablesendBeacon() when in "private browsing" or equivalent mode, both to avoid breaking the application and to avoid leaking that the user is in such mode.

A.Acknowledgments

Thanks to Alois Reitbauer, Arvind Jain, Anne van Kesteren, Boris Zbarsky, Chase Douglas, Daniel Austin, Jatinder Mann, James Simonsen, Jason Weber, Jonas Sicking, Nick Doty, Philippe Le Hegaret, Todd Reifsteck, Tony Gentilcore, William Chan, and Yoav Weiss for their contributions to this work.

B.References

B.1Normative references

[fetch]
Fetch Standard. Anne van Kesteren. WHATWG. Living Standard. URL:https://fetch.spec.whatwg.org/
[html]
HTML Standard. Anne van Kesteren; Domenic Denicola; Ian Hickson; Philip Jägenstedt; Simon Pieters. WHATWG. Living Standard. URL:https://html.spec.whatwg.org/multipage/
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL:https://www.rfc-editor.org/rfc/rfc2119
[RFC8174]
Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words. B. Leiba. IETF. May 2017. Best Current Practice. URL:https://www.rfc-editor.org/rfc/rfc8174
[url]
URL Standard. Anne van Kesteren. WHATWG. Living Standard. URL:https://url.spec.whatwg.org/
[webidl]
Web IDL Standard. Edgar Chen; Timothy Gu. WHATWG. Living Standard. URL:https://webidl.spec.whatwg.org/

B.2Informative references

[PAGE-VISIBILITY-2]
Page Visibility Level 2. Ilya Grigorik; Marcos Caceres. W3C. 23 June 2022. W3C Candidate Recommendation. URL:https://www.w3.org/TR/page-visibility-2/
[SERVICE-WORKERS]
Service Workers 1. Alex Russell; Jungkee Song; Jake Archibald; Marijn Kruisselbrink. W3C. 19 November 2019. W3C Candidate Recommendation. URL:https://www.w3.org/TR/service-workers-1/


[8]ページ先頭

©2009-2025 Movatter.jp