This API allows a website to communicate with NFC tags through a device's NFC reader.

  • 4 - 79 : Not supported
  • 80 - 88 : Disabled by default
  • 89 - 123 : Not supported
  • 124 : Not supported
  • 125 - 127 : Not supported
  • 12 - 79 : Not supported
  • 3.1 - 17.3 : Not supported
  • 17.4 : Not supported
  • 17.5 - TP : Not supported
  • 2 - 124 : Not supported
  • 125 : Not supported
  • 126 - 128 : Not supported
  • 9 - 66 : Not supported
  • 67 - 75 : Disabled by default
  • 76 - 108 : Not supported
  • 109 : Not supported
  • 5.5 - 10 : Not supported
  • 11 : Not supported

Chrome for Android

  • 124 : Supported

Safari on iOS

  • 3.2 - 17.3 : Not supported
  • 17.5 : Not supported

Samsung Internet

  • 4 - 23 : Not supported
  • 24 : Not supported
  • all : Not supported

Opera Mobile

  • 10 - 12.1 : Not supported
  • 80 : Not supported

UC Browser for Android

  • 15.5 : Not supported

Android Browser

  • 2.1 - 4.4.4 : Not supported

Firefox for Android

  • 14.9 : Not supported

Baidu Browser

  • 13.52 : Supported

KaiOS Browser

  • 2.5 : Not supported
  • 3 : Not supported

Many devices are not equipped with NFC readers. They won't return any data, even though an installed browser might support this API.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers .

Experimental: This is an experimental technology Check the Browser compatibility table carefully before using this in production.

The NDEFReader interface of the Web NFC API is used to read from and write data to compatible NFC devices, e.g. NFC tags supporting NDEF, when these devices are within the reader's magnetic induction field.

Constructor

Returns a new NDEFReader object.

Instance methods

The NDEFReader interface inherits the methods of EventTarget , its parent interface.

Activates a reading device and returns a Promise that either resolves when an NFC tag read operation is scheduled or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted.

Attempts to write an NDEF message to a tag and returns a Promise that either resolves when a message has been written to the tag or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted.

Inherits events from its parent, EventTarget .

Fires when a new reading is available from compatible NFC devices.

Fires when a tag is in proximity of a reading device, but cannot be read.

Handling initial reads while writing

The example below shows how to coordinate between a common reading handler and one used specifically for a single write. In order to write, a tag needs to be found and read. This gives you the ability to check whether it is actually a tag that you want to write to. That's why it's recommended that you call write() from a reading event.

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

the Chromium logo

The Chromium Projects

W3C Web NFC API implementation in Chromium

Rijubrata Bhaumik < [email protected] >

Leon Han < [email protected] >

Donna Wu < [email protected] >

Former: Alexander Shalamov < [email protected] >

Last updated: 22 Dec 2020

This document explains how W3C Web NFC API is implemented in Chromium on both renderer and browser process sides. Future work and implementation challenges are described in “Future work” section of this document.

Ed spec (8 dec 2020):, w3c web nfc api https://w3c.github.io/web-nfc/, the web nfc api enables wireless communication in close proximity between active and passive nfc devices. the means of communication are based on ndef message exchange specification. the api provides simple, yet powerful interfaces to create, read (receive) or write (send) ndef compliant messages. the ndef format was chosen to hide low level complexity and laborious handling of various nfc technology types. the nfc apis are available on android, windows (uwp), ios , chrome os and linux platforms., high level overview, the implementation of web nfc in chromium consists of two main parts:, the nfc module in blink located at third_party/blink/renderer/modules/nfc/ which contains blink js bindings for web nfc, and the browser side platform level adaptation that is located at services/device/nfc . the blink nfc module communicates with the browser adaptation through nfc mojo interface defined in nfc.mojom file and implemented by the services/device/nfc module. the browser communicates with the android nfc implementation also through nfc_provider.mojom , in order to get the nfc object associated with which either resumes or suspends nfc operation in case of webpage visibility status change. at the time of writing, only android platform is supported., other platforms provide nfc interfaces and can be supported in the future ., ndefreader is the primary interface of the web nfc. the ndefreader interface has both, write and scan methods:, - the write method is for writing data to an nfc tag. this method returns a promise, which will be resolved when the message is successfully written to an nfc tag, or rejected either when errors happened or process is aborted by setting the abortsignal in the ndefwriteoptions., - the scan method tries to read data from any nfc tag that comes within proximity. once there is some data found, an ndefreadingevent carrying the data is dispatched to the ndefreader., detailed design, blink module, android adaptation, the most important classes for android adaptation are nfcimpl , nfctaghandler and ndefmessageutils ., nfcimpl class implements mojo nfc interface and uses android platform nfc apis to access nfc functionality. nfctaghandler wraps android.nfc.tag object and provides a unified interface for reading / writing ndef messages. ndefmessageutils has few static methods for conversion between android.nfc.ndefmessage and mojom.ndefmessage objects., at runtime, the latest nfc.push operation is stored in pendingpushoperation object and as soon as the nfc tag appears within close proximity, write operation is performed. same pattern is applicable for nfc.watch operations., runtime view, ndefreader#write(), ndefreader::write() will resolve the promise if there is no error occurred and the message is written to a matched target successfully. in other cases, any errors, or the abortsignal is set during the process, it will reject the promise., ndefreader#scan(), ndefreader#scan() may trigger ndefreader#{onreading,onreadingerror}() events during the whole process. ndefreader::scan() can be called multiple times on the same reader object but there is maximum only one active at any time point., future work, security and privacy, please see the ux design for detailed information about the permission model., web nfc api can be only accessed by top-level secure browsing contexts and user permission is required to access nfc functionality. web nfc api specification addresses security and privacy topics in chapter security and privacy., [web nfc] w3c web nfc api https://w3c.github.io/web-nfc/, [active] active nfc device (phones, nfc readers, powered devices), [passive] passive nfc device (tags, smart cards, etc), [ndef] nfc data exchange format ndef definition.

