2 min read

Web NFC API

The Web NFC API allows web applications to read and write to Near Field Communication (NFC) tags when they are in close proximity to the user's device (usually 5-10 cm, 2-4 inches). This opens up possibilities for inventory management, museum guides, and configuring IoT devices directly from the browser.

1. The Concept

Web NFC focuses on NDEF (NFC Data Exchange Format) tags. It does not support low-level ISO-DEP (ISO 14443-4) communication (like reading credit cards or passports directly).

2. Reading NFC Tags

To read tags, you use the NDEFReader object.

  1. Create Reader: const reader = new NDEFReader();
  2. Scan: Call reader.scan(). This prompts the user for permission.
  3. Listen: Handle the reading event.
const scanButton = document.getElementById("scanButton");

scanButton.addEventListener("click", async () => {
  try {
    const ndef = new NDEFReader();
    await ndef.scan();
    console.log("> Scan started");

    ndef.addEventListener("readingerror", () => {
      console.log("Argh! Cannot read data from the NFC tag. Try another one?");
    });

    ndef.addEventListener("reading", ({ message, serialNumber }) => {
      console.log(`> Serial Number: ${serialNumber}`);
      console.log(`> Records: (${message.records.length})`);

      for (const record of message.records) {
        console.log(`  Record type:  ${record.recordType}`);
        console.log(`  MIME type:    ${record.mediaType}`);
        console.log(`  Record id:    ${record.id}`);

        // Decode data based on record type
        const textDecoder = new TextDecoder(record.encoding);
        console.log(`  Data: ${textDecoder.decode(record.data)}`);
      }
    });
  } catch (error) {
    console.log("Argh! " + error);
  }
});

3. Writing to NFC Tags

To write data, you use the write() method on an NDEFReader instance.

const writeButton = document.getElementById("writeButton");

writeButton.addEventListener("click", async () => {
  try {
    const ndef = new NDEFReader();

    // Write a simple text record
    await ndef.write("Hello World");
    console.log("> Message written");

  } catch (error) {
    console.log("Argh! " + error);
  }
});

4. Security and Privacy

  • HTTPS: Only works on secure contexts.
  • User Gesture: scan() and write() must be triggered by a user interaction.
  • Visibility: Only works when the web page is visible (foreground).
  • Browser Support: Primarily supported in Chrome for Android.

programming/javascript/vanilla/javascript programming/javascript/vanilla/promises-async-await programming/javascript/vanilla/events