How to get plain text from NDEF Record object?

1.3k Views Asked by At

I am trying to read the NFC tag using Web NFC. I've received the message object, I am able to read the record message.records[0], but I am not able to get the plain text "Hello world" stored in that NFC record.

scanRfid.addEventListener("click", async () => {
  //curlog("User clicked scan button");

  try {
    const reader = new NDEFReader();
    await reader.scan();
   // curlog("> Scan started");

    reader.addEventListener("error", (event) => {
      console.log(`Argh! ${event.message}`);
    });

    reader.addEventListener("reading", ({ message, serialNumber }) => {
      
      //curlog(`> Records: (${message.records})`);
      //processMessage(message);
      console.log(message.records[0[);
      
    });
  } catch (error) {
    curlog("Argh! " + error);
  }
});
1

There are 1 best solutions below

0
On

As described at https://web.dev/nfc/#read-and-write-a-text-record, the text record data can be decoded with a TextDecoder instantiated with the record encoding property. Note that the language of the text record is available through its lang property.

function readTextRecord(record) {
  console.assert(record.recordType === "text");
  const textDecoder = new TextDecoder(record.encoding);
  console.log(`Text: ${textDecoder.decode(record.data)} (${record.lang})`);
}