Search code examples
javascriptnfcndef

Set NDEF message on Android Chrome


I would like to set an NDEF message on my website if it is opened from android chrome and read it with an NFC Reader using nfcpy.

According to https://developer.mozilla.org/en-US/docs/Web/API/NDEFMessage/NDEFMessage I think I should be able to do this.

My page looks like this:

<button onclick="set_ndef()">Set NDEF msg</button>
<pre id="log"></pre>

<script>
async function set_ndef() {
  if ("NDEFReader" in window) {
    try {
      const ndefmsg = new NDEFMessage({'records': [{'recordType': 'text', 'data': 'asd'}]});
      consoleLog(ndefmsg)
    } catch(error) {
      consoleLog(error);
    }
  } else {
    consoleLog("Web NFC is not supported.");
  }
}

function consoleLog(data) {
    var logElement = document.getElementById('log');
    logElement.innerHTML += data + '\n';
}
</script>

The website uses HTTPS, and when I press the button an NDEFRecord object is printed into the div.

I have an acr122u NFC reader, which I was able to set up using nfcpy:

import nfc
import time    

def on_connect(tag):
    print(tag.identifier.hex())
    tag_ident = tag.identifier.hex()[:8]
    print(tag.ndef)
    if tag.ndef:
        for record in tag.ndef:
            print(record)
    return True


while True:
    with nfc.ContactlessFrontend('usb') as clf:
        tag = clf.connect(rdwr={'on-connect': on_connect, 'beep-on-connect': True})
    time.sleep(1)

After I place my phone on the reader (after pressing the button on the page) I am only able to read the UID of the phone, but the tag.ndef is None

How can I do this (if I am even able to)?


Solution

  • https://stackoverflow.com/a/65659726/2373819 should give you some background as why this won't work, Android Chrome NFC is an NFC reader and 2 readers won't work.

    Though with the acr122u NFC reader can usually be configure to behave as an NFC Tag, then Android Chrome should be able read and write NDEF messages to it (https://nfcpy.readthedocs.io/en/latest/topics/get-started.html#emulate-a-card)