This document provides a collection of use cases and usage scenarios for web pages and applications using Near Field Communication (NFC). More information about Web NFC can be found here .

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.

This document provides informative background to the Web NFC specification . Comments on the document should be filed as issues at https://github.com/w3c/nfc/issues .

Terminology

For NFC terminology see the Web NFC specification .

A few NFC user scenarios have been enumerated here . For the Web NFC API in particular, a few examples of intended user scenarios follow next.

Reading generic information in a museum

The user touches an NFC capable device to information points of works of arts in a museum, obtaining information about the exposed items. Also, by touching information points in halls, the user can get suggested itineraries, schedule and other information to the personal device for later consultation.

Reading information in administration office

In a population administration office, the user touches in information point in order to save a list of documents required for renewing a passport, and obtaining a the next queuing number for the clerk.

Updating tag information

A museum employee touches information points with a special device which can write to the museum's NFC tags in order to update (read, then write) information on them.

Sending image to another Web NFC capable device

While a user is actively interacting with web site, e.g. https://images.example.com/, and if the user taps the device with another device where another user is actively interacting with the same web site https://images.example.com/, then they can initiate sending an image from one device to the other, using the NFC connection or by handover to Bluetooth or WiFi connection. The second device may be for instance a TV set to show the picture, or a personal computer for image processing.

Handover to Bluetooth

NFC supports handover protocols to Bluetooth or WiFi connectivity for the purpose of larger volume data transfer. The user touches another NFC capable device, and as a result configuration data is sent for a new Bluetooth or WiFi connection, which is then established between the devices.

A related use case for gaming has been described here . Other use cases may include bulk transfer of contacts cards, photos, and other data.

Payment to another user

The user navigates to a web site which manages seller and buyer accounts and touches the device to another device of another user. A payment can be made between the two users' accounts.

Payment for services

On an automated point of sales terminal, such as ticketing machines, the user navigates to a web site which offers the paid service. By touching the receiver area of the point of sales, the payment can be done and the ticket can be delivered electronically to the user's device.

Acknowledgments

The editors would like to express their gratitude to Jonas Sicking and Jeffrey Yasskin.

Web NFC - interacting with NFC tags from a browser

web nfc api safari

What is Web NFC ? 

Web NFC provides the ability for users to interact with NFC tags via a browser. This is a significant development and has the potential to change both how and where NFC tags are used. 

Web NFC Background

As most readers will know, reading an NFC tag from a mobile phone is typically done in two ways. With the latest iPhones (Xs, Xr, 11) or almost any Android phone, it's possible to simply wave the phone over an encoded tag to, for example, launch a website. The second method is to use an App. In which case, the App is opened first and then the tag can be scanned or encoded. 

In the first instance, where the phone scans the tag without an App, then the tag is always simply just 'read'. No encoding is possible with this method. To encode tags, an App is always required. Additionally, an App is always required to access a NFC tag's UID (the 7 byte unique ID locked onto the tag during manufacture). 

Web NFC changes this by allowing NFC tags to be scanned and written directly from a browser . This means that no additional Apps need to be downloaded to read an NFC tag, write to an NFC tag or access the UID. 

Why this is useful

We can see a number of powerful use cases for this but two of the most important are user experience and ease of development. The ability to add NFC tag interaction to existing websites can be completed with a few lines of code. No requirement for complex App development, testing or messing about. The technology also allows access of the tag UID, which can be used as an additional level of authentication and identification. In fact, in combination with the NTAG424 authentication chip , users can access a website, scan an NFC tag and get authentication of a product or item without any additional downloads. 

What it can't do

At the moment, the scope for the WebNFC project is limited. While it's possible to write NFC tags, it's not possible to lock them - which might limit the benefits of being able to write to the tags. However, with access to the tag UID, in location tag deployment via the browser can still be undertaken as the UID cannot be overwritten. 

>>Update : As of Chrome 100 on Android, it is now possible to lock NFC tags as well as encode. 

Using Web NFC

Right now, it's not in full release. At the time of writing, the current version of Chrome for Android (81) has the technology built in but only under development registration. The current plan is to build the tech into release 84. However, clearly, this technology can only currently be used on Android phones and therefore widespread use of the tech is not likely to happen any time soon. 

Without Apple iPhone support, it would be difficult to build a consumer based application around it. But, if Apple did adopt the tech, it might solve one of the signicant barriers on the older iPhone 7 and 8 which currently require an App download to read a tag. By allowing NFC tag scan from a browser, users can have an easier, more steamlined experience without the hassle of having to download an App to scan a tag. 

Regardless, Seritag think that the tech has a substantial appeal to companies with internal intranets, websites, web applications and so on that can see use cases for NFC but don't want the effort of App development. 

More information

Seritag will be producing a video in the next few weeks for our NFC Pro Series video tutorials. More information can also be found at  https://web.dev/nfc/ . This will be an interested new technology. At the very least, developers can add NFC functionality to existing websites without having the cost and expense of developing an App. At best, the project will move forward to encompass more features and more widespread adoption. 

what is an nfc tag

Latest Articles

web nfc api safari

  • NFC Tutorials
  • News & Blog
  • Ixkio Tag Management

5 star review image

Download Free

Browser Terms Explained: Web NFC API

It's free and super easy to set up

