NFC
The Web NFC API is a low-level API that provides sites the ability to read and write to nearby NFC (Near-Field Communication) devices.
It allows starting up a scan that informs when an NFC tag has been tapped. It also provides a method to write a message via NFC.
Current support is limited to an experimental implementation in Chrome, available behind the "experimental-web-platform-features" flag on Android. There was also Firefox OS experimental implementation that is moz
-prefixed and doesn't follow the current state of the specification draft.
API glimpse
const ndef = new NDEFReader()
- Creates an object used for interacting with NDEF formatted NFC tags.
ndef.scan(options)
- Returns a
Promise
resolved if starting NFC scan was successful. ndef.addEventListener('reading', listener)
- An event fired when a new reading is available.
ndef.addEventListener('readingerror', listener)
- An event fired when an error happened during reading.
ndef.write(message, options)
- Returns a
Promise
resolved if writing themessage
(String, ArrayBuffer or NDEF record) withoptions
was successful.
Live Demo
Based on the code snippets from specification draft.
-
async function readTag() { if ("NDEFReader" in window) { const ndef = new NDEFReader(); try { await ndef.scan(); ndef.onreading = event => { const decoder = new TextDecoder(); for (const record of event.message.records) { consoleLog("Record type: " + record.recordType); consoleLog("MIME type: " + record.mediaType); consoleLog("=== data ===\n" + decoder.decode(record.data)); } } } catch(error) { consoleLog(error); } } else { consoleLog("Web NFC is not supported."); } } async function writeTag() { if ("NDEFReader" in window) { const ndef = new NDEFReader(); try { await ndef.write("What Web Can Do Today"); consoleLog("NDEF message written!"); } catch(error) { consoleLog(error); } } else { consoleLog("Web NFC is not supported."); } } function consoleLog(data) { var logElement = document.getElementById('log'); logElement.innerHTML += data + '\n'; };
-
<p> <button onclick="readTag()">Test NFC Read</button> <button onclick="writeTag()">Test NFC Write</button> </p> <pre id="log"></pre> <p><small>Based on the code snippets from <a href="https://w3c.github.io/web-nfc/#examples">specification draft</a>.</small></p>