Friday, May 25, 2012

Read and Write NFC Tags with PhoneGap

The phonegap-nfc plugin allows you to read and write NFC tags from a PhoneGap application using JavaScript.

The plugin originally supported Android. The latest release adds support for Blackberry 7.0.

After installing the plugin into your PhoneGap app (See README) it is easy to start scanning tags.

Create a function that will handle the NFC events.

function onNfc(nfcEvent) {
    // display the tag as JSON
    alert(JSON.stringify(nfcEvent.tag));
}

Create the optional success and failure callbacks. These callbacks are for success and failure of adding the listener.

function success(result) {
    console.log("Listening for NFC Messages");
}

function failure(reason) {
    alert("Failed to add NDEF listener");
}

Register listener. When the listener is added, the plugin will generate an NFC Event whenever a tag is scanned.

nfc.addNdefListener(onNfc, success, failure);

Deploy the application and scan a tag.

Example Project

The NFC Reader example project has been updated for Blackberry.

More info

The PhoneGap NFC API is documented in the README file.

Kevin wrote Building NFC applications with Android last year. Most of that information still applies.

3 comments:

  1. I have been using the phonegap nfc plugin for a while. Recently, new un-formatted tags would get formatted with the nfc.erase function, but I don't this works anymore.

    I read that there was a bug with NFC formatting nfc tags in android 4.0. It should be fixed, but I still cannot format tags with 4.1?

    Have you noticed, or have any information about this?

    Thank you for the code... It has really helped me with my projects

    ReplyDelete
    Replies
    1. I think think we can fix this. EraseTag changed when I added Blackberry support.

      This is probably covered by Issue #20 https://github.com/chariotsolutions/phonegap-nfc/issues/20

      If you'd like, add some details on how to reproduce in the comments for that issue.

      Delete
  2. I just started looking at your PhoneGap Build NFC plugin for Android... great stuff. I'm using the nfc.addNDEFListener code exactly as in your sample... and it works great. I'd like to remove that listener so that I can add another. I'm scanning the same tag for 2 different lookup tables and if I add a 2nd listener then both fire. I see you have

    removeNdefListener: function (callback, win, fail) {
    document.removeEventListener("ndef", callback, false);
    cordova.exec(win, fail, "NfcPlugin", "removeNdef", []);

    available in the code. How would I use this to remove a listener I added? Thanks very much.

    David

    ReplyDelete