In today’s world, we are surrounded by digital devices that help us in various ways. One of the most prevalent technologies that are being used these days is Near Field Communication or NFC. It enables us to transfer data wirelessly between two devices. To simplify the use of NFC in our web applications, a new technology was introduced years ago called Web NFC API. In this article, we will explore this technology in-depth and understand its implementation, use cases, and real-world applications.

Understanding Web NFC API

Web NFC API is a technology that allows web applications to read and write data to NFC tags. It provides a seamless experience for the users as they no longer need to install any external applications on their devices to interact with NFC tags. This technology makes use of the NFC hardware that is integrated into modern-day devices, like smartphones and other electronic gadgets, to create two-way communication between these devices.

What is NFC Technology?

NFC or Near Field Communication is a wireless technology that allows two devices to communicate with each other when they are placed close together. It operates on radio-frequency identification (RFID) technology and is used in various applications like contactless payments, access control, and IoT device management.

How Web NFC API Works

Web NFC API is integrated into web browsers like Google Chrome, Mozilla Firefox, Safari, and Microsoft Edge, and enables web applications to access the device’s NFC hardware. When a user taps an NFC tag with their device, it automatically triggers a web application that is capable of reading NFC data. The application can then read the data from the NFC tag and respond to it accordingly. It can also write data to the NFC tag if required.

Use Cases for Web NFC API

Web NFC API has several use cases that make it a necessary technology for web applications. Some of them are as follows:

Building contactless payment systems.

Smart posters and advertising interactions.

Access control and authentication.

IoT device management.

Browser Support for Web NFC API

Web NFC API is available in most of the modern-day web browsers, such as Google Chrome, Mozilla Firefox, Safari, and Microsoft Edge. Let’s take a look at how each of these browsers supports Web NFC API.

Google Chrome and Web NFC API

Google Chrome first introduced the Web NFC API in version 81 for Android and Windows devices. It is available as an experimental feature that needs to be enabled manually. To enable the feature, the user needs to go to the ‘chrome://flags’ page and search for ‘WebNFCAPI’. Users can then enable this feature to access Web NFC API.

Mozilla Firefox and Web NFC API

Mozilla Firefox announced support for Web NFC API in version 72 and above. As of Firefox version 89, Web NFC API is enabled by default for users on desktop and Android devices. However, users on iOS devices will not have access to Web NFC API as iOS devices do not have support for NFC hardware.

Safari and Web NFC API

Safari has announced support for Web NFC API in its iOS 14. NFC tags can be read and written using Safari on iPhones that have built-in NFC hardware, such as iPhone 7 and later.

Microsoft Edge and Web NFC API

Microsoft Edge announced support for Web NFC API in version 89. Web NFC API is enabled by default for desktop users but not yet supported on mobile devices.

Implementing Web NFC API in Web Applications

Implementing Web NFC API in web applications is not a complicated task. Developers need to follow a few simple steps to get started.

Basic Web NFC API Implementation

The basic implementation of Web NFC API involves registering an event listener that listens for a reading event. In this event listener, developers fetch the records from the NFC tag and show them to the user. Below is a code snippet that shows a simple implementation of the Web NFC API.

