Skip to content

Instantly share code, notes, and snippets.

@TheBrenny
Last active January 21, 2023 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheBrenny/7a968805bb1dcd25d7b008b1fdef746a to your computer and use it in GitHub Desktop.
Save TheBrenny/7a968805bb1dcd25d7b008b1fdef746a to your computer and use it in GitHub Desktop.
<html>
<head>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
padding: 2em;
}
script {
display: block;
max-width: 500px;
padding: 2em;
overflow: scroll;
}
button {
display: block;
margin: 2em;
width: 10em;
height: 3em;
}
textarea {
max-width: 500px;
width: 100%;
}
</style>
</head>
<body>
<p>This HTML and JS code tests out the capabilities of the Web NFC API by letting you interrogate the records from NFC tags.</p>
<p>Written by TheBrenny, adapted from Google's example.</p>
<button id="scanButton">Scan</button>
<button id="writeButton">Write</button>
<textarea id="output" rows="15"></textarea>
<pre>
<script>
const $ = (selector) => document.querySelector(selector);
const outputBox = $("#output");
function log(data) {
outputBox.value += data + "\n";
}
$("#scanButton").addEventListener("click", async () => {
log("User clicked scan button");
try {
const ndef = new NDEFReader();
await ndef.scan();
log("> Scan started");
ndef.addEventListener("readingerror", () => {
log("Argh! Cannot read data from the NFC tag. Try another one?");
});
ndef.addEventListener("reading", ({ message, serialNumber }) => {
log(`> Serial Number: ${serialNumber}`);
log(`> Records: ${message.records.length}`);
message.records.forEach((r, i) => {
const recordObj = {
recordType: r.recordType,
mediaType: r.mediaType,
id: r.id,
data: r.data,
encoding: r.encoding,
lang: r.lang,
};
log(`> Record ${i+1}: ${JSON.stringify(recordObj, null, 2)}`);
});
});
} catch (error) {
log("Argh! " + error);
}
});
$("#writeButton").addEventListener("click", async () => {
log("User clicked write button");
try {
const ndef = new NDEFReader();
await ndef.write("Hello world!");
log("> Message written");
} catch (error) {
log("Argh! " + error);
}
});
</script>
</pre>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment