Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active June 25, 2023 02:20
Show Gist options
  • Save code-boxx/f10e18b84e4c7f2ba46ac752f269d2b6 to your computer and use it in GitHub Desktop.
Save code-boxx/f10e18b84e4c7f2ba46ac752f269d2b6 to your computer and use it in GitHub Desktop.
Javascript Read Write NFC Tag

JAVASCRIPT READ & WRITE NFC TAGS

https://code-boxx.com/read-write-nfc-javascript/

NOTES

  1. Take note that https:// and access permission is required for Web NFC to work properly.
  2. Web NFC is still in the experimental phase at the time of writing. It is only supported on a few browsers, and it may change over time.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<!DOCTYPE html>
<html>
<head>
<title>Web NFC Read Write</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="x-dummy.css">
<script defer src="1-read-write.js"></script>
</head>
<body>
<!-- (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>
</body>
</html>
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);
},
// (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));
},
// (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));
}
};
window.onload = nfc.init;
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));
const ndef = new NDEFReader();
ndef.makeReadOnly()
.then(() => nfc.logger("Tag is now read only."))
.catch(err => nfc.logger("ERROR - " + err.message));
/* (X) NOT IMPORTANT */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
font-size: 1rem;
}
body, input, #demoNFC, #demoMSG { padding: 10px; }
body { max-width: 600px; }
#demoNFC {
display: flex;
margin-bottom: 10px;
border: 1px solid #e7e7e7;
background: #f3f3f3;
}
#demoT { flex-grow: 1; }
input {
padding: 10px;
border: 0;
}
input[type=button] {
margin: 0 1px;
color: #fff;
background: #225cc5;
cursor: pointer;
}
input[type=button]:disabled {
color: #7c7c7c;
background: #c3c3c3;
}
#demoMSG {
border: 1px solid #e7e7e7;
background: #fff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment