-
Notifications
You must be signed in to change notification settings - Fork 40
/
webnfc.js
92 lines (84 loc) · 3.16 KB
/
webnfc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
function log(msg) {
const logElem = document.getElementById("log");
logElem.innerText += msg + "\n";
}
log("WebNFC available: " + ("NDEFReader" in window));
const mimeType = "application/x-rbyerstest";
let abortController = null;
document.getElementById("abort").onclick = event => {
if (abortController) {
abortController.abort();
abortController = null;
}
};
document.getElementById('init').addEventListener("click", async () => {
log("Initializing card");
let start = new Date();
try {
const ndef = new NDEFReader();
const encoder = new TextEncoder();
await ndef.write({records: [
{recordType: "mime", mediaType: mimeType, data: encoder.encode("0")}
]});
log("Card initialized, duration: " + (new Date() - start) + "ms");
} catch (error) {
log("Error: " + error);
}
});
document.getElementById('scan').addEventListener("click", async () => {
log("Scan started");
try {
let start = new Date();
abortController = new AbortController();
abortController.signal.onabort = event => {
log("Abort");
};
const ndef = new NDEFReader();
await ndef.scan({ signal: abortController.signal });
ndef.addEventListener("readingerror", () => {
log("NFC tag read error");
});
ndef.addEventListener("reading", async ({ message, serialNumber }) => {
try {
let readTime = new Date();
log(`Found card, ${readTime - start}ms.`);
log(` Serial Number: ${serialNumber}`);
for (const record of message.records) {
log(" Record type: " + record.recordType);
log(" MIME type: " + record.mediaType);
log(" Record id: " + record.id);
log(" Encoding: " + record.encoding);
switch (record.recordType) {
case "text":
const text = new TextDecoder().decode(record.data);
log(` Text: ${text} (${record.lang})`);
break;
case "url":
const url = new TextDecoder().decode(record.data);
log(" Url: " + url);
break;
case "mime":
if (record.mediaType == mimeType) {
const text = new TextDecoder().decode(record.data);
let count = parseInt(text);
count++;
log(" Updating count to: " + count);
const encoder = new TextEncoder();
await ndef.write({ signal: abortController.signal, records: [
{recordType: "mime", mediaType: mimeType, data: encoder.encode(count)}
]});
log(` Update complete, duration: ${new Date() - readTime}ms`);
}
break;
default:
log(" Unknown record type");
}
}
} catch (error) {
log("Error: " + error);
}
});
} catch (error) {
log("Error: " + error);
}
});