-
Notifications
You must be signed in to change notification settings - Fork 0
/
nfc.html
100 lines (92 loc) · 2.85 KB
/
nfc.html
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
93
94
95
96
97
98
99
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=no">
<meta name='mobile-web-app-capable' content='yes'>
<title>NFC Test Page</title>
<style>
#log {
border: 1px solid black;
background: rgba(182, 182, 182, 0.5);
}
</style>
</head>
<script>
function log(str) {
document.getElementById('log').innerHTML += '<div>' + str + '</div>';
}
function isInNavigatorInterface(str) {
return (str in navigator);
}
function isAPIPresent() {
return isInNavigatorInterface('nfc');
}
addEventListener('load', function() {
var hasAPI = isAPIPresent();
if (!hasAPI) {
log('NFC API not found.');
return;
}
log('NFC API found.');
});
function push(nfc, text) {
log("Pushing message: " + text);
nfc.push(text)
.then(() => {
log("Message pushed.");
}).catch((error) => {
log("Push failed with error: " + error.message);
});
}
function watch(nfc) {
nfc.watch((message) => {
if (message.data[0].recordType == 'empty') {
log('Read empty message');
} else {
log('Read message written by ' + message.url);
processMessage(message);
}
}).then(() => {
log("Added a watch.");
}).catch((error) => {
log("Adding watch failed with error: " + error.message);
});
function processMessage(message) {
for (let record of message.data) {
switch (record.recordType) {
case "text":
log('Data is text: ' + record.data);
break;
case "url":
log('Data is URL: ' + record.data);
break;
case "json":
log('JSON data: ' + record.data.myProperty.toString());
break;
case "opaque":
if (record.mediaType == 'image/png') {
var img = document.createElement("img");
img.src = URL.createObjectURL(new Blob(record.data, record.mediaType));
img.onload = function() {
window.URL.revokeObjectURL(this.src);
};
}
break;
}
}
}
}
</script>
<body>
<div>colinblundell.github.com</div>
<button type='button' onclick='push(navigator.nfc, document.getElementById("textfield").value);'>Push message to tag:</button>
<input type="text" name="textfield" id="textfield" /><br>
<button type='button' onclick='watch(navigator.nfc);'>Read data from tag</button><br>
<div id='log'></div>
<script>
</script>
<iframe srcdoc="<button type='button' onclick='parent.push(navigator.nfc, document.getElementById("textfield").value);'>Push message to tag from iframe:</button> <input type='text' name='textfield' id='textfield' /><br> <button type='button' onclick='parent.watch(navigator.nfc);'>Read data from tag from iframe</button><br>"
>
</iframe>
</body>
</html>