navigator.permissions.query({name: "nfc"}).then(permissionStatus => { if (permissionStatus.state === "granted") { // add an event listener // for the nfcfound event nfc.addEventListener('reading', ({message, serialNumber}) => { console.log(`Found NFC tag with serial number: ${serialNumber} and data: ${message.url}`); }); } });

Reading NFC Tags with Web NFC API

Reading NFC tags with Web NFC API is a simple process. When an NFC tag is detected, it sends a ‘reading’ event to the application. Developers can then fetch the records from the NFC tag and show them to the user. Below is a code snippet that shows how to read NFC data using Web NFC API.

// add an event listener for the nfcfound eventnfc.addEventListener('reading', ({message, serialNumber}) => { console.log(`NFC tag with serial number: ${serialNumber} and data: ${message.url}`);});

Writing NFC Tags with Web NFC API

The Web NFC API also allows developers to write data to NFC tags. The process involves creating an NDEF message containing the data and writing it to the NFC tag. Once the data is written successfully, the ‘writeend’ event is sent to the application. Below is a code snippet that shows how to write data to an NFC tag.

// Create an NDEF messageconst message = [ new window.NDEFRecord.createTextRecord("Hello, world!"),];nfc.write(message).then(() => { console.log('NFC tag has been written');}).catch((err) => { console.error(`Error while writing NFC tag: ${err}`);});

Security Considerations for Web NFC API

Developers should be mindful of the security risks while implementing Web NFC API in their applications. NFC tags can potentially carry sensitive information, and therefore, it is essential to ensure that the data is encrypted and safe. Developers should also be wary of ‘clickjacking’ attacks and ensure that the user is aware of the NFC interactions. In addition, security best practices like CORS should be followed to prevent cross-site scripting attacks.

Real-World Applications of Web NFC API

Web NFC API has several real-world applications that make it a necessary technology for web developers. Let’s take a look at some of them.

Contactless Payments

Web NFC API is being widely used in contactless payment systems, enabling users to make payments using their smartphones. This technology eliminates the need for users to carry cash or cards, making the payment process more convenient and seamless.

Smart Posters and Advertising

Web NFC API also enables smart posters and advertising interactions. These interactions allow users to interact with posters and advertisements to receive further information or special offers.

Access Control and Authentication

Web NFC API can also be used for access control and authentication purposes, allowing users to access restricted areas or sensitive information by tapping their phones. This technology is useful for organizations that require secure access to certain areas or information.

IoT Device Management

Web NFC API can be used for IoT device management, enabling users to perform operations like device configuration, firmware updates, and data retrieval. This technology simplifies the management process, making it more efficient and cost-effective.

To conclude, Web NFC API is a technology that simplifies the use of NFC in web applications. It enables seamless data transfer between NFC tags and web applications, eliminating the need for external applications. This technology has several real-world applications, including contactless payments, smart posters, access control, and IoT device management. Developers should be mindful of the security risks when implementing Web NFC API in their applications and follow security best practices to ensure the safety of user data.

Let's set you up !

Working on the web!

Student Tips

Startup Tools

Browser Glossary

Browser Tips

Web NFC API

Experimental: This is an experimental technology Check the Browser compatibility table carefully before using this in production.

The Web NFC API allows exchanging data over NFC via light-weight NFC Data Exchange Format (NDEF) messages.

Note: Devices and tags have to be formatted and recorded specifically to support NDEF record format to be used with Web NFC. Low-level operations are currently not supported by the API, however there is a public discussion about API that would add such functionality.

Interface that represents NDEF messages that can be received from or sent to a compatible tag via a NDEFReader object. A message is composed of metadata and NDEF Records.

Interface that enables reading and writing messages from compatible NFC tags. The messages are represented as NDEFMessage objects.

Interface that represents NDEF records that can be included in an NDEF message.

Specifications

Browser compatibility.

© 2005–2023 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/API/Web_NFC_API

  • My W3C Account

Community & Business Groups

  • Web NFC Community... /

Web NFC API ships in Chrome

Inspired by the community’s enthusiastic response to the previous milestone that made the Web NFC API available to early adopters , the team behind the Web NFC API has been busy during 2020 perfecting the API for the next major milestone!

Today, I am beyond excited to announce the Web NFC API is shipping in Chrome 89 for Android by default! Thanks to the early adopter feedback received during 2020, the new API in Chrome 89 is even easier to use and offers the most flexible NDEF support optimized for your key use cases.

If you’re a web developer and want to learn more, please check out the most excellent developer documentation that explains with easy to understand code examples how to scan and write to NFC tags and interface with other exciting capabilities of this API.

The Web NFC API is available now in Chrome Dev and Canary channels and is coming to Beta in Jan 28 – Feb 4, 2020 and hits Stable in March 2, 2020.

Happy hacking with this new web capability! 🚀

Anssi Kostiainen , Web NFC Community Group Chair

One Response to Web NFC API ships in Chrome

web nfc api safari

This is awesome news. Congratulations!

I’ve had a ton of fun with this new feature while it was being developed in Chrome Dev.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Before you comment here, note that this forum is moderated and your IP address is sent to Akismet , the plugin we use to mitigate spam comments.

  • January 2021
  • December 2019
  • Announcements

Footer Navigation

  • Participate

Contact W3C

  • Help and FAQ
  • Sponsor / Donate
  • Feedback ( archive )

W3C Updates

Remember me

Log in or Request an account

web nfc api safari

Apple declined to implement 16 Web APIs in Safari due to privacy concerns

catalin-cimpanu.jpg

Apple said this week that it declined to implement 16 new web technologies (Web APIs) in Safari because they posed a threat to user privacy by opening new avenues for user fingerprinting.

Technologies that Apple declined to include in Safari because of user fingerprinting concerns include:

  • Web Bluetooth - Allows websites to connect to nearby Bluetooth LE devices.
  • Web MIDI API - Allows websites to enumerate, manipulate and access MIDI devices.
  • Magnetometer API - Allows websites to access data about the local magnetic field around a user, as detected by the device's primary magnetometer sensor.
  • Web NFC API - Allows websites to communicate with NFC tags through a device's NFC reader.
  • Device Memory API - Allows websites to receive the approximate amount of device memory in gigabytes.
  • Network Information API - Provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type changes
  • Battery Status API - Allows websites to receive information about the battery status of the hosting device.
  • Web Bluetooth Scanning - Allows websites to scan for nearby Bluetooth LE devices.
  • Ambient Light Sensor - Lets websites get the current light level or illuminance of the ambient light around the hosting device via the device's native sensors.
  • HDCP Policy Check extension for EME - Allows websites to check for HDCP policies, used in media streaming/playback.
  • Proximity Sensor - Allows websites to retrieve data about the distance between a device and an object, as measured by a proximity sensor.
  • WebHID - Allows websites to retrieve information about locally connected Human Interface Device (HID) devices.
  • Serial API - Allows websites to write and read data from serial interfaces, used by devices such as microcontrollers, 3D printers, and othes.
  • Web USB - Lets websites communicate with devices via USB (Universal Serial Bus).
  • Geolocation Sensor (background geolocation) - A more modern version of the older Geolocation API that lets websites access geolocation data.
  • User Idle Detection - Lets website know when a user is idle.

The vast majority of these APIs are only implemented in Chromium-based browsers, and very few on Mozilla's platform.

Apple claims that the 16 Web APIs above would allow online advertisers and data analytics firms to create scripts that fingerprint users and their devices.

User fingerprints are small scripts that an advertiser loads and runs inside each user's browser. The scripts execute a set of standard operations, usually against a common Web API or common web browser feature, and measure the response.

Since each user has a different browser and operating system configuration, responses are unique per user device. Advertisers use this unique response (fingerprint), coupled with other fingerprints and data points, to create unique identifiers for each user.

Over the past three years, user fingerprinting has become the standard method of tracking users in the online ad tech market.

The shift to user fingerprinting comes as browser makers have been deploying anti-tracking features that have limited the capabilities and reach of third-party (tracking) cookies.

Some browser makers have also been deploying countermeasures to prevent fingerprinting operations through the most common methods -- such as fonts, HTML5 canvas, and WebGL -- but not all user fingerprinting vectors are currently blocked.

Furthermore, new ones are constantly being created as browser makers add new Web APIs to their code.

Currently, Apple has identified the 16 Web APIs above as some of the worst offenders; however, the browser maker said that if any of these new technologies "reduce fingerprintability down the road" it would reconsider adding it to Safari.

"WebKit's first line of defense against fingerprinting is to not implement web features which increase fingerprintability and offer no safe way to protect the user," Apple said.

For Web APIs already implemented in Safari years before, Apple says it's been working to limit their fingerprintability vector. So far, Apple said it:

  • Removed support for custom fonts. This means only presenting built-in fonts which are the same for all users with the same system.
  • Removed minor software update information from the user agent string. The string only changes with the marketing version of the platform and the browser.
  • Removed the Do Not Track flag, which ironically was used as a fingerprinting vector, adding uniqueness to the users who had enabled it.
  • Removed support for any plug-ins on macOS. Other desktop ports may differ. (Plug-ins were never a thing on iOS.)
  • Require a user permission for websites to access the Device Orientation/Motion APIs on mobile devices, because the physical nature of motion sensors may allow for device fingerprinting.
  • Prevent fingerprinting of attached cameras and microphones through the Web Real-Time Communication API (WebRTC).

WWDC 2020: Apple Silicon highlights in pictures

Ios 18 wishlist: 5 features i'd like to see apple bring to the iphone, apple to let eu users download apps from the web with ios 17.5 beta 2. how it works, apple confirms next ipad event for may 7: here's what to expect.

Web/API/Web NFC API

Draft This page is not complete.

This is an experimental technology Check the Browser compatibility table carefully before using this in production.

The Web NFC API allows exchanging data over NFC via light-weight NFC Data Exchange Format (NDEF) messages.

Note: Devices and tags have to be formatted and recorded specifically to support NDEF record format to be used with Web NFC. Low-level operations are currently not supported by the API, however there is a public discussion about API that would add such functuionality.

  • 1 Interfaces
  • 2 Specifications

Specifications

Browser compatibility.

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Web NFC API by Mozilla Contributors is licensed under CC-BY-SA 2.5 .

  • Javascript API References

Powered by MediaWiki

Optimizing WebKit & Safari for Speedometer 3.0

Apr 10, 2024

by Alan Baradlay, Antti Koivisto, Matt Woodrow, Patrick Angle, Ryosuke Niwa, Vitor Ribeiro Roriz, Wenson Hsieh, and Yusuke Suzuki

The introduction of Speedometer 3.0 is a major step forward in making the web faster for all, and allowing Web developers to make websites and web apps that were not previously possible. In this article, we explore ways the WebKit team made performance optimizations in WebKit and Safari based on the Speedometer 3.0 benchmark.

In order to make these improvements, we made an extensive use of our performance testing infrastructure. It’s integrated with our continuous integration , and provides the capability to schedule A/B tests. This allows engineers to quickly test out performance optimizations and catch new performance regressions.

Improving Tools

Proper tooling support is the key to identifying and addressing performance bottlenecks. We defined new internal JSON format for JavaScriptCore sampling profiler output to dump and process them offline. It includes a script which processes and generates analysis of hot functions and hot byte codes for JavaScriptCore. We also added FlameGraph generation tool for the dumped sampling profiler output which visualizes performance bottlenecks. In addition, we added support for JITDump generation on Darwin platforms to dump JIT related information during execution. And we improved generated JITDump information for easy use as well. These tooling improvements allowed us to quickly identify bottlenecks across Speedometer 3.0.

Improving JavaScriptCore

Revising megamorphic inline cache (ic).

Megamorphic IC offers faster property access when one property access site observes many different object types and/or property names. We observed that some frameworks such as React contain a megamorphic property access. This led us to continuously improve JavaScriptCore’s megamorphic property access optimizations: expanding put megamorphic IC, adding megamorphic IC for the in operation, and adding generic improvements for megamorphic IC.

Revising Call IC

Call IC offers faster function calls by caching call targets inline. We redesigned Call IC and we integrated two different architectures into different tiers of Just-In-Time (JIT) compilers. Lower level tiers use Call IC without any JIT code generation and the highest level tier uses JIT code generatiton with the fastest Call IC. There is a tradeoff between code generation time and code efficiency, and JavaScriptCore performs a balancing act between them to achieve the best performance across different tiers.

Optimizing JSON

Speedometer 3.0 also presented new optimization opportunities to our JSON implementations as they contain more non-ASCII characters than before. We made our fast JSON stringifier work for unicode characters . We also analyzed profile data carefully and made JSON.parse faster than ever .

Adjusting Inlining Heuristics

There are many tradeoffs when inlining functions in JavaScript. For example, inline functions can more aggressively increase the total bytecode size and may cause memory bandwidth to become a new bottleneck. The amount of instruction cache available in CPU can also influence how effective a given inlining strategy is. And the calculus of these tradeoffs change over time as we make more improvements to JavaScriptCore such as adding new bytecode instruction and changes to DFG’s numerous optimization phases. We took the release of the new Speedometer 3.0 benchmark as an opportunity to adjust inlining heuristics based on data collected in modern Apple silicon Macs with the latest JavaScriptCore.

Make JIT Code Destruction Lazy

Due to complicated conditions, JavaScriptCore eagerly destroyed CodeBlock and JIT code when GC detects they are dead. Since these destructions are costly, they should be delayed and processed while the browser is idle. We made changes so that they are now destroyed lazily, during idle time in most cases.

Opportunistic Sweeping and Garbage Collection

In addition, we noticed that a significant amount of time goes into performing garbage collection and incremental sweeping across all subtests in both Speedometer 2.1 and 3.0. In particular, if a subtest allocated a large number of JavaScript objects on the heap, we would often spend a significant amount of time in subsequent subtests collecting these objects. This had several effects:

  • Increasing synchronous time intervals on many subtests due to on-demand sweeping and garbage collection when hitting heap size limits.
  • Increasing asynchronous time intervals on many subtests due to asynchronous garbage collection or timer-based incremental sweeping triggering immediately after the synchronous timing interval.
  • Increasing overall variance depending on whether timer-based incremental sweeping and garbage collection would fall in the synchronous or asynchronous timing windows of any given subtest.

At a high level, we realized that some of this work could be performed opportunistically in between rendering updates — that is, during idle time — instead of triggering in the middle of subtests. To achieve this, we introduced a new mechanism in WebCore to provide hints to JavaScriptCore to opportunistically perform scheduled work after the previous rendering update has completed until a given deadline (determined by the estimated remaining time until the next rendering update). The opportunistic task scheduler also accounts for imminently scheduled zero delay timers or pending requestAnimationFrame callbacks : if it observes either, it’s less likely to schedule opportunistic work in order to avoid interference with imminent script execution. We currently perform a couple types of opportunistically scheduled tasks:

  • Incremental Sweeping : Prior to the opportunistic task scheduler, incremental sweeping in JavaScriptCore was automatically triggered by a periodically scheduled 100 ms timer. This had the effect of occasionally triggering incremental sweeping during asynchronous timing intervals, but also wasn’t aggressive enough to prevent on-demand sweeping in the middle of script execution. Now that JavaScriptCore is knowledgable about when to opportunistically schedule tasks, it can instead perform the majority of incremental sweeping in between rendering updates while there aren’t imminently scheduled timers. The process of sweeping is also granular to each marked block, which allows us to halt opportunistic sweeping early if we’re about to exceed the deadline for the next estimated rendering update.
  • Garbage Collection : By tracking the amount of time spent performing garbage collection in previous cycles, we’re able to roughly estimate the amount of time needed to perform the next garbage collection based on the number of bytes visited or allocated since the last cycle. If the remaining duration for performing opportunistically scheduled tasks is longer than this estimated garbage collection duration, we immediately perform either an Eden collection or full garbage collection . Furthermore, we integrated activity-based garbage collections into this new scheme to schedule them at appropriate timing.

Overall, this strategy yields a 6.5% total improvement in Speedometer 3.0 *, decreasing the time spent in every subtest by a significant margin, and a 6.9% total improvement in Speedometer 2.1 *, significantly decreasing the time spent in nearly all subtests.

* macOS 14.4, MacBook Air (M2, 2022)

Various Miscellaneous Optimizations for Real World Use Cases

We extensively reviewed all Speedometer 3.0 subtests and did many optimizations for realistic use cases. The examples include but are not limited to: faster Object.assign with empty objects , improving object spread performance , and so on.

Improving DOM code

Improving DOM code is Speedometer’s namesake, and that’s exactly what we did. For example, we now store the NodeType in the Node object itself instead of relying on a virtual function call. We also made DOMParser use a fast parser, improved its support of li elements , and made DOMParser not construct a redundant DocumentFragment . Together, these changes improved TodoMVC-JavaScript-ES5 by ~20%. We also eliminated O(n^2) behavior in the fast parser for about ~0.5% overall progression in Speedometer 3.0. We also made input elements construct their user-agent shadow tree lazily during construction and cloning , the latter of which is new in Speedometer 3.0 due to web components and Lit tests. We devirtualized many functions and inlined more functions to reduce the function call overheads. We carefully reviewed performance profile data and removed inefficiency in hot paths like repeated reparsing of the same URLs .

Improving Layout and Rendering

We landed a number of important optimizations in our layout and rendering code. First off, most type checks performed on RenderObject are now done using an inline enum class instead of virtual function calls , this alone is responsible for around ~0.7% of overall progression in Speedometer 3.0.

Improving Style Engine

We also optimized the way we compute the properties animated by Web Animations code. Previously, we were enumerating every animatable properties while resolving transition: all . We optimized this code to only enumerate affected properties. This was ~0.7% overall Speedometer 3.0 progression. Animating elements can now be resolved without fully recomputing their style unless necessary for correctness.

Speedometer 3.0 content, like many modern web sites, uses CSS custom properties extensively. We implemented significant optimizations to improve their performance. Most custom property references are now resolved via fast cache lookups, avoiding expensive style resolution time property parsing. Custom properties are now stored in a new hierarchical data structure that reduces memory usage as well.

One key component of WebKit styling performance is a cache (called “matched declarations cache”) that maps directly from a set of CSS declarations to the final element style, avoiding repeating expensive style building steps for identically styled elements. We significantly improved the hit rate of this cache.

We also improved styling performance of author shadow trees, allowing trees with identical styles to share style data more effectively.

Improving Inline Layout

We fixed a number of performance bottlenecks in inline layout engine as well. Eliminating complex text path in Editor-TipTap was a major ~7% overall improvement. To understand this optimization, WebKit has two different code paths for text layout: the simple text path, which uses low level font API to access raw font data, and the complex text path, which uses CoreText for complex shaping and ligatures. The simple text path is faster but it does not cover all the edge cases. The complex text path has full coverage but is slower than the simple text path.

Previously, we were taking the complex text path whenever a non-default value of font-feature or font-variant was used. This is because historically the simple text path wouldn’t support these operations. However, we noticed that the only feature of these still missing in the simple text path was font-variant-caps . By implementing font-variant-caps support for the simple text path , we allowed the simple text path to handle the benchmark content. This resulted in 4.5x improvement in Editor-TipTap subtest, and ~7% overall progression in Speedometer 3.0.

In addition to improving the handling of text content in WebKit, we also worked with CoreText team to avoid unnecessary work in laying out glyphs. This resulted in ~0.5% overall progression in Speedometer 3.0, and these performance gains will benefit not just WebKit but other frameworks and applications that use CoreText.

Improving SVG Layout

Another area we landed many optimizations for is SVG. Speedometer 3.0 contains a fair bit of SVG content in test cases such as React-Stockcharts-SVG. We were spending a lot of time computing the bounding box for repaint by creating GraphicsContext, applying all styles, and actually drawing strokes in CoreGraphics. Here, we adopted Blink ’s optimization to approximate bounding box and made ~6% improvement in React-Stockcharts-SVG subtest. We also eliminated O(n^2) algorithm in SVG text layout code, which made some SVG content load a lot quicker .

Improving IOSurface Cache Hit Rate

Another optimization we did involve improving the cache hit rate of IOSurface. An IOSurface is a bitmap image buffer we use to paint web contents into. Since creating this object is rather expensive, we have a cache of IOSurface objects based on their dimensions. We observed that the cache hit rate was rather low (~30%) so we increased the cache size from 64MB to 256MB on macOS and improved the cache hit rate by 2.7x to ~80%, improving the overall Speedometer 3.0 score by ~0.7%. In practice, this means lower latency for canvas operations and other painting operations.

Reducing Wait Time for GPU Process

Previously, we required a synchronous IPC call from the Web Process to the GPU process to determine which of the existing buffers had been released by CoreAnimation and was suitable to use for the next frame. We optimized this by having the GPUP just select (or allocate) an appropriate buffer, and direct all incoming drawing commands to the right destination without requiring any response. We also changed the delivery of any newly allocated IOSurface handles to go via a background helper thread , rather than blocking the Web Process’s main thread.

Improving Compositing

Updates to compositing layers are now batched , and flushed during rendering updates, rather than computed during every layout. This significantly reduces the cost of script-incurred layout flushes.

Improving Safari

In addition to optimizations we made in WebKit, there were a handful of optimizations for Safari as well.

Optimizing AutoFill Code

One area we looked at was Safari’s AutoFill code. Safari uses JavaScript to implement its AutoFill logic, and this execution time was showing up in the Speedometer 3.0 profile. We made this code significantly faster by waiting for the contents of the page to settle before performing some work for AutoFill. This includes coalescing handling of newly focused fields until after the page had finished loading when possible, and moving lower-priority work out of the critical path of loading and presenting the page for long-loading pages. This was responsible for ~13% progression in TodoMVC-React-Complex-DOM and ~1% progression in numerous other tests, improving the overall Speedometer 3.0 score by ~0.9%.

Profile Guided Optimizations

In addition to making the above code changes, we also adjusted our profile-guided optimizations to take Speedometer 3.0 into account. This allowed us to improve the overall Speedometer 3.0 score by 1~1.6%. It’s worth noting that we observed an intricate interaction between making code changes and profile-guided optimizations. We sometimes don’t observe an immediate improvement in the overall Speedometer 3.0 score when we eliminate, or reduce the runtime cost of a particular code path until the daily update of profile-guided optimizations kicks. This is because the modified or newly added code has to benefit from profile-guided optimizations before it can show a measurable difference. In some cases, we even observed that a performance optimization initially results in a performance degradation until the profile-guided optimizations are updated.

With all these optimizations and dozens more, we were able to improve the overall Speedometer 3.0 score by ~60% between Safari 17.0 and Safari 17.4. Even though individual progressions were often less than 1%, over time, they all stacked up together to make a big difference. Because some of these optimizations also benefited Speedometer 2.1, Safari 17.4 is also ~13% faster than Safari 17.0 on Speedometer 2.1. We’re thrilled to deliver these performance improvements to our users allowing web developers to build websites and web apps that are more responsive and snappier than ever.

IMAGES

  1. NFC метка для сайта Safari: что это и как использовать

    web nfc api safari

  2. NFC метка для сайта Safari: что это и как использовать

    web nfc api safari

  3. React project to scan and write into NFC tags using the Web NFC API

    web nfc api safari

  4. Nova API do Safari permite autenticação com o Face ID e Touch ID na web

    web nfc api safari

  5. Web NFC

    web nfc api safari

  6. NFC метка для сайта Safari: что это и как использовать

    web nfc api safari

VIDEO

  1. Ylang Ylang

  2. CRUD Tutorial

  3. Wild Animals Song 🦒 Safari Chants for Preschoolers

  4. Northern Cape Safari

  5. Dino Safari Park Karachi

  6. HOW TO GET A JOB AT GOOGLE IN 2021

COMMENTS

  1. Web NFC API

    The Web NFC API allows exchanging data over NFC via light-weight NFC Data Exchange Format (NDEF) messages. Note: Devices and tags have to be formatted and recorded specifically to support NDEF record format to be used with Web NFC. Low-level operations are currently not supported by the API, however there is a public discussion about API that ...

  2. How to use Web-NFC in Chrome for iOS?

    5. As of 23.11.2020 Web-NFC isn't supported in Chrome for iOS. For iOS 13, NFC is available for native iOS developers. However, it seems it isn't yet available within Chrome for iOS according to whatwebcando.today. Posted a comment within the Google Chrome Feature Request for Web-NFC to also support Chrome for iOS. Related links: Requests on ...

  3. Web NFC

    Web NFC. 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.

  4. Web NFC

    Many devices are not equipped with NFC readers. They won't return any data, even though an installed browser might support this API. 1 Was experimentally supported in desktop Chromium browsers behind the enable-experimental-web-platform-features flag. 2 Current implementations only allow communication through the NDEF protocol in order to ...

  5. web-nfc/EXPLAINER.md at gh-pages · w3c/web-nfc · GitHub

    Among different use-cases, NFC allows users to take their NFC enabled device such as a phone and touch NFC tags (sticker, card and the like). The platform, or a certain application can then at this moment read the content, write new content back, and make NFC tag permanently read-only. Web NFC allows to build web experiences that can do the ...

  6. NDEFReader

    The NDEFReader interface of the Web NFC API is used to read from and write data to compatible NFC devices, e.g. NFC tags supporting NDEF, when these devices are within the reader's magnetic induction field.

  7. Web NFC API Use Cases

    This document provides a collection of use cases and usage scenarios for web pages and applications using Near Field Communication (NFC). More information about Web NFC can be found here . 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.

  8. Web NFC Community Group

    The Web NFC Community Group will create a Near Field Communication API that is browser-friendly and adheres to the Web's security model. We believe that means the API will not expose full, low level NFC functionality, but rather a higher level subset that is safe for Web pages, protects user privacy, and does not annoy users with unnecessary or complex permission requests.

  9. Web NFC

    W3C Web NFC API https://w3c.github.io/web-nfc/ Background The Web NFC API enables wireless communication in close proximity between active and passive NFC devices. The means of communication are based on NDEF message exchange specification. The API provides simple, yet powerful interfaces to create, read (receive) or write (send) NDEF compliant ...

  10. Web NFC API

    Abstract. This document provides a collection of use cases and usage scenarios for web pages and applications using Near Field Communication (NFC). More information about Web NFC can be found here . 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 ...

  11. Web NFC

    Web NFC provides the ability for users to interact with NFC tags via a browser. This is a significant development and has the potential to change both how and where NFC tags are used. Web NFC Background. As most readers will know, reading an NFC tag from a mobile phone is typically done in two ways.

  12. Browser Terms Explained: Web NFC API

    Web NFC API is integrated into web browsers like Google Chrome, Mozilla Firefox, Safari, and Microsoft Edge, and enables web applications to access the device’s NFC hardware. When a user taps an NFC tag with their device, it automatically triggers a web application that is capable of reading NFC data. The application can then read the ...

  13. Web NFC API

    The Web NFC API allows exchanging data over NFC via light-weight NFC Data Exchange Format (NDEF) messages. Note: Devices and tags have to be formatted and recorded specifically to support NDEF record format to be used with Web NFC. Low-level operations are currently not supported by the API, however there is a public discussion about API that ...

  14. Overview

    What is Web NFC. NFC stands for Near Field Communications and is a short range wireless technology operating at 13.56 MHz. Short range really means short range: in order to communicate, the devices have to be just a few centimeters apart or less. There are four operating modes defined by the NFC Forum: reader/writer, peer-to-peer, card ...

  15. Is reading a NFC chip as a web app possible

    1. The Web NFC API is what you're looking for: https://web.dev/nfc. Web NFC is available only on Chrome for Android for now. It is limited to NDEF because the security properties of reading and writing NDEF data are more easily quantifiable. Low-level I/O operations (e.g. ISO-DEP, NFC-A/B, NFC-F), Peer-to-Peer communication mode and Host-based ...

  16. Web NFC API

    The editors would like to thank Jaehyun Park and Taehee Lee of Samsung for their work on the initial API design. We would also like to thank the members of the W3C SysApps group for their help on the API specification process, and the members of the W3C NFC group for their feedback on this API. A. References A.1 Normative references

  17. Web NFC API ships in Chrome

    Inspired by the community's enthusiastic response to the previous milestone that made the Web NFC API available to early adopters, the team behind the Web NFC API has been busy during 2020 perfecting the API for the next major milestone!. Today, I am beyond excited to announce the Web NFC API is shipping in Chrome 89 for Android by default! Thanks to the early adopter feedback received ...

  18. Apple declined to implement 16 Web APIs in Safari due to ...

    Web NFC API - Allows websites to communicate with NFC tags through a device's NFC reader. ... For Web APIs already implemented in Safari years before, Apple says it's been working to limit their ...

  19. iOS: Polyfill NFC web API

    The primary issue is that it is using NFC scanner. I have started to wonder if there is any way to polyfill NFC web API on iOS / Safari? It seems that official support will not happend soon... At the moment I'm thinking of creating some kind of "service" that would host native NFC API over some communication channel. A bit more detailed:

  20. Web/API/Web NFC API

    The Web NFC API allows exchanging data over NFC via light-weight NFC Data Exchange Format (NDEF) messages. ... Safari on iOS: Samsung Internet: NDEFReader. Experimental ' Chrome. No support No Edge. No support No Firefox. No support No IE. No support No Opera. No support No Safari. No support No WebView Android.

  21. Optimizing WebKit & Safari for Speedometer 3.0

    The introduction of Speedometer 3.0 is a major step forward in making the web faster for all, and allowing Web developers to make websites and web apps that were not previously possible. In this article, we explore ways the WebKit team made performance optimizations in WebKit and Safari based on the Speedometer 3.0 benchmark.

  22. Can the Web NFC api be used in Progressive Web Applications?

    22. Web NFC API is available only in Chrome for Android and that too when a flag is enabled ( try about:flags) enabled. Unless you are targeting your app for some internal corporate app where you can set the flag in all targeted users browser, I would recommend go with native code or wrapper (cordova or have a native app send in the details via ...