File size: 2,116 Bytes
3cf1131
cfb2c08
3cf1131
50eaf63
3cf1131
 
 
50eaf63
 
 
 
3cf1131
50eaf63
 
 
 
 
3cf1131
50eaf63
3cf1131
50eaf63
 
 
3cf1131
50eaf63
 
 
 
3cf1131
50eaf63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cf1131
50eaf63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cf1131
 
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
<!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>