Last active
January 21, 2023 06:26
-
-
Save TheBrenny/7a968805bb1dcd25d7b008b1fdef746a to your computer and use it in GitHub Desktop.
Testing the Web NFC API: https://gistpreview.github.io/?7a968805bb1dcd25d7b008b1fdef746a
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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