Welcome to a tutorial on how to read and write NFC tags in Javascript. Yes, you read that right. It is totally possible to work with NFC tags in web apps – Read on for the examples!
TABLE OF CONTENTS
JAVASCRIPT NFC
All right, let us now get into the examples of reading and writing NFC tags in Javascript.
1) READ & WRITE TO NFC TAGS
1A) THE HTML
<!-- (A) NFC TAG ACTIONS -->
<div id="demoNFC">
<input type="text" id="demoT" value="Hello World" required>
<input type="button" id="demoW" value="Write" disabled onclick="nfc.write();">
<input type="button" id="demoR" value="Read" disabled onclick="nfc.read()">
</div>
<!-- (B) "CONSOLE MESSAGES" -->
<div id="demoMSG"></div>
First, let us start with a little bit of the HTML interface. This should be pretty self-explanatory.
<input id="demoT">
Write this text into the NFC tag.<input id="demoW">
Engage NFC write mode.<input id="demoR">
Engage NFC read mode.<div id="demoMSG">
Well, debugging is still a pain on Android devices… You have to enable developer mode and connect to a PC to show console messages. So this little section will show the “debug messages” without the need to connect to a PC.
1B) JAVASCRIPT – INIT
var nfc = {
// (A) INIT
hTxt : null, // html data to write
hWrite : null, // html write button
hRead : null, // html read button
hMsg : null, // html "console messages"
init : () => {
// (A1) GET HTML ELEMENTS
nfc.hTxt = document.getElementById("demoT"),
nfc.hWrite = document.getElementById("demoW"),
nfc.hRead = document.getElementById("demoR"),
nfc.hMsg = document.getElementById("demoMSG");
// (A2) FEATURE CHECK + GET PERMISSION
if ("NDEFReader" in window) {
nfc.logger("Ready");
nfc.hWrite.disabled = false;
nfc.hRead.disabled = false;
nfc.hReadOnly.disabled = false;
} else { nfc.logger("Web NFC is not supported on this browser."); }
},
// (B) HELPER - DISPLAY LOG MESSAGE
logger : msg => {
let row = document.createElement("div");
row.innerHTML = msg;
nfc.hMsg.appendChild(row);
},
// ...
};
window.onload = nfc.init;
The first 2 sections of the Javascript do nothing more than “boring initialization”.
init()
Runs on window load. Gets all the HTML elements, checks if Web NFC is supported, and enables the HTML interface accordingly.logger()
A helper function to display a message in<div id="demoMSG">
.
1C) JAVASCRIPT – WRITE TO NFC TAG
// (C) WRITE NFC TAG
write : () => {
nfc.logger("Approach NFC Tag");
const ndef = new NDEFReader();
ndef.write(nfc.hTxt.value)
.then(() => nfc.logger("Write OK"))
.catch(err => nfc.logger("ERROR - " + err.message));
},
No sweat, ndef.write()
is all you need. This simple example writes a flat string into the NFC tag, but NFC tags actually offer a lot more… Will go through more below.
1D) JAVASCRIPT – READ FROM NFC TAG
// (D) READ NFC TAG
read : () => {
nfc.logger("Approach NFC Tag");
const ndef = new NDEFReader();
ndef.scan()
.then(() => {
ndef.onreadingerror = err => nfc.logger("Read failed");
ndef.onreading = evt => {
const decoder = new TextDecoder();
for (let record of evt.message.records) {
nfc.logger("Record type: " + record.recordType);
nfc.logger("Record encoding: " + record.encoding);
nfc.logger("Record data: " + decoder.decode(record.data));
}
};
})
.catch(err => nfc.logger("Read error - " + err.message));
}
No sweat, just use ndef.scan()
to read an NFC tag. But a little bit of text decoding is required.
2) NFC RECORD FORMATS
ndef.write({
records: [
{ recordType:"text", data:"Hello World" },
{ recordType:"url", data:"https://code-boxx.com/" },
{ recordType:"url", data:"sms:12345678" },
{ recordType:"url", data:"tel:12345678" },
{ recordType:"url", data:"mailto:jon@doe.com?subject=Title&body=Body" },
{ recordType:"url", data:"geo:35.698723,139.772639" },
{ recordType:"empty" }
]
})
.then(() => nfc.logger("Write OK"))
.catch(err => nfc.logger("ERROR - " + err.message));
Apart from plain text – We can also write URLs, SMS, telephone, email, geolocation, and this list is not even exhaustive. NFC is capable of WIFI records (tap to connect to WIFI network), vCard, Bitcoin wallet, opening an app, smart posters, and even storing entire files.
P.S. Yes, an NFC tag is capable of storing multiple records.
P.P.S. To “erase” an NFC tag, just write a single empty record.
3) SET NFC TAG TO READ-ONLY
const ndef = new NDEFReader();
ndef.makeReadOnly()
.then(() => nfc.logger("Tag is now read only."))
.catch(err => nfc.logger("ERROR - " + err.message));
To “lock an NFC tag”, run the ndef.makeReadOnly()
function. Take extra note though, this is permanent. There is seemingly no way to make the tag writable again, at least in Web NFC.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- NFC – CanIUse
At the time of writing, Web NFC is pretty much an experimental feature supported on Android Chrome and Baidu browser only. It can also be enabled in Opera by toggling the “enable experimental features” flag.
LINKS & REFERENCES
- Web NFC API – MDN
- Interact with NFC devices on Chrome for Android – Web.dev
- W3C Web NFC Examples – GitHub
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
It works perfectly, thanks.
hi, this nfc will work when i tap with mobile?
See COMPATIBILITY CHECKS above.