NFC / index.html
Dmtlant's picture
Update index.html
50eaf63 verified
<!DOCTYPE html>
<html>
<head>
<title>NFC Reader</title>
</head>
<body>
<div id="nfc-data"></div>
<script>
const nfcDataDisplay = document.getElementById('nfc-data');
if (!window.NFC) {
nfcDataDisplay.textContent = "NFC API not supported by your browser.";
console.error("NFC API not supported.");
return;
}
const reader = new window.NFC();
reader.onreading = (event) => {
const tag = event.tag;
nfcDataDisplay.textContent = ''; // Clear previous data
if (tag) {
if (tag.ndefMessage) {
try {
let dataString = "";
for (let i = 0; i < tag.ndefMessage.length; i++) {
const record = tag.ndefMessage[i];
if(record.type === 'application'){
dataString += "Application record found: " + record.id + "\n";
}
if (record.type === 'text') {
const text = new TextDecoder('utf-8').decode(record.payload);
dataString += `Text record: ${text}\n`;
}
if (record.type === 'mime') {
dataString += `MIME record: ${record.mime} ${new TextDecoder('utf-8').decode(record.payload)}\n`;
}
if (record.type === 'uri') {
dataString += `URI record: ${new TextDecoder('utf-8').decode(record.payload)}\n`;
}
// Add more cases for other types as needed
}
nfcDataDisplay.textContent = dataString || "No readable data.";
} catch (error) {
console.error("Error processing data:", error);
nfcDataDisplay.textContent = "Error reading data";
}
} else {
nfcDataDisplay.textContent = "No NDEF message found.";
}
} else {
nfcDataDisplay.textContent = "No tag detected.";
}
};
reader.ondisconnect = () => {
nfcDataDisplay.textContent = "NFC tag removed.";
};
reader.onerror = (error) => {
nfcDataDisplay.textContent = "Error: " + error.message;
console.error("NFC error:", error);
};
reader.start(); // Start listening for NFC tags
</script>
</body>
</html>