Created
September 12, 2022 05:04
-
-
Save osmianski/45e94623f627e6719a406a8de18624ed to your computer and use it in GitHub Desktop.
Put this file under HTTPS server, access it from your phone's Chrome, and scan NFC tags around you :)
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>NFC Test</title> | |
</head> | |
<body> | |
<button id="scan" style="display: none;">Scan</button> | |
<pre id="output"> | |
</pre> | |
<script> | |
const output = document.getElementById('output'); | |
function startScanning() { | |
try { | |
const ndef = new NDEFReader(); | |
ndef.scan().then(() => { | |
output.innerText += "Scan started successfully.\n"; | |
ndef.onreadingerror = (error) => { | |
output.innerText += "Cannot read data from the NFC tag. Try another one?\n"; | |
}; | |
ndef.onreading = event => { | |
const message = event.message; | |
for (const record of message.records) { | |
output.innerText += `Record type: ${record.recordType}\n`; | |
output.innerText += `MIME type: ${record.mediaType}\n`; | |
output.innerText += `Record id: ${record.id}\n`; | |
output.innerText += JSON.stringify(record); | |
} | |
}; | |
}).catch(error => { | |
output.innerText += `Error! Scan failed to start: ${error}.\n`; | |
}); | |
} | |
catch (error) { | |
output.innerText += `NFC Initialization error: ${error}.\n`; | |
} | |
} | |
function checkPermissions() { | |
try { | |
navigator.permissions.query({ name: "nfc" }).then(nfcPermissionStatus => { | |
if (nfcPermissionStatus.state === "granted") { | |
// NFC access was previously granted, so we can start NFC scanning now. | |
startScanning(); | |
} else { | |
// Show a "scan" button. | |
document.querySelector("#scan").style.display = "block"; | |
document.querySelector("#scan").onclick = () => { | |
// Prompt user to allow UA to send and receive info when they tap NFC devices. | |
startScanning(); | |
}; | |
} | |
}).catch(error => { | |
output.innerText += `Can't check NFC permissions: ${error}.\n`; | |
}); | |
} | |
catch (error) { | |
output.innerText += `NFC permission check error: ${error}.\n`; | |
} | |
} | |
checkPermissions(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment