• Web NFC API


    W3C Editor's Draft 29 December 2014

    This version:
    http://www.w3.org/2012/nfc/web-api/
    Latest published version:
    http://www.w3.org/TR/nfc/
    Latest editor's draft:
    http://www.w3.org/2012/nfc/web-api/
    Editors:
    Kenneth Rohde Christiansen, Intel
    Zoltan Kis, Intel
    Repository:
    We are on Github.
    File a bug.
    Commit history.

    Abstract

    Near Field Communication (NFC) enables wireless communication between two devices at close proximity, usually less than a few centimeters. NFC is an international standard (ISO/IEC 18092) defining an interface and protocol for simple wireless interconnection of closely coupled devices operating at 13.56 MHz (see http://www.nfc-forum.org/specs/spec_list/).

    This specification defines an API to manage selected NFC use-cases from Web applications and pages, and to enable new use-cases based on NFC technology.

    The generic use-cases covered in this specification are:

      • Enabling reading and writing simple consumer NFC tags
      • Allowing pushing data to another NFC peer device when it is within range.

    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 W3Cpublications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

    Implementors need to be aware that this specification is considered unstable. Implementors who are not taking part in the discussions will find the specification changing out from under them in incompatible ways. Vendors interested in implementing this specification before it eventually reaches the Candidate Recommendation phase should subscribe to the repository on GitHub and take part in the discussions.

    Significant changes to this document since last publication are documented in the Changes section.

    This document was published by the NFC working group as an Editor's Draft. If you wish to make comments regarding this document, please send them to public-nfc@w3.org (subscribearchives). All comments are welcome.

    Publication as an Editor's 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 PolicyW3C 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 August 2014 W3C Process Document.

    Table of Contents

    1. 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 words may, must, must not, and should are to be interpreted as described in [RFC2119].

    This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces it contains.

    Implementations that use ECMAScript to implement the APIs defined in this specification must implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [WEBIDL], as this specification uses that specification and terminology.

    2. Terminology

    The EventHandler interface represents a callback used for event handlers as defined in [HTML5].

    The concepts queue a task and fire a simple event are defined in [HTML5].

    The terms event handler and event handler event types are defined in [HTML5].

    Promise, and JSON.parse are defined in [ECMASCRIPT].

    The algorithms utf-8 encode, and utf-8 decode are defined in [ENCODING].

    EventInitDOMExceptionAbortErrorSyntaxErrorNotSupportedErrorNotFoundError, and SecurityError are defined in [DOM4].

    The term web app refers to a Web application, i.e. an application implemented using Web technologies, and executing within the context of a Web user agent, e.g. a Web browser or other Web-based runtime environments.

    The term expressed permission refers to an act by the user, e.g. via user interface or host device platform features, via which the user approves the permission of a web app to access the Web NFC API.

    Blob is defined in [FILEAPI].

    DOMStringArrayBufferBufferSource and any are defined in [WEBIDL].

    An NFC tag is a passive, unpowered NFC device. The NFC tag is powered by magnetic induction when an active NFC device is in proximity range. A NFC tagcontains a single NDEF message.

    NOTE

    The way of reading the message may happen through proprietary technologies, which require the reader and the tag to be of the same manufacturer. Implementations are expected to encapsulate this.

    An NFC peer is another device, which can interact with other devices in order to exchange data using NFC.

    An NDEF message encapsulates one or more application-defined NDEF records. NDEF stands for NFC Forum Data Exchange Format, a lightweight binary message format. NDEF messages can be stored on a NFC tag or exchanged between NFC-enabled devices.

    An NDEF record has a maximum payload of 2^32-1 bytes. The record also contains information about the payload size, type, and an optional identifier. NFC Forum standardized a small set of useful data types to be used in NDEF records, for instance text, URL, media. In addition, there are record types designed for more complex interactions, such as Smart Poster, and handover records.

    Part of the NDEF record is the TNF field, standing for Type Name Format. It can take binary values representing the following types:

    TNF valueNDEF record type
    0 Empty
    1 NFC Forum Well-Known Type
    2 Media Type
    3 Absolute URI
    4 NFC Forum External Type
    5 Unknown
    6 Unchanged
    7 Reserved

    NFC Forum Well-Known Type includes record types textURISmart Poster (containing a URI or other data and possible actions).

    The term sufficient permission in this document means that a web app which is invoking the methods of this API has been checked to comply with the security policies set by the underlying platform and API implementation in the moment and context of invoking the API method.

    The term document base URL is defined in [HTML5].

    The term URL scope is introduced in this document for NFC operations as a sub-string match to the web app's document URL, which includes the domain of the calling web app. The URL scope is stored in the identifier field of an NDEF record.

    3. Introduction

    This section is non-normative.

    There are three groups of application scenarios for NFC:

    • Hold a device close to a passive wireless tag to read and write data.
    • Hold two powered devices, e.g. phones or tablets, close to each other in order to push data from one to the other, or to initiate a connection using another wireless carrier such as Bluetooth or WiFi.
    • Card emulation
      1. For payments by holding your phone close to a point-of-sales terminal, instead of swiping a payment card.
      2. For emulating tags, allowing use-cases like being able to open your hotel room using just your phone instead of using a NFC-enabled tag or smart card.

    NFC works using magnetic induction, meaning that the reader will emit a small electric charge which then creates a magnetic field. This field powers the passive device which turns it in to electrical impulses to communicate data. Thus, when the devices are within range, a read is always performed (see NFC Analog Specification and NFC Digital Protocol, NFC Forum, 2006). The peer-to-peer connection works in a similar way, as the device periodically switches into a so-called initiator mode in order to scan for targets, for then to fall back into target mode. If a target is found, the data is read the same way as for tags.

    In addition to data types standardized for NDEF records by the NFC Forum, many commercial products, e.g. bus cards, door openers etc, use different card specific data and protocol extensions which require specific NFC chips (same vendor of card and reader) in order to work.

    Card emulation mode capabilities also depend on the NFC chip in the device. For payments, a Secure Element is often needed.

    NFC is usually deeply integrated into device platforms (e.g. Android, Tizen, etc), because end-to-end user experience implications (e.g. users need to be presented platform specific dialogs for selecting applications and actions). Also, privacy and security related issues require platform specific solutions.

    The various integrated technologies, wide variety of use cases, and platform integration issues make standardization of NFC for the web a challenge. Therefore this specification makes a few simplifications in what use cases and data types are possible to handle by users of this API:

    • expose data types already known to web browsers as MIME types
    • use the web security model
    • implementations encapsulate NDEF record handling and the API exposes only data and control events.
    NOTE

    Handover scenarios are expected to be completely encapsulated by implementations. A later version of this API may expose initiating a handover over Bluetooth or WiFi, but in either case implementations and underlying platforms are assumed to handle handover records according to their capabilities.

    NOTE

    Implementations may handle Smart Poster (see "Smart Poster RTD Specification", NFC Forum, 2006) record types, and may expose their data to web apps through this API.

    4. Usage Examples

    This section is non-normative.

    This section shows how developers can make use of the various features of this specification.

    EXAMPLE 1: Save and restore game progress
    navigator.nfc.requestTagRegistration({ scope: "/jumpyjack" }).then(
      function(tagHandler) {
        tagHandler.onmessage = function(ev) {
          if (!self.isAwaitingSave && message.length > 0)
            return self.showRestoreLevelDialog(ev.message[0].progress);
          tagHandler.write({
            progress: self.progress(),
            player: self.player()
          }, "/jumpyjack");
        };
      }, function(error) {
        console.log("buggyjack");
      }
    });

    5. Security and Privacy Considerations

    User agents must not provide Web NFC API access to web apps without the expressed permission of the user. User agents must acquire consent for permission through a user interface for each call to the request*() methods, unless a prearranged trust relationship applies.

    User agents may support prearranged trust relationships that do not require such per-request user interfaces.

    NOTE

    Considering adding the following: User agents must implement the WebNFC API to be HTTPS-only. SSL-only support provides better protection for the user against man-in-the-middle attacks intended to obtain push registration data. Browsers may ignore this rule for development purposes only.

    Permissions that are preserved beyond the current browsing session must be revocable.

    6. Data types and content

    6.1 Data types

    This API exposes the following data types originating from NDEF messages.

    typedef NfcMessageType = DOMString | URL | Blob | JSON;

    The mapping from NDEF record types to supported NfcMessageType is as follows:

    NfcMessageTypeNDEF record type
    DOMString NFC Forum Well Known Type (TNF=1) with type Text
    URL
    • NFC Forum Well Known Type (TNF=1) with type URI
    • NFC Forum Well Known Type (TNF=1) with type Smart Poster
    • Absolute URI as defined in RFC 3986 (TNF=3)
    JSON Media-type as defined in RFC 2046 (TNF=2) with associated MIME type "application/webnfc+json"
    Blob
    • Media-type as defined in RFC 2046 (TNF=2)
    • NFC Forum External Type (TNF=4)
    • Unknown (TNF=5)
    • Any NDEF record type that is not covered by DOMString, URL and JSON types.

    6.2 The NfcMessageData interface

    The content of the NDEF message is exposed by the following interface:

    [NoInterfaceObject]
    interface NfcMessageData {
        readonly    attribute DOMString contentType;
        DOMString   url ();
        ArrayBuffer arrayBuffer ();
        Blob        blob ();
        any         json ();
        DOMString   text ();
    };

    NfcMessageData objects have associated data read by the NFC chip upon creation.

    The contentType attribute describes the type of data such as MIME type and additional information for text messages, e.g. "text/plain;charset=UTF-8;"

    The url() method, when invoked, must return a DOMString representing any URL stored in the NDEF message or undefined.

    The arrayBuffer() method, when invoked, must return an ArrayBuffer whose contents are bytes.

    The blob() method, when invoked, must return a Blob whose contents are bytes.

    The json() method, when invoked, must return the result of invoking the initial value of JSON.parse with the result of running utf-8 decode on bytes as argument. Re-throw any exceptions thrown by JSON.parse.

    The text() method, when invoked, must return the result of running utf-8 decode onbytes.

    6.3 The NfcMessageEvent interface

    In this specification, NDEF message content is delivered by an NfcMessageEvent event.

    interface NfcMessageEvent : Event {
        readonly    attribute DOMString        scope;
        readonly    attribute NfcMessageData[] message;
    };

    The scope property represents the URL scope of the NDEF message.

    The message property represents the NfcMessageData content of the NDEF message.

    7. Extensions to the Navigator interface

    The HTML specification defines a Navigator interface [HTML] which this specification extends.

    partial interface Navigator {
        readonly    attribute NFC nfc;
    };

    7.1 The nfc attribute

    When getting the nfc attribute, the user agent must return the NFC object, which provides NFC related functionality.

    8. The NFC interface

    interface NFC {
        Promise<NfcTagRegistration>  requestTagRegistration (RegistrationOptions? options);
        Promise<NfcPeerRegistration> requestPeerRegistration (RegistrationOptions? options);
    };

    By using these methods, web apps can obtain control objects providing NFC functionality, separately for handling passive NFC tags and communication with active NFC peers, in a similar way to that of service worker extensions [SERVICE-WORKERS].

    As web apps might not be interested in all peer and tag messages, the messages have an associated identifier represented as a URL scope, which enables filtering based on this scope, and also based on content types the web app can or wants to handle.

    When writing or pushing messages to peers, the document base URL serves as the default scope, though another URL scope can be set with the restriction that it must include the document domain (e.g. http://www.w3.org for any data exchange from http://www.w3.org/TR/nfc/).

    Using a different scope can be useful in order to easily differentiate messages and use different registrations and event handlers per scope.

    To describe which messages a registration should apply to, the following dictionary is used:

    8.1 The RegistrationOptions dictionary

    dictionary RegistrationOptions {
        DOMString?  scope;
        DOMString[] contentTypes;
    };

    The scope property denotes the URL scope for which all messages must belong to for the given registration. If the value is null or undefined, then implementations should use the web app's document base URL.

    The contentTypes property denotes the list of MIME types, that the registrations wants to handle.

    EXAMPLE 2: Filter accepting only JSON based messages from http://www.w3.org
    var registrationOptions = {
      scope: "http://www.w3.org",
      contentTypes: ["application/manifest+json", "application/json", "text/json"]
    }
    EXAMPLE 3: Filter which only accept JSON based messages from https://01.org/registration for authentication
    var registrationOptions = {
      scope: "https://01.org/registration",
      contentTypes: ["application/json"]
    }

    8.2 The within-scope algorithm

    Preconditions: a registration object (either NfcTagRegistration or NfcPeerRegistration) exists with an associated regOptions of type RegistrationOptions, which contains registeredScope URL scope.

    Inputurl, a URL to be checked for being within scope.

    Outputtrue or false

    When filtering NDEF messages associated with url, based on URL scope, run the following steps atomically.

    1. If registeredScope defined in regOptions is undefined, then let scope be the calling web app's document base URL.
    2. Otherwise let scope be registeredScope.
    3. If url is a substring of scope, return true, otherwise return false.

    8.3 The requestTagRegistration() method

    The requestTagRegistration() method provides a control object for handling NFC functionality related to NFC tags. When this method is invoked, the user agentmust run the following steps:

    1. Let promise be a new Promise object.
    2. Return promise and continue the following steps asynchronously.
    3. If there are no sufficient permissions to use this method, then reject promise with a new DOMException object whose name property is set to "SecurityError", and terminate these steps.
    4. If there is no support for NFC tag handling functionality in hardware, software, or due to physical incompatibility, then reject promise with a newDOMException object whose name property is set to "NotSupportedError", and terminate these steps.
    5. Parse the argument filter. If it is invalid in the given platform, then reject promise with a new DOMException object whose name property is set to"SyntaxError", and terminate these steps.
    6. Make a request to the underlying platform to initialize NFC functionality. If the request fails, then reject promise with a new DOMException object whosename property is set to "NotSupportedError", and terminate these steps.
    7. If the request is successful, then resolve promise with a NfcTagRegistration object with filtering for incoming data types described by the filterparameter, i.e. fire message events only for messages within-scope and accepted content types.
    8. Whenever the user agent detects an NFC tag which matches the filter associated with an NfcTagRegistration object, queue a task to fire a "message" event at the object.

    8.4 The requestPeerRegistration() method

    The requestPeerRegistration() method provides a control object for handling NFC functionality related to NFC peers. When this method is invoked, the user agent must run the following steps:

    1. Let promise be a new Promise object.
    2. Return promise and continue the following steps asynchronously.
    3. If there are no sufficient permissions to use this method, then reject promise with a new DOMException object whose name property is set to "SecurityError", and terminate these steps.
    4. If there is no support for NFC tag handling functionality in the device, then reject promise with a new DOMException object whose name property is set to"NotSupportedError" , and terminate these steps.
    5. Parse the argument filter. If it is invalid in the given platform, then reject promise with a new DOMException object whose name property is set to"SyntaxError", and terminate these steps.
    6. Make a request to the underlying platform to initialize NFC functionality. If the request fails, then reject promise with a new DOMException object whosename property is set to "NotSupportedError" , and terminate these steps.
    7. If the request is successful, then resolve promise with a NfcPeerRegistration object with filtering for incoming data types described by the filterparameter, i.e. fire message events only for messages within-scope and accepted content types.
    8. Whenever the user agent detects an NFC tag which matches to the filter associated with a NfcTagRegistration object, queue a task to fire an "message"event at the object.

    9. The NfcTagRegistration interface

    [NoInterfaceObject]
    interface NfcTagRegistration : EventHandler {
        Promise write (NfcMessageType message, DOMString scope);
                    attribute EventHandler onmessage;
    };

    The following are the event handlers implemented by the NfcTagRegistration interface.

    event handlerevent nameevent type
    onmessage message NfcMessageEvent

    9.1 The message event

    The message event is used for notifying the registration objects about messages dispatched to the web app via NFC.

    9.2 The write() method

    The write() method is used for writing an NFC tag, if possible. When this method is invoked, the user agent must run the following steps:

    1. Let promise be a new Promise object.
    2. Return promise and continue the following steps asynchronously.
    3. If there are no sufficient permissions to use this method, then reject promise with a new DOMException object whose name property is set to "SecurityError", and terminate these steps.
    4. If there is no support for the functionality of writing an NFC tag in proximity range, then reject promise with a new DOMException object whose nameproperty is set to "NotSupportedError", and terminate these steps.
    5. Parse the argument message. If it is invalid on the given platform, then reject promise with a new DOMException object whose name property is set to"SyntaxError", and terminate these steps. If valid, create an appropriate NDEF message, i.e. a list of NDEF records to be written to the NFC tag, denoted by output.
    6. Parse the argument scope. If it is invalid in the given platform, then reject promise with a new DOMException object whose name property is set to"SyntaxError", and terminate these steps. If the value is undefined, then attribute to scope the DOMString describing the document base URL.
    7. Make a request to the underlying platform to write output to the NFC tag in proximity range. If the request fails, then reject promise with a newDOMException object whose name property is set to "NotSupportedError", and terminate these steps.
    8. If the request is successful, then resolve promise.

    10. The NfcPeerRegistration interface

    [NoInterfaceObject]
    interface NfcPeerRegistration : EventHandler {
        Promise setPushMessage (NfcMessageType message, DOMString scope);
                    attribute EventHandler onmessagepushed;
                    attribute EventHandler onmessage;
    };

    The following are the event handlers implemented by the NfcTagRegistration interface.

    event handlerevent nameevent type
    onmessage message NfcMessageEvent
    onmessagepushed messagepushed NfcMessageEvent

    10.1 the message event

    The message event is used for notifying the registration objects about messages dispatched to the web app via NFC.

    10.2 the messagepushed event

    As messages are not automatically pushed to peers when they detect each other, but most often requires some kind of user interaction, a messagepushed event exists which will be called when a message has been successfully pushed to the other peer.

    10.3 The setPushMessage() method

    The setPushMessage() method is used for setting the messages which the user can push to another peer when it gets into proximity range. When this method is invoked, the user agent must run the following steps:

    1. Let promise be a new Promise object.
    2. Return promise and continue the following steps asynchronously.
    3. If there are no sufficient permissions to use this method, then reject promise with a new DOMException object whose name property is set to "SecurityError", and terminate these steps.
    4. If there is no support for the functionality of sending data to an NFC peer in proximity range, then reject promise with a new DOMException object whosename property is set to "NotSupportedError", and terminate these steps.
    5. Parse the argument message. If it is invalid on the given platform, then reject promise with a new DOMException object whose name property is set to"SyntaxError", and terminate these steps. If valid, create an appropriate NDEF message, i.e. a list of NDEF records to be written to the NFC tag, denoted by output.
    6. Parse the message parameter. If it is invalid or incompatible in the given platform, then reject promise with a new DOMException object whose nameproperty is set to "SyntaxError", and terminate these steps.
    7. Let output be a newly composed NDEF message which matches best the content of message. Set the id field of the NDEF records to scope.
    8. Make a request to the underlying platform to write output to NFC peers in proximity range. If the request fails, then reject promise with a newDOMException object whose name property is set to "NotSupportedError", and terminate these steps.
    9. If the request is successful, then resolve promise.

    A. Changes

    The following is a list of substantial changes to the document. For a complete list of changes, see the change log on Github. You can also view the recently closed bugs.

    • Redesigned the API to follow contemporary web design patterns
    • Change of editors

    B. Acknowledgements

    The editors would like to express their gratitude to the former editors Luc Yriarte and Samuel Ortiz, and also to Don Coleman and Salvatore Iovene for their technical guidance, implementation feedback and support.

    C. References

    C.1 Normative references

    [DOM4]
    Anne van Kesteren; Aryeh Gregor; Ms2ger; Alex Russell; Robin Berjon. W3C DOM4. 10 July 2014. W3C Last Call Working Draft. URL: http://www.w3.org/TR/dom/
    [ECMASCRIPT]
    Allen Wirfs-Brock. ECMA-262 ECMAScript Language Specification, Edition 6. Draft. URL: http://people.mozilla.org/~jorendorff/es6-draft.html
    [ENCODING]
    Anne van Kesteren; Joshua Bell; Addison Phillips. Encoding. 16 September 2014. W3C Candidate Recommendation. URL: http://www.w3.org/TR/encoding/
    [FILEAPI]
    Arun Ranganathan; Jonas Sicking. File API. 12 September 2013. W3C Last Call 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
    [WEBIDL]
    Cameron McCormack. Web IDL. 19 April 2012. W3C Candidate Recommendation. URL: http://www.w3.org/TR/WebIDL/

    C.2 Informative references

    [SERVICE-WORKERS]
    Alex Russell; Jungkee Song. Service Workers. 18 November 2014. W3C Working Draft. URL: http://www.w3.org/TR/service-workers/
  • 相关阅读:
    多个div并排显示的居中问题——来自腾讯的一道面试题
    c++ 类的对象与指针
    c++ 联合体
    用户输入一个数字,找到所有能够除尽它的数的总个数
    javascript
    今天的排版
    论学习php的方法
    我想对所有新程序员说的一些话
    注册表单
    安卓机器人
  • 原文地址:https://www.cnblogs.com/zoucaitou/p/4198766.html
Copyright © 2020-2023  润新知