API in Capabilities
Web NFC API
Published Updated
NDEFReader lets a web app read and write NFC Data Exchange Format (NDEF) messages on tags held against the phone. scan() starts listening and fires a reading event with the tag’s serial number and records each time one comes into range. write() pushes a message to the next tag; makeReadOnly() locks a tag permanently. A PWA uses it for inventory labels, event check-in, or pairing with a device that carries an NFC sticker; low-level tag protocols outside NDEF are not exposed.
Chrome 89 for Android is the only implementation: it ships NDEFReader, scan(), write(), and the reading and readingerror events, and Chrome 100 for Android added makeReadOnly() (BCD api.NDEFReader). Chromium browsers on Android that mirror Chrome, such as Samsung Internet, inherit it; desktop Chrome, Firefox, and Safari report no support, and WebKit has filed an “oppose” position (standards-positions #584).
Syntax
Section titled “Syntax”const reader = new NDEFReader()
reader.scan()reader.scan(options)reader.write(message)reader.write(message, options)reader.makeReadOnly()reader.makeReadOnly(options)All three methods return a Promise<undefined>. scan() resolves as soon as listening has started, not when a tag is read; results arrive through reading (NDEFReadingEvent with serialNumber and message) and readingerror (fired when a tag is in range but reading it fails). write() and makeReadOnly() resolve once the tag has been written or locked, which may be seconds later when no tag is present yet. The interface is [SecureContext, Exposed=Window], works only in the top-level browsing context, and is suspended while the page is not visible.
Parameters
Section titled “Parameters”scan() and makeReadOnly() take one optional dictionary each; write() takes a message and an optional dictionary.
| Method | Parameter | Type | Required | Description |
|---|---|---|---|---|
scan() |
options |
NDEFScanOptions { signal } |
No | signal (AbortSignal) stops listening and removes this reader from the active set. |
write() |
message |
NDEFMessageSource: DOMString, BufferSource, or NDEFMessageInit |
Yes | A string becomes one "text" record, a buffer one "mime" record of type application/octet-stream, and NDEFMessageInit supplies explicit records. |
write() |
options |
NDEFWriteOptions { overwrite = true, signal } |
No | With overwrite: false the write is refused when the tag already holds NDEF records. signal aborts a pending write. |
makeReadOnly() |
options |
NDEFMakeReadOnlyOptions { signal } |
No | signal aborts the pending lock. |
NDEFMessageInit has a single required member records, a sequence<NDEFRecordInit>.
NDEFRecordInit member |
Type | Required | Description |
|---|---|---|---|
recordType |
USVString |
Yes | "empty", "text", "url", "smart-poster", "mime", "absolute-url", "unknown", an external type such as "example.com:shelf", or a local type such as ":act" inside a smart poster. |
mediaType |
USVString |
No | MIME type of the payload, used only by "mime" records and defaulting to application/octet-stream when absent or unparsable; must be absent for every other record type. |
id |
USVString |
No | Record identifier; must be absent for "empty". |
encoding |
USVString |
No | For "text" only: "utf-8" (default), "utf-16", "utf-16be", or "utf-16le". The UTF-16 values need BufferSource data; with DOMString data only "utf-8" or omission is accepted. |
lang |
USVString |
No | BCP 47 language tag for "text" records, for example "en"; defaults to the document language. |
data |
any |
Depends on type | DOMString or BufferSource for "text"; DOMString for "url" and "absolute-url"; BufferSource for "mime" and "unknown"; BufferSource or NDEFMessageInit for external and local types; NDEFMessageInit only for "smart-poster"; omitted for "empty". |
Nesting is limited to 32 levels of NDEFMessageInit, and an external type name may not exceed 255 bytes.
Exceptions
Section titled “Exceptions”Checks that run before the promise is returned reject immediately; the rest happen after the user grants the nfc permission.
| Exception | Methods | Condition |
|---|---|---|
InvalidStateError |
all | The caller is not the active top-level browsing context (iframes are refused), or, for scan(), this reader is already scanning. |
the signal’s abort reason (AbortError by default) |
all | options.signal was already aborted at call time, or is aborted while the operation is pending. |
TypeError |
write() |
The message is invalid: empty records; nesting deeper than 32; a mediaType or id on a record type that forbids it; data of the wrong type for the recordType; a "text" encoding other than the four allowed, or a UTF-16 encoding on DOMString data; an external type name over 255 bytes; or a "smart-poster" without exactly one URL record. |
SyntaxError |
write() |
A "url" or "absolute-url" record whose data does not parse as a URL, or a "text" lang longer than 63 bytes. |
NotAllowedError |
all | The user denied the nfc permission, or (write() with overwrite: false) the tag already carries NDEF records. |
NotSupportedError |
all | The device has no NFC adapter or the adapter is unreachable. For write(), also an adapter that cannot push data, or a tag that does not expose NDEF technology and is not formattable. While scanning, an incompatible tag fires readingerror instead of rejecting scan(). |
NotReadableError |
all | The browser is not allowed to use the adapter, for example when NFC is switched off in system settings. |
NetworkError |
write(), makeReadOnly() |
The transfer to the tag or the lock operation failed, for instance because the tag moved away mid-write. |
scan() itself cannot report an unreadable tag: that arrives as a readingerror event on the reader, with no payload, so the handler should prompt the user to hold the tag still and try again.
Examples
Section titled “Examples”Test for NDEFReader in window before using it. Desktop browsers and iOS run the fallback branch, which can offer a QR code or manual entry carrying the same identifier.
Scanning tags with a QR-code fallback
Section titled “Scanning tags with a QR-code fallback”Start scanning from a tap so the permission prompt is tied to a gesture, decode "text" and "url" records, and show a QR scanner when Web NFC is missing. scan() resolves once listening starts; the actual reads come later through the reading event.
async function startTagScan(onTag, showQrFallback) { if (!('NDEFReader' in window)) { showQrFallback(); return; }
const reader = new NDEFReader(); reader.addEventListener('reading', ({ serialNumber, message }) => { const decoder = new TextDecoder(); for (const record of message.records) { if (record.recordType === 'text') onTag({ serialNumber, text: decoder.decode(record.data) }); if (record.recordType === 'url') onTag({ serialNumber, url: decoder.decode(record.data) }); } }); reader.addEventListener('readingerror', () => onTag({ error: 'Tag could not be read; hold it still and try again.' }));
try { await reader.scan(); } catch (err) { if (err.name === 'NotAllowedError') showQrFallback(); else throw err; }}record.data is a DataView; "text" records carry their encoding in record.encoding and language in record.lang, so a UTF-16 tag needs new TextDecoder(record.encoding) instead of the default.
Writing a URL only to blank tags, with a timeout
Section titled “Writing a URL only to blank tags, with a timeout”overwrite: false protects tags that already hold data, and an AbortSignal stops the pending write if no tag shows up within ten seconds. Without Web NFC the function returns false so the UI can offer to print the URL as a QR label instead.
async function writeLabel(url) { if (!('NDEFReader' in window)) return false;
const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 10_000); try { await new NDEFReader().write( { records: [{ recordType: 'url', data: url }] }, { overwrite: false, signal: controller.signal }, ); return true; } catch (err) { if (err.name === 'AbortError') return false; // no tag within 10 s if (err.name === 'NotAllowedError') throw new Error('Tag already has content or NFC permission was denied'); throw err; } finally { clearTimeout(timer); }}A tag that moves away during the transfer rejects with NetworkError. The specification does not say what is left on the tag, so read it back before trusting it; a retry with overwrite: false is refused if the first attempt left records behind.
Writing a vendor record and locking the tag
Section titled “Writing a vendor record and locking the tag”External record types let an app store structured data under its own namespace. After writing, makeReadOnly() locks the tag so a visitor’s phone cannot change it; the lock is irreversible, so the example asks for confirmation first.
async function provisionShelfTag(shelfId, confirmLock) { if (!('NDEFReader' in window)) return 'unsupported';
const reader = new NDEFReader(); const payload = new TextEncoder().encode(JSON.stringify({ shelfId })); await reader.write({ records: [{ recordType: 'example.com:shelf', data: payload }] });
if (!(await confirmLock())) return 'written'; try { await reader.makeReadOnly(); return 'locked'; } catch (err) { if (err.name === 'NotSupportedError') return 'written-not-lockable'; throw err; }}The external type example.com:shelf must use a domain you control and, with the domain converted to ASCII, stay within 255 bytes; reading it back yields recordType === 'example.com:shelf' with the same bytes in record.data.
See also
Section titled “See also”- Web Bluetooth API, for nearby Bluetooth Low Energy devices, a separate transport that NFC tag scanning does not cover
- WebHID API
- WebUSB API
- Web NFC: NDEFReader scan() method (w3c-cg.github.io)
- Web NFC: security policies (w3c-cg.github.io)
- WebKit standards position: Web NFC (github.com)
- Interact with NFC devices on Chrome for Android (developer.chrome.com)
Specifications
| Specification | Status |
|---|---|
| Web NFC API | Community draft |
| Web NFC: NDEFReader scan() method | Community draft |
| Web NFC: NDEFReader write() method | Community draft |
| Web NFC: NDEFReader makeReadOnly() method | Community draft |
- Legend
- Yes
- Partial
- Flag
- No
- Unknown
| Browser / Platform | Support | Versions | Confidence | Source | Notes |
|---|---|---|---|---|---|
| Chrome (Desktop)# | No | — | high | source | 1 |
| Chrome (Android)# | Yes | 89 | high | source | — |
| Edge (Desktop)# | No | — | high | source | 23 |
| Firefox (Desktop)# | No | — | high | source | 4 |
| Firefox (Android)# | No | — | high | source | 56 |
| Safari (macOS)# | No | — | high | source | 7 |
| Safari (iOS)# | No | — | high | source | 89 |
| Samsung Internet# | Yes | 15.0 | high | source | 10 |
| WebView (Android)# | Yes | 89 | high | source | 11 |
- No Chrome support is recorded in browser-compat-data.
- No Edge support is recorded in browser-compat-data.
- Derived by browser-compat-data mirroring from Chrome.
- No Firefox support is recorded in browser-compat-data.
- No Firefox for Android support is recorded in browser-compat-data.
- Derived by browser-compat-data mirroring from Firefox.
- No Safari support is recorded in browser-compat-data.
- No Safari on iOS support is recorded in browser-compat-data.
- Derived by browser-compat-data mirroring from Safari.
- Derived by browser-compat-data mirroring from Chrome Android.
- Derived by browser-compat-data mirroring from Chrome Android.