Git Product home page Git Product logo

phonegap-nfc's Introduction

PhoneGap NFC Plugin

The NFC plugin allows you to read and write NFC tags. You can also beam to, and receive from, other NFC enabled devices.

Use to

  • read data from NFC tags
  • write data to NFC tags
  • send data to other NFC enabled devices
  • receive data from NFC devices
  • send raw commands (ISO 14443-3A, ISO 14443-3A, ISO 14443-4, JIS 6319-4, ISO 15693) to NFC tags

This plugin uses NDEF (NFC Data Exchange Format) for maximum compatibilty between NFC devices, tag types, and operating systems.

Supported Platforms

  • Android
  • iOS 11
  • Windows (includes Windows Phone 8.1, Windows 8.1, Windows 10)
  • BlackBerry 10
  • Windows Phone 8
  • BlackBerry 7

Contents

Installing

Cordova

$ cordova plugin add phonegap-nfc

PhoneGap

$ phonegap plugin add phonegap-nfc

PhoneGap Build

Edit config.xml to install the plugin for PhoneGap Build.

<preference name="phonegap-version" value="cli-9.0.0" />
<plugin name="phonegap-nfc" source="npm" />

Windows Phone 8.1 should use the windows platform. The Silverlight based Windows Phone 8 code is no longer being maintained.

BlackBerry 7 support is only available for Cordova 2.x. For applications targeting BlackBerry 7, you may need to use an older version of phonegap-nfc.

See Getting Started and Getting Started BlackBerry 10for more details.

iOS Notes

Reading NFC NDEF tags is supported on iPhone 7 (and newer) since iOS 11. iOS 13 added support for writing NDEF messages to NFC tags. iOS 13 also adds the ability to get the UID from some NFC tags. On iOS, the user must start a NFC session to scan for a tag. This is different from Android which can constantly scan for NFC tags. The nfc.scanNdef and nfc.scanTag functions start a NFC scanning session. The NFC tag is returned to the caller via a Promise. If your existing code uses the deprecated nfc.beginSession, update it to use nfc.scanNdef.

The scanNdef function uses NFCNDEFReaderSession to detect NFC Data Exchange Format (NDEF) tags. scanTag uses the newer NFCTagReaderSession available in iOS 13 to detect ISO15693, FeliCa, and MIFARE tags. The scanTag function will include the tag UID and tag type for some NFC tags along with the NDEF messages. scanTag can also read some RFID tags without NDEF messsages. scanTag will not scan some NDEF tags including Topaz and Mifare Classic.

You must call nfc.scanNdef and nfc.scanTag before every scan.

Writing NFC tags on iOS uses the same nfc.write function as other platforms. Although it's the same function, the behavior is different on iOS. Calling nfc.write on an iOS device will start a new scanning session and write data to the scanned tag.

NFC

The nfc object provides access to the device's NFC sensor.

Methods

ReaderMode

Tag Technology Functions

nfc.addNdefListener

Registers an event listener for any NDEF tag.

nfc.addNdefListener(callback, [onSuccess], [onFailure]);

Parameters

  • callback: The callback that is called when an NDEF tag is read.
  • onSuccess: (Optional) The callback that is called when the listener is added.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.addNdefListener registers the callback for ndef events.

A ndef event is fired when a NDEF tag is read.

For BlackBerry 10, you must configure the type of tags your application will read with an invoke-target in config.xml.

On Android registered mimeTypeListeners takes precedence over this more generic NDEF listener.

On iOS you must call beingSession before scanning a tag.

Supported Platforms

  • Android
  • iOS
  • Windows
  • BlackBerry 7
  • BlackBerry 10
  • Windows Phone 8

nfc.removeNdefListener

Removes the previously registered event listener for NDEF tags added via nfc.addNdefListener.

nfc.removeNdefListener(callback, [onSuccess], [onFailure]);

Removing listeners is not recommended. Instead, consider that your callback can ignore messages you no longer need.

Parameters

  • callback: The previously registered callback.
  • onSuccess: (Optional) The callback that is called when the listener is successfully removed.
  • onFailure: (Optional) The callback that is called if there was an error during removal.

Supported Platforms

  • Android
  • iOS
  • Windows
  • BlackBerry 7

nfc.addTagDiscoveredListener

Registers an event listener for tags matching any tag type.

nfc.addTagDiscoveredListener(callback, [onSuccess], [onFailure]);

Parameters

  • callback: The callback that is called when a tag is detected.
  • onSuccess: (Optional) The callback that is called when the listener is added.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.addTagDiscoveredListener registers the callback for tag events.

This event occurs when any tag is detected by the phone.

Supported Platforms

  • Android
  • Windows
  • BlackBerry 7

Note that Windows Phones need the newere NXP PN427 chipset to read non-NDEF tags. That tag will be read, but no tag meta-data is available.

nfc.removeTagDiscoveredListener

Removes the previously registered event listener added via nfc.addTagDiscoveredListener.

nfc.removeTagDiscoveredListener(callback, [onSuccess], [onFailure]);

Removing listeners is not recommended. Instead, consider that your callback can ignore messages you no longer need.

Parameters

  • callback: The previously registered callback.
  • onSuccess: (Optional) The callback that is called when the listener is successfully removed.
  • onFailure: (Optional) The callback that is called if there was an error during removal.

Supported Platforms

  • Android
  • Windows
  • BlackBerry 7

nfc.addMimeTypeListener

Registers an event listener for NDEF tags matching a specified MIME type.

nfc.addMimeTypeListener(mimeType, callback, [onSuccess], [onFailure]);

Parameters

  • mimeType: The MIME type to filter for messages.
  • callback: The callback that is called when an NDEF tag matching the MIME type is read.
  • onSuccess: (Optional) The callback that is called when the listener is added.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.addMimeTypeListener registers the callback for ndef-mime events.

A ndef-mime event occurs when a Ndef.TNF_MIME_MEDIA tag is read and matches the specified MIME type.

This function can be called multiple times to register different MIME types. You should use the same handler for all MIME messages.

nfc.addMimeTypeListener("text/json", *onNfc*, success, failure);
nfc.addMimeTypeListener("text/demo", *onNfc*, success, failure);

On Android, MIME types for filtering should always be lower case. (See IntentFilter.addDataType())

Supported Platforms

  • Android
  • BlackBerry 7

nfc.removeMimeTypeListener

Removes the previously registered event listener added via nfc.addMimeTypeListener.

nfc.removeMimeTypeListener(mimeType, callback, [onSuccess], [onFailure]);

Removing listeners is not recommended. Instead, consider that your callback can ignore messages you no longer need.

Parameters

  • mimeType: The MIME type to filter for messages.
  • callback: The previously registered callback.
  • onSuccess: (Optional) The callback that is called when the listener is successfully removed.
  • onFailure: (Optional) The callback that is called if there was an error during removal.

Supported Platforms

  • Android
  • BlackBerry 7

nfc.addNdefFormatableListener

Registers an event listener for formatable NDEF tags.

nfc.addNdefFormatableListener(callback, [onSuccess], [onFailure]);

Parameters

  • callback: The callback that is called when NDEF formatable tag is read.
  • onSuccess: (Optional) The callback that is called when the listener is added.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.addNdefFormatableListener registers the callback for ndef-formatable events.

A ndef-formatable event occurs when a tag is read that can be NDEF formatted. This is not fired for tags that are already formatted as NDEF. The ndef-formatable event will not contain an NdefMessage.

Supported Platforms

  • Android

nfc.write

Writes an NDEF Message to a NFC tag.

A NDEF Message is an array of one or more NDEF Records

var message = [
    ndef.textRecord("hello, world"),
    ndef.uriRecord("http://github.com/chariotsolutions/phonegap-nfc")
];

nfc.write(message, [onSuccess], [onFailure]);

Parameters

  • ndefMessage: An array of NDEF Records.
  • onSuccess: (Optional) The callback that is called when the tag is written.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.write writes an NdefMessage to a NFC tag.

On Android this method must be called from within an NDEF Event Handler.

On iOS this method can be called outside the NDEF Event Handler, it will start a new scanning session. Optionally you can reuse the read session to write data. See example below.

On Windows this method may be called from within the NDEF Event Handler.

On Windows Phone 8.1 this method should be called outside the NDEF Event Handler, otherwise Windows tries to read the tag contents as you are writing to the tag.

Examples

Android

On Android, write must be called inside an event handler

function onNfc(nfcEvent) {

    console.log(nfcEvent.tag);
    
    var message = [
        ndef.textRecord(new String(new Date()))
    ];
    
    nfc.write(
        message,
        success => console.log('wrote data to tag'),
        error => console.log(error)
    );

nfc.addNdefListener(onNfc);

iOS - Simple

Calling nfc.write on iOS will create a new session and write data when the user taps a NFC tag

    var message = [
        ndef.textRecord("Hello, world")
    ];

    nfc.write(
        message,
        success => console.log('wrote data to tag'),
        error => console.log(error)
    );

iOS - Read and Write

On iOS you can optionally write to NFC tag using the read session

    try {
        let tag = await nfc.scanNdef({ keepSessionOpen: true});

        // you can read tag data here
        console.log(tag);
        
        // this example writes a new message with a timestamp
        var message = [
            ndef.textRecord(new String(new Date()))
        ];

        nfc.write(
            message,
            success => console.log('wrote data to tag'),
            error => console.log(error)
        );

    } catch (err) {
        console.log(err);
    }

Supported Platforms

  • Android
  • iOS
  • Windows
  • BlackBerry 7
  • Windows Phone 8

nfc.makeReadOnly

Makes a NFC tag read only. Warning this is permanent.

nfc.makeReadOnly([onSuccess], [onFailure]);

Parameters

  • onSuccess: (Optional) The callback that is called when the tag is locked.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.makeReadOnly make a NFC tag read only. Warning this is permanent and can not be undone.

On Android this method must be called from within an NDEF Event Handler.

Example usage

onNfc: function(nfcEvent) {

    var record = [
        ndef.textRecord("hello, world")
    ];

    var failure = function(reason) {
        alert("ERROR: " + reason);
    };

    var lockSuccess = function() {
        alert("Tag is now read only.");
    };

    var lock = function() {
        nfc.makeReadOnly(lockSuccess, failure);
    };

    nfc.write(record, lock, failure);

},

Supported Platforms

  • Android

nfc.share

Shares an NDEF Message via peer-to-peer.

A NDEF Message is an array of one or more NDEF Records

var message = [
    ndef.textRecord("hello, world")
];

nfc.share(message, [onSuccess], [onFailure]);

Parameters

  • ndefMessage: An array of NDEF Records.
  • onSuccess: (Optional) The callback that is called when the message is pushed.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.share writes an NdefMessage via peer-to-peer. This should appear as an NFC tag to another device.

Supported Platforms

  • Android
  • Windows
  • BlackBerry 7
  • BlackBerry 10
  • Windows Phone 8

Platform differences

Android - shares message until unshare is called
Blackberry 10 - shares the message one time or until unshare is called
Windows Phone 8 - must be called from within a NFC event handler like nfc.write

nfc.unshare

Stop sharing NDEF data via peer-to-peer.

nfc.unshare([onSuccess], [onFailure]);

Parameters

  • onSuccess: (Optional) The callback that is called when sharing stops.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.unshare stops sharing data via peer-to-peer.

Supported Platforms

  • Android
  • Windows
  • BlackBerry 7
  • BlackBerry 10

nfc.erase

Erase a NDEF tag

nfc.erase([onSuccess], [onFailure]);

Parameters

  • onSuccess: (Optional) The callback that is called when sharing stops.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.erase erases a tag by writing an empty message. Will format unformatted tags before writing.

This method must be called from within an NDEF Event Handler.

Supported Platforms

  • Android
  • BlackBerry 7

nfc.handover

Send a file to another device via NFC handover.

var uri = "content://media/external/audio/media/175";
nfc.handover(uri, [onSuccess], [onFailure]);


var uris = [
    "content://media/external/audio/media/175",
    "content://media/external/audio/media/176",
    "content://media/external/audio/media/348"
];
nfc.handover(uris, [onSuccess], [onFailure]);

Parameters

  • uri: A URI as a String, or an array of URIs.
  • onSuccess: (Optional) The callback that is called when the message is pushed.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.handover shares files to a NFC peer using handover. Files are sent by specifying a file:// or context:// URI or a list of URIs. The file transfer is initiated with NFC but the transfer is completed with over Bluetooth or WiFi which is handled by a NFC handover request. The Android code is responsible for building the handover NFC Message.

This is Android only, but it should be possible to add implementations for other platforms.

Supported Platforms

  • Android

nfc.stopHandover

Stop sharing NDEF data via NFC handover.

nfc.stopHandover([onSuccess], [onFailure]);

Parameters

  • onSuccess: (Optional) The callback that is called when sharing stops.
  • onFailure: (Optional) The callback that is called if there was an error.

Description

Function nfc.stopHandover stops sharing data via peer-to-peer.

Supported Platforms

  • Android

nfc.showSettings

Show the NFC settings on the device.

nfc.showSettings(success, failure);

Description

Function showSettings opens the NFC settings for the operating system.

Parameters

  • success: Success callback function [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

nfc.showSettings();

Supported Platforms

  • Android
  • Windows
  • BlackBerry 10

nfc.enabled

Check if NFC is available and enabled on this device.

nfc.enabled(onSuccess, onFailure);

Parameters

  • onSuccess: The callback that is called when NFC is enabled.
  • onFailure: The callback that is called when NFC is disabled or missing.

Description

Function nfc.enabled explicitly checks to see if the phone has NFC and if NFC is enabled. If everything is OK, the success callback is called. If there is a problem, the failure callback will be called with a reason code.

The reason will be NO_NFC if the device doesn't support NFC and NFC_DISABLED if the user has disabled NFC.

Note: that on Android the NFC status is checked before every API call NO_NFC or NFC_DISABLED can be returned in any failure function.

Windows will return NO_NFC_OR_NFC_DISABLED when NFC is not present or disabled. If the user disabled NFC after the application started, Windows may return NFC_DISABLED. Windows checks the NFC status before most API calls, but there are some cases when the NFC state can not be determined.

Supported Platforms

  • Android
  • iOS
  • Windows

nfc.beginSession

beginSession is deprecated. Use scanNdef or scanTag

iOS requires you to begin a session before scanning a NFC tag.

nfc.beginSession(success, failure);

Description

beginSession is deprecated. Use scanNdef or scanTag

Function beginSession starts the NFCNDEFReaderSession allowing iOS to scan NFC tags. Use nfc.addNdefListener to receive the results of the scan.

Parameters

  • success: Success callback function called when the session begins [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

nfc.beginSession();

Supported Platforms

  • iOS

nfc.invalidateSession

invalidateSession is deprecated. Use `cancelScan``.

Invalidate the NFC session.

nfc.invalidateSession(success, failure);

Description

Function invalidateSession stops the NFCNDEFReaderSession returning control to your app.

Parameters

  • success: Success callback function called when the session in invalidated [optional]
  • failure: Error callback function, invoked when error occurs. [optional]

Quick Example

nfc.invalidateSession();

Supported Platforms

  • iOS

nfc.scanNdef

Calling scanNdef will being an iOS NFC scanning session. The NFC tag will be returned in a Promise.

nfc.scanNdef();

Description

Function scanNdef starts the NFCNDEFReaderSession allowing iOS to scan NFC tags.

Returns

  • Promise

Quick Example

// Promise
nfc.scanNdef().then(
    tag => console.log(JSON.stringify(tag)),
    err => console.log(err)
);

// Async Await
try {
    let tag = await nfc.scanNdef();
    console.log(JSON.stringify(tag));
} catch (err) {
    console.log(err);
}

Supported Platforms

  • iOS

nfc.scanTag

Calling scanTag will being an iOS NFC scanning session. The NFC tag will be returned in a Promise.

nfc.scanTag();

Description

Function scanTag starts the NFCTagReaderSession allowing iOS to scan NFC tags.

The Tag reader will attempt to get the UID from the NFC Tag. If can also read the UID from some non-NDEF tags.

Use scanNdef for reading NFC tags on iOS unless you need to get the tag UID.

Returns

  • Promise

Quick Example

// Promise
nfc.scanTag().then(
    tag => {
        console.log(JSON.stringify(tag))
        if (tag.id) {
            console.log(nfc.bytesToHexString(tag.id));
        }            
    },
    err => console.log(err)
);

// Async Await
try {
    let tag = await nfc.scanTag();
    console.log(JSON.stringify(tag));
    if (tag.id) {
        console.log(nfc.bytesToHexString(tag.id));
    }
} catch (err) {
    console.log(err);
}

Supported Platforms

  • iOS

nfc.cancelScan

Invalidate the NFC session started by scanNdef or scanTag.

nfc.cancelScan();

Description

Function cancelScan stops the NFCReaderSession returning control to your app.

Returns

  • Promise

Quick Example

nfc.cancelScan().then(
    success => { console.log('Cancelled NFC session')}, 
    err => { console.log(`Error cancelling session ${err}`)}
);

Supported Platforms

  • iOS

Reader Mode Functions

nfc.readerMode

Read NFC tags sending the tag data to the success callback.

nfc.readerMode(flags, readCallback, errorCallback);

Description

In reader mode, when a NFC tags is read, the results are returned to read callback as a tag object. Note that the normal event listeners are not used in reader mode. The callback receives the tag object without the event wrapper.

{
    "isWritable": true,
    "id": [4, 96, 117, 74, -17, 34, -128],
    "techTypes": ["android.nfc.tech.IsoDep", "android.nfc.tech.NfcA", "android.nfc.tech.Ndef"],
    "type": "NFC Forum Type 4",
    "canMakeReadOnly": false,
    "maxSize": 2046,
    "ndefMessage": [{
        "id": [],
        "type": [116, 101, 120, 116, 47, 112, 103],
        "payload": [72, 101, 108, 108, 111, 32, 80, 104, 111, 110, 101, 71, 97, 112],
        "tnf": 2
    }]
}

Foreground dispatching and peer-to-peer functions are disabled when reader mode is enabled.

The flags control which tags are scanned. One benefit to reader mode, is the system sounds can be disabled when a NFC tag is scanned by adding the nfc.FLAG_READER_NO_PLATFORM_SOUNDS flag. See Android's NfcAdapter.enableReaderMode() documentation for more info on the flags.

Parameters

  • flags: Flags indicating poll technologies and other optional parameters
  • readCallback: The callback that is called when a NFC tag is scanned.
  • errorCallback: The callback that is called when NFC is disabled or missing.

Quick Example

nfc.readerMode(
    nfc.FLAG_READER_NFC_A | nfc.FLAG_READER_NO_PLATFORM_SOUNDS, 
    nfcTag => console.log(JSON.stringify(nfcTag)),
    error => console.log('NFC reader mode failed', error)
);

Supported Platforms

  • Android

nfc.disableReaderMode

Disable NFC reader mode.

nfc.disableNfcReaderMode(successCallback, errorCallback);

Description

Disable NFC reader mode.

Parameters

  • successCallback: The callback that is called when a NFC reader mode is disabled.
  • errorCallback: The callback that is called when NFC reader mode can not be disabled.

Quick Example

nfc.disableReaderMode(
    () => console.log('NFC reader mode disabled'),
    error => console.log('Error disabling NFC reader mode', error)
)

Supported Platforms

  • Android

Tag Technology Functions

The tag technology functions provide access to I/O operations on a tag. Connect to a tag, send commands with transceive, close the tag. See the Android TagTechnology and implementations like IsoDep and NfcV for more details. These new APIs are promise based rather than using callbacks.

ISO-DEP (ISO 14443-4) Example

const DESFIRE_SELECT_PICC = '00 A4 04 00 07 D2 76 00 00 85 01 00';
const DESFIRE_SELECT_AID = '90 5A 00 00 03 AA AA AA 00'

async function handleDesfire(nfcEvent) {
    
    const tagId = nfc.bytesToHexString(nfcEvent.tag.id);
    console.log('Processing', tagId);

    try {
        await nfc.connect('android.nfc.tech.IsoDep', 500);
        console.log('connected to', tagId);
        
        let response = await nfc.transceive(DESFIRE_SELECT_PICC);
        ensureResponseIs('9000', response);
        
        response = await nfc.transceive(DESFIRE_SELECT_AID);
        ensureResponseIs('9100', response);
        // 91a0 means the requested application not found

        alert('Selected application AA AA AA');

        // more transcieve commands go here
        
    } catch (error) {
        alert(error);
    } finally {
        await nfc.close();
        console.log('closed');
    }

}

function ensureResponseIs(expectedResponse, buffer) {
    const responseString = util.arrayBufferToHexString(buffer);
    if (expectedResponse !== responseString) {
        const error = 'Expecting ' + expectedResponse + ' but received ' + responseString;
        throw error;
    }
}

function onDeviceReady() {
    nfc.addTagDiscoveredListener(handleDesfire);
}

document.addEventListener('deviceready', onDeviceReady, false);

nfc.connect

Connect to the tag and enable I/O operations to the tag from this TagTechnology object.

nfc.connect(tech);

nfc.connect(tech, timeout);

Description

Function connect enables I/O operations to the tag from this TagTechnology object. nfc.connect should be called after receiving a nfcEvent from the addTagDiscoveredListener or the readerMode callback. Only one TagTechnology object can be connected to a Tag at a time.

See Android's TagTechnology.connect() for more info.

Parameters

  • tech: The tag technology e.g. android.nfc.tech.IsoDep
  • timeout: The transceive(byte[]) timeout in milliseconds [optional]

Returns

  • Promise when the connection is successful, optionally with a maxTransceiveLength attribute in case the tag technology supports it

Quick Example

nfc.addTagDiscoveredListener(function(nfcEvent) {
    nfc.connect('android.nfc.tech.IsoDep', 500).then(
        () => console.log('connected to', nfc.bytesToHexString(nfcEvent.tag.id)),
        (error) => console.log('connection failed', error)
    );
})

Supported Platforms

  • Android

nfc.transceive

Send raw command to the tag and receive the response.

nfc.transceive(data);

Description

Function transceive sends raw commands to the tag and receives the response. nfc.connect must be called before calling transceive. Data passed to transceive can be a hex string representation of bytes or an ArrayBuffer. The response is returned as an ArrayBuffer in the promise.

See Android's documentation IsoDep.transceive(), NfcV.transceive(), MifareUltralight.transceive() for more info.

Parameters

  • data: a string of hex data or an ArrayBuffer

Returns

  • Promise with the response data as an ArrayBuffer

Quick Example

// Promise style
nfc.transceive('90 5A 00 00 03 AA AA AA 00').then(
    response => console.log(util.arrayBufferToHexString(response)),
    error => console.log('Error selecting DESFire application')
)

// async await
const response = await nfc.transceive('90 5A 00 00 03 AA AA AA 00');
console.log('response =',util.arrayBufferToHexString(response));

Supported Platforms

  • Android

nfc.close

Close TagTechnology connection.

nfc.close();

Description

Function close disabled I/O operations to the tag from this TagTechnology object, and releases resources.

See Android's TagTechnology.close() for more info.

Parameters

  • none

Returns

  • Promise when the connection is successfully closed

Quick Example

nfc.transceive().then(
    () => console.log('connection closed'),
    (error) => console.log('error closing connection', error);
)

Supported Platforms

  • Android

NDEF

The ndef object provides NDEF constants, functions for creating NdefRecords, and functions for converting data. See android.nfc.NdefRecord for documentation about constants

NdefMessage

Represents an NDEF (NFC Data Exchange Format) data message that contains one or more NdefRecords. This plugin uses an array of NdefRecords to represent an NdefMessage.

NdefRecord

Represents a logical (unchunked) NDEF (NFC Data Exchange Format) record.

Properties

  • tnf: 3-bit TNF (Type Name Format) - use one of the TNF_* constants
  • type: byte array, containing zero to 255 bytes, must not be null
  • id: byte array, containing zero to 255 bytes, must not be null
  • payload: byte array, containing zero to (2 ** 32 - 1) bytes, must not be null

The ndef object has a function for creating NdefRecords

var type = "text/pg",
    id = [],
    payload = nfc.stringToBytes("Hello World"),
    record = ndef.record(ndef.TNF_MIME_MEDIA, type, id, payload);

There are also helper functions for some types of records

Create a URI record

var record = ndef.uriRecord("http://chariotsolutions.com");

Create a plain text record

var record = ndef.textRecord("Plain text message");

Create a mime type record

var mimeType = "text/pg",
    payload = "Hello Phongap",
    record = ndef.mimeMediaRecord(mimeType, nfc.stringToBytes(payload));

Create an Empty record

var record = ndef.emptyRecord();

Create an Android Application Record (AAR)

var record = ndef.androidApplicationRecord('com.example');

See ndef.record, ndef.textRecord, ndef.mimeMediaRecord, and ndef.uriRecord.

The Ndef object has functions to convert some data types to and from byte arrays.

See the phonegap-nfc.js source for more documentation.

Events

Events are fired when NFC tags are read. Listeners are added by registering callback functions with the nfc object. For example nfc.addNdefListener(myNfcListener, win, fail);

NfcEvent

Properties

  • type: event type
  • tag: Ndef tag

Types

  • tag
  • ndef-mime
  • ndef
  • ndef-formatable

The tag contents are platform dependent.

id and techTypes may be included when scanning a tag on Android. serialNumber may be included on BlackBerry 7.

id and serialNumber are different names for the same value. id is typically displayed as a hex string nfc.bytesToHexString(tag.id).

Windows, Windows Phone 8, and BlackBerry 10 read the NDEF information from a tag, but do not have access to the tag id or other meta data like capacity, read-only status or tag technologies.

Assuming the following NDEF message is written to a tag, it will produce the following events when read.

var ndefMessage = [
    ndef.createMimeRecord('text/pg', 'Hello PhoneGap')
];

Sample Event on Android

{
    type: 'ndef',
    tag: {
        "isWritable": true,
        "id": [4, 96, 117, 74, -17, 34, -128],
        "techTypes": ["android.nfc.tech.IsoDep", "android.nfc.tech.NfcA", "android.nfc.tech.Ndef"],
        "type": "NFC Forum Type 4",
        "canMakeReadOnly": false,
        "maxSize": 2046,
        "ndefMessage": [{
            "id": [],
            "type": [116, 101, 120, 116, 47, 112, 103],
            "payload": [72, 101, 108, 108, 111, 32, 80, 104, 111, 110, 101, 71, 97, 112],
            "tnf": 2
        }]
    }
}

Sample Event on BlackBerry 7

{
    type: 'ndef',
    tag: {
        "tagType": "4",
        "isLocked": false,
        "isLockable": false,
        "freeSpaceSize": "2022",
        "serialNumberLength": "7",
        "serialNumber": [4, 96, 117, 74, -17, 34, -128],
        "name": "Desfire EV1 2K",
        "ndefMessage": [{
            "tnf": 2,
            "type": [116, 101, 120, 116, 47, 112, 103],
            "id": [],
            "payload": [72, 101, 108, 108, 111, 32, 80, 104, 111, 110, 101, 71, 97, 112]
        }]
    }
}

Sample Event on Windows, BlackBerry 10, or Windows Phone 8

{
    type: 'ndef',
    tag: {
        "ndefMessage": [{
            "tnf": 2,
            "type": [116, 101, 120, 116, 47, 112, 103],
            "id": [],
            "payload": [72, 101, 108, 108, 111, 32, 80, 104, 111, 110, 101, 71, 97, 112]
        }]
    }
}

Getting Details about Events

The raw contents of the scanned tags are written to the log before the event is fired. Use adb logcat on Android and Event Log (hold alt + lglg) on BlackBerry.

You can also log the tag contents in your event handlers. console.log(JSON.stringify(nfcEvent.tag)) Note that you want to stringify the tag not the event to avoid a circular reference.

Platform Differences

Non-NDEF Tags

Only Android and BlackBerry 7 can read data from non-NDEF NFC tags. Newer Windows Phones with NXP PN427 chipset can read non-NDEF tags, but can not get any tag meta data.

Mifare Classic Tags

BlackBerry 7, BlackBerry 10 and many newer Android phones will not read Mifare Classic tags. Mifare Ultralight tags will work since they are NFC Forum Type 2 tags. Newer Windows 8.1 phones (Lumia 640) can read Mifare Classic tags.

Tag Id and Meta Data

Windows Phone 8, BlackBerry 10, and Windows read the NDEF information from a tag, but do not have access to the tag id or other meta data like capacity, read-only status or tag technologies.

Multiple Listeners

Multiple listeners can be registered in JavaScript. e.g. addNdefListener, addTagDiscoveredListener, addMimeTypeListener.

On Android, only the most specific event will fire. If a Mime Media Tag is scanned, only the addMimeTypeListener callback is called and not the callback defined in addNdefListener. You can use the same event handler for multiple listeners.

For Windows, this plugin mimics the Android behavior. If an ndef event is fired, a tag event will not be fired. You should receive one event per tag.

On BlackBerry 7, all the events fire if a Mime Media Tag is scanned.

addTagDiscoveredListener

On Android, addTagDiscoveredListener scans non-NDEF tags and NDEF tags. The tag event does NOT contain an ndefMessage even if there are NDEF messages on the tag. Use addNdefListener or addMimeTypeListener to get the NDEF information.

Windows can scan non-NDEF (unformatted) tags using addTagDiscoveredListener. The tag event will not include any data.

On BlackBerry 7, addTagDiscoveredListener does NOT scan non-NDEF tags. Webworks returns the ndefMessage in the event.

Non-NDEF tag scanned with addTagDiscoveredListener on Android

{
    type: 'tag',
    tag: {
        "id": [-81, 105, -4, 64],
        "techTypes": ["android.nfc.tech.MifareClassic", "android.nfc.tech.NfcA", "android.nfc.tech.NdefFormatable"]
    }
}

NDEF tag scanned with addTagDiscoveredListener on Android

{
    type: 'tag',
    tag: {
        "id": [4, 96, 117, 74, -17, 34, -128],
        "techTypes": ["android.nfc.tech.IsoDep", "android.nfc.tech.NfcA", "android.nfc.tech.Ndef"]
    }
}

Non-NDEF tag scanned with addTagDiscoveredListener on Windows

{
    type: 'tag',
    tag: {
    }
}

BlackBerry 10 Invoke Target

This plugin uses the BlackBerry Invocation Framework to read NFC tags on BlackBerry 10. This means that you need to register an invoke target in the config.xml.

If your project supports multiple platforms, copy www/config.xml to merges/config.xml and add a rim:invoke-target tag. The invoke-target determines which tags your app will scan when it is running. If your application is not running, BlackBerry will launch it when a matching tag is scanned.

This sample configuration attempts to open any NDEF tag.

<rim:invoke-target id="your.unique.id.here">
    <type>APPLICATION</type>
    <filter>
        <action>bb.action.OPEN</action>
        <mime-type>application/vnd.rim.nfc.ndef</mime-type>
        <!-- any TNF Empty(0), Well Known(1), MIME Media(2), Absolute URI(3), External(4) -->
        <property var="uris" value="ndef://0,ndef://1,ndef://2,ndef://3,ndef://4" />
    </filter>
</rim:invoke-target>

You can configure you application to handle only certain tags.

For example to scan only MIME Media tags of type "text/pg" use

<rim:invoke-target id="your.unique.id.here">
    <type>APPLICATION</type>
    <filter>
        <action>bb.action.OPEN</action>
        <mime-type>application/vnd.rim.nfc.ndef</mime-type>
        <!-- TNF MIME Media(2) with type "text/pg" -->
        <property var="uris" value="ndef://2/text/pg" />
    </filter>
</rim:invoke-target>

Or to scan only Plain Text tags use

<rim:invoke-target id="your.unique.id.here">
    <type>APPLICATION</type>
    <filter>
        <action>bb.action.OPEN</action>
        <mime-type>application/vnd.rim.nfc.ndef</mime-type>
        <!-- TNF Well Known(1), RTD T -->
        <property var="uris" value="ndef://1/T" />
    </filter>
</rim:invoke-target>

See the BlackBerry documentation for more info.

Launching your Android Application when Scanning a Tag

On Android, intents can be used to launch your application when a NFC tag is read. This is optional and configured in AndroidManifest.xml.

<intent-filter>
  <action android:name="android.nfc.action.NDEF_DISCOVERED" />
  <data android:mimeType="text/pg" />
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

Note: data android:mimeType="text/pg" should match the data type you specified in JavaScript

We have found it necessary to add android:noHistory="true" to the activity element so that scanning a tag launches the application after the user has pressed the home button.

See the Android documentation for more information about filtering for NFC intents.

Testing

Tests require the Cordova Plugin Test Framework

Create a new project

git clone https://github.com/chariotsolutions/phonegap-nfc
cordova create nfc-test com.example.nfc.test NfcTest
cd nfc-test
cordova platform add android
cordova plugin add ../phonegap-nfc
cordova plugin add ../phonegap-nfc/tests
cordova plugin add https://github.com/apache/cordova-plugin-test-framework.git

Change the start page in config.xml

<content src="cdvtests/index.html" />

Run the app on your phone

cordova run

Sample Projects

HCE

For Host Card Emulation (HCE), try the Cordova HCE Plugin.

Book

Need more info? Check out my book Beginning NFC: Near Field Communication with Arduino, Android, and PhoneGap

Beginning NFC

License

The MIT License

Copyright (c) 2011-2020 Chariot Solutions

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

phonegap-nfc's People

Contributors

andreamaioli avatar asgeo1 avatar axelnennker avatar chuckytuh avatar dfroeh avatar don avatar gonzalo123 avatar gtanner avatar h0schi avatar homer-jay avatar jlkalberer avatar johnmclear avatar lezardrouge avatar lucasconstantino avatar luisegr avatar m00sey avatar mletynski avatar mzabaluev avatar pschlang avatar wux-shuto avatar zhorwedel avatar zonpantli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phonegap-nfc's Issues

android.nfc.tech.NdefFormatable should return tag id when reading

NdefFormatable tags do not return the tag id to javascript

D/NfcPlugin(14710): onNewIntent Intent { act=android.nfc.action.TECH_DISCOVERED flg=0x24000000 cmp=com.chariotsolutions.nfc.demo.reader/.ReaderDemo (has extras) }
D/NfcPlugin(14710): parseMessage Intent { act=android.nfc.action.TECH_DISCOVERED flg=0x24000000 cmp=com.chariotsolutions.nfc.demo.reader/.ReaderDemo (has extras) }
D/NfcPlugin(14710): action android.nfc.action.TECH_DISCOVERED
D/NfcPlugin(14710): android.nfc.tech.MifareUltralight
D/NfcPlugin(14710): android.nfc.tech.NfcA
D/NfcPlugin(14710): android.nfc.tech.NdefFormatable
V/NfcPlugin(14710): var e = document.createEvent('Events');
V/NfcPlugin(14710): e.initEvent('ndef-formatable');
V/NfcPlugin(14710): e.tag = {};
V/NfcPlugin(14710): document.dispatchEvent(e);
D/DroidGap(14710): Resuming the App
D/NfcPlugin(14710): onResume Intent { }

NFC Share callback event not firing after share.

 var mime = "application/mah-phonegap-app";
 var payload = nfc.stringToBytes(JSON.stringify(waitingForOrders.orders));
 var record = ndef.mimeMediaRecord(mime, payload);
 nfc.share(
    [record],
    function (){
      console.log("NFC Share [Success]");  // <-- This never fires....
      navigator.notification.vibrate(200);
    },
    function (reason){
      console.log("problem with nfc.share :{0}".template([reason]));
    }
 );

I am expecting a success callback event when the ndef record is shared with a recipient, but it's not fired.

(Tested with plugin version at HEAD)

WP8 Tag ID

If possible get the tag id and other information like tag type, tag technologies, tag capacity, is-read-only (or is-locked), can make tag read only on Windows Phone 8

NullReferenceException thrown by calling "proximityDevice.PublishBinaryMessage(type, data.AsBuffer())" method

I just called the "share" method and got an "NullReferenceException" thrown.
My System Specification is:

  • WindowsPhone 8
  • Latest Plug-In Version

The error message:
$exception {System.NullReferenceException: Object reference not set to an instance of an object.
at Cordova.Extension.Commands.NfcPlugin.publish(String type, String args)
at Cordova.Extension.Commands.NfcPlugin.shareTag(String args)} System.Exception {System.NullReferenceException}

add channels for events

Add cordova channels for nfc events so the plugin can be called when the javascript listeners are added

Then document.addEventListener("ndef", onNFC, false); can be used instead of nfc.addNdefListener(onNFC, win, fail);

Add function to make tags readonly

Ndef.makeReadOnly() and possibly NdefFormatable.formatReadOnly(message)

navigator.nfc.makeReadOnly()

// consider options object for writeTag
navigator.nfc.writeTag(ndefMessage, win, lose, { read-only: true })

Launching the application when a NFC tag is scanned

Hello guys, I just wanted to clarify something really. Now, I'm not overly knowledgeable about NFC but I know that you can use an NFC tag to open your application, right? But what I'm wondering is, could you also make that tag trigger an action within the app? So upon tapping the tag against the phone / tablet, it would open the app and trigger an event as well, such as opening a contact for example. And the contact that it would open would depend on the information in that specific tag? Is this possible?

I would really appreciate your help!

Thanks.

ICS - NFC tag opens app but does not trigger onNFC event

First of all this is a great plugin!

One issue that I have (Samsung Galaxy Nexus) is that I wrote app that reads NFC tag. It works just fine when I first start app and put the tag to the phone.

Since I would like to make user experience better, I added Intent to manifest file which actually opens my application when I put NFC tag to my phone. But it seems that it does not trigger onNFC event.

Am I doing something wrong or is anyone experiencing the same issue?

API CHANGE - use success callback for NFC messages instead of JS events

cordova-wp8 will be removing BaseCommand.InvokeCustomScript, then means the code won't be able to fire JS events when a NFC message is received.

I'm considering changing the API so the NFC messages are returned in the success callback and not via a JS event.

The current API looks like this

nfc.addNdefListener(callback, [onSuccess], [onFailure]);

The callback is called using an event listener and receives a nfcEvent

onSuccess is only called when the listener is successfully added, which isn't very useful. onFailure is called when the the code fails to add the listener.

The proposed change would make the API look like

nfc.addNdefListener(onSuccess, [onFailure]);

The onSuccess callback would be kept and onSuccess would be called with nfcTag every time a tag was scanned. A breaking change is the callback would receive a tag not an event.

Maybe the new versions of these should be renamed, while the old versions are deprecated?

This change would apply to

  • nfc.addNdefListener
  • nfc.addNdefFormatableListener
  • nfc.addMimeTypeListener
  • nfc.addTagDiscoveredListener

Truly asynchronous, stateful I/O API

The implementation of writeTag has a few problems:

  • it calls blocking NFC I/O methods in the browser thread;
  • it does not call close() on the tag tech object to release resources,
    as mandated by the API documentation;
  • it does not lend itself well to continuous operation with multiple
    writes (and reads) in a sequence.

To solve these issues and let the client to be in control, I think a new stateful API is necessary.
My attempt at it follows the Android tag interfaces:
https://github.com/mzabaluev/phonegap-nfc/commits/async-tag-ops

The branch is commingled with other changes I've made, such as an update to Cordova 2.2. If there's interest, I can rebase the changes or just submit them sequentially (#28 would be a good start). There is no implementation for Blackberry.

Add better documentation for nfcEvent.type = 'tag'

Add better documentation for nfcEvent.type = 'tag' and reading the NFC tag ID (not NDEF field ID)

If you register for the ACTION_TAG_DISCOVERED you will get a TAG event instead of a NDEF event in PhoneGap NFC.
(See http://developer.android.com/reference/android/nfc/NfcAdapter.html#ACTION_TAG_DISCOVERED)

The nfcEvent should look something like

{
    type: "tag",
    tag: {
        "id": [ - 81, 105, -4, 64],
        "techTypes": ["android.nfc.tech.MifareClassic", "android.nfc.tech.NfcA", "android.nfc.tech.NdefFormatable"]
    }
}

Example code to read the NFC tag id

var ready = function() {

    function nfcListener(nfcEvent) {
        navigator.notification.alert(nfc.bytesToHexString(nfcEvent.tag.id), function() {}, "NFC Tag ID");
    }

    function win() {
        console.log("Added Tag Discovered Listener");
    }

    function fail(reason) {
        navigator.notification.alert(reason, function() {}, "There was a problem");
    }

    nfc.addTagDiscoveredListener(nfcListener, win, fail);    
};

document.addEventListener('deviceready', ready, false);

After scanning a tag, pushing the home button and starting the app again: the app is created again and not resumed

Hello,
i have an issue on my nexus 7 with android 4.2.2 using the last versions of phonegap (2.5.) and phonegap-nfc (0.4.1). when using the homebutton, the app is recreated again and not resumed. but the other state is still there and available as soon as i exit from the application (as if it is started twice). i've broken this down using only the reader demo. this problem only occurres if a tag is scanned.

I can reproduce it with phonegap-nrc-reader-demo in that way:

  • starting the app
  • scanning a tag (without this task the problem does not occur)
  • pushing homebutton to leave the app in the background
  • starting the app again

you can the on the logs that the app is created (see logs below). if you exit the application now, the application is still available with the old data).


logs for resuming the app WITHOUT scanning a tag:

03-19 11:19:00.714: D/DroidGap(26662): Resuming the App
03-19 11:19:00.714: D/NfcPlugin(26662): onResume Intent { }


logs for resuming the app and a tag is scanned before:

03-19 11:20:45.064: D/DroidGap(26662): DroidGap.onCreate()
03-19 11:20:45.074: D/JsMessageQueue(26662): Set native->JS mode to 2
03-19 11:20:45.074: D/DroidGap(26662): DroidGap.init()
03-19 11:20:45.084: D/CordovaWebView(26662): >>> loadUrl(file:///android_asset/www/index.html)
03-19 11:20:45.084: D/PluginManager(26662): init()
03-19 11:20:45.084: D/CordovaWebView(26662): >>> loadUrlNow()
03-19 11:20:45.084: D/DroidGap(26662): Resuming the App
03-19 11:20:45.094: D/DroidGap(26662): onMessage(onPageStarted,file:///android_asset/www/index.html)
03-19 11:20:45.104: D/SoftKeyboardDetect(26662): Ignore this event
03-19 11:20:45.134: D/CordovaLog(26662): Viewport argument value "320;" for key "width" was truncated to its numeric prefix.
03-19 11:20:45.134: V/Web Console(26662): Viewport argument value "320;" for key "width" was truncated to its numeric prefix. at file:///android_asset/www/index.html:4
03-19 11:20:45.194: D/Cordova(26662): onPageFinished(file:///android_asset/www/index.html)
03-19 11:20:45.194: D/Cordova(26662): Trying to fire onNativeReady
03-19 11:20:45.204: D/DroidGap(26662): onMessage(onNativeReady,null)
03-19 11:20:45.204: D/DroidGap(26662): onMessage(onPageFinished,file:///android_asset/www/index.html)
03-19 11:20:45.214: D/SoftKeyboardDetect(26662): Ignore this event
03-19 11:20:45.264: D/NfcPlugin(26662): execute init
03-19 11:20:45.264: D/NfcPlugin(26662): Enabling plugin Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.chariotsolutions.nfc.demo.reader/.ReaderDemo bnds=[272,595][400,723] }
03-19 11:20:45.274: D/CordovaLog(26662): Initialized the NfcPlugin
03-19 11:20:45.274: I/Web Console(26662): Initialized the NfcPlugin at file:///android_asset/www/phonegap-nfc-0.4.1.js:7
03-19 11:20:45.284: D/NfcPlugin(26662): parseMessage Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.chariotsolutions.nfc.demo.reader/.ReaderDemo bnds=[272,595][400,723] }
03-19 11:20:45.284: D/NfcPlugin(26662): action android.intent.action.MAIN
03-19 11:20:45.294: D/CordovaNetworkManager(26662): Connection Type: wifi
03-19 11:20:45.294: D/DroidGap(26662): onMessage(networkconnection,wifi)
03-19 11:20:45.294: D/CordovaNetworkManager(26662): Connection Type: wifi
03-19 11:20:45.294: D/DroidGap(26662): onMessage(spinner,stop)
03-19 11:20:45.304: D/NfcPlugin(26662): execute registerNdef
03-19 11:20:45.304: D/NfcPlugin(26662): execute registerMimeType
03-19 11:20:45.314: D/CordovaLog(26662): Listening for NDEF tags.
03-19 11:20:45.314: I/Web Console(26662): Listening for NDEF tags. at file:///android_asset/www/main.js:116
03-19 11:20:45.314: D/CordovaLog(26662): Listening for NDEF mime tags with type text/pg.
03-19 11:20:45.314: I/Web Console(26662): Listening for NDEF mime tags with type text/pg. at file:///android_asset/www/main.js:128
03-19 11:20:47.214: D/DroidGap(26662): onMessage(spinner,stop)

Make RTD_* constants Strings not Arrays

Comparing types to RTD_* constants is clunky since arrays can't be compared.

This change will make the JavaScript more convenient

Converting the constants to Strings is OK, since most constructors now take Strings or [] and convert appropriately.

The native implementations probably don't need to change.

I haven't see a case where Type is not a String. Need to check the specs, but it would be nice if record.type and record.id could be strings and only payload would be a byte array.

/cc @tigoe

NFC Plugin not playing nice w/ Webintent Plugin

In the past I've written some apps using phonegap-nfc that have worked great out of the box (simply responding to scans), but I'm trying something a bit more complex now and trying to wrap my head around it.

What I'm trying to do have an app handle a share intent (ie from the Gallery) using the WebIntent plugin (I had to modify the plugin a bit, but it works) to load up my PhoneGap app and the image and then I'd like to be able to scan some tags.

With the webintent plugin alone and the following intent-filter, everything works as expected:

        <intent-filter>
          <action android:name="android.intent.action.SEND" />
          <data android:mimeType="image/*" />

          <category android:name="android.intent.category.DEFAULT" />
        </intent-filter> 

window.webintent.getExtra() is able to pull what I need.

However, when the nfcplugin is activated, I don't seem to see anything. It seems like NfcPlugin is eating the intent?

10-16 14:39:55.728: D/NfcPlugin(28694): Enabling plugin Intent { act=android.intent.action.SEND typ=image/* flg=0x80001 cmp=com.lensley.client.roaming/.MainActivity (has clip) (has extras) }
10-16 14:39:55.728: D/NfcPlugin(28694): parseMessage Intent { act=android.intent.action.SEND typ=image/* flg=0x80001 cmp=com.lensley.client.roaming/.MainActivity (has clip) (has extras) }
10-16 14:39:55.738: D/NfcPlugin(28694): action android.intent.action.SEND

(BTW, a secondary issue was that when I enter w/ a SHARE intent, and then scanned w/ the NFC, it seems to start a second copy of the MainActivity - I switched the activity to android:launchMode="singleTask" as a workaround)

It looks like there's some programmatic stuff going on w/ NfcPlugin and intents that's beyond my ken (I'm an Android programming noob). Is there a quick fix or has this issue been encountered before?

Undefined

Hi Don,
Managed to get the phonegap nfc plugin working. Installed the reader demo, the app runs ok, no issues on the log, but when I read tags, I get all "undefined" for the tag type, max size etc...is tehre a step I skipped? I would like to read the tags unique id for starters. The app vibrates when it reads the tags and just shows "undefined" on each of the items. Any help? Thanks.

Start/stop, reading sessions

As I see, the plugin is working all the time (draining the battery), isn't it?
Is (will be) there any way to use the plugin in sessions, e.g manually start/stop the reading?

Empty object return after scanning

Screenshot_2013-01-24-01-21-20

after scaning nfc card i see this picture. Application "NFC Taginfo" show me info about this card. (in last string "o:" i've just tried to output object "tag", without any edits result of application work the same)

NFCInfo

also strange that "NFC Taginfo" ask me hold card for 2-3sec for reading, using your plugin event fires exact after card connect to device, without delay.

Fix documentation for nfc.share and nfc.write

Update documentation. It is not clear that NdefMessage is an array of NdefRecords and the first argument to nfc.write and nfc.share is an array.

Some sample code in the documentation will help.

NFC-feature detection (enhancement request)

I'm creating an app which has an optional NFC feature.
I want to be able to detect if NFC is available or not so that I can enable or disable this feature accordingly.
Thanks!

Blackberry 10 : Class NfcPlugin cannot be found

Hi. Using cordova 2.2.0, on blackberry dev alpha. Followed the steps required :

  1. Added your classes to cordova.2.2.0.jar, and it is showing correctly with jar tf command.
  2. Added to plugins.xml (there is no res/xml/plugins.xml) , there is plugins.xml in the www directory itself.
  3. Added phonegap-nfc.js after webworks and cordova.js

Please help. It works properly in android, but am not getting it to work on BB 10. Thanks in advance.

Plugin crashes app if device does not have NFC

Handle devices without NFC more gracefully

private void startNfc() {
    createPendingIntent(); // onResume can call startNfc before execute

    this.ctx.runOnUiThread(new Runnable() {
        public void run() {
            NfcAdapter.getDefaultAdapter(ctx.getContext()).enableForegroundDispatch(
   ...

D/NfcPlugin( 900): execute init
D/NfcPlugin( 900): Enabling plugin Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.chariotsolutions.nfc.demo.reader/.ReaderDemo }
V/NFC ( 900): this device does not have NFC support
D/AndroidRuntime( 900): Shutting down VM
W/dalvikvm( 900): threadid=1: thread exiting with uncaught exception (group=0x40015578)
E/AndroidRuntime( 900): FATAL EXCEPTION: main
E/AndroidRuntime( 900): java.lang.NullPointerException
E/AndroidRuntime( 900): at com.chariotsolutions.nfc.plugin.NfcPlugin$1.run(NfcPlugin.java:160)
E/AndroidRuntime( 900): at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime( 900): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 900): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime( 900): at android.app.ActivityThread.main(ActivityThread.java:3687)
E/AndroidRuntime( 900): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 900): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 900): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
E/AndroidRuntime( 900): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
E/AndroidRuntime( 900): at dalvik.system.NativeStart.main(Native Method)
D/NfcPlugin( 900): parseMessage Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.chariotsolutions.nfc.demo.reader/.ReaderDemo }
D/NfcPlugin( 900): action android.intent.action.MAIN
E/ ( 129): Dumpstate > /data/log/dumpstate_app_error
W/ActivityManager( 129): Force finishing activity com.chariotsolutions.nfc.demo.reader/.ReaderDemo
I/dumpstate( 919): begin

Foreground dispatch should only be enabled by onResume

In the current code, modifying intent filters or tech lists from JavaScript results in foreground dispatch being enabled on the NfcAdapter. These modifications may occur before onResume is called, resulting in an IllegalStateException.

Commit mzabaluev@d10fe6362d6bdfeb5e43e8b3dc154f41f56e7ee7 removes the state error.
Additionally, commit mzabaluev@98e6070d030bd9948a8e61a4b1d39c40c1f4fa8a resolves threading issues by synchronizing or context-passing the NFC dispatch and push data shared between the UI thread and the browser thread.
For your reference, the branch (based on my other changes) is posted here:
https://github.com/mzabaluev/phonegap-nfc/commits/lifecycle-fixes

Tag capacity check skipped when formatting

If the message exceeds the tag capacity on a formatted tag, the user receives a message "Tag capacity is 46 bytes, Message is 198 bytes"

If the tag is not formatted, the same write call formats the tag and gives an error "null"

Can we check the capacity of a tag before formatting?

BB10: error thrown on nfc.write()

Using cordova 2.3, along with plugin 0.4.2 on BB10 simulator and DevAlpha .

Calling nfc.write([ndef]) inside an event handler throws the following:

Error: Status=7 Message=Action not found: writeTag cordova-2.3.0.js:1036

NFC + Barcodescanner

Hi,

I'm using the NFC as well as the Barcodescanner (https://github.com/phonegap/phonegap-plugins/tree/master/Android/BarcodeScanner) plugins in the same project for Android.
I would like to be able to continue detecting NFC tags even when the Barcodescanner activity has started.

At the moment if the barcodescanner activity is active and an NFC tag is detected, the default Android action (opening the tag's url in a browser) is performed.

Is there anyway to tell the NFC plugin to continue listening for NFC tags even if the main activity is in the background ?

I'm new to Android, and have tried to comment out the onPause and onResume functions in the NFC plugin, but this doesn't change anything.

Any help is highly appreciated.

uriRecord doesn't quite work as expected.

Was having a lot of difficulty using uriRecord with web urls on my Nexus 7 and Galaxy Nexus. When reading the payload back off on a separate device, I would just get "U" in the default ndef handler.

I have a patch I can submit up as a pull request next week (didn't clone and have hacked around the file a lot), but basically I used Android's UriRecord.java as a reference and discovered there was a missing 0x00 prefixing the nfc.stringToBytes( text ) payload definition in uriRecord. I also used the TNF_WELL_KNOWN instead of TNF_ABSOLUTE_URI.

Tags tapped now open in the default browser.

Thanks much for your work on this - really helped us get a quick app off the ground.

JSON Error - when attempting to share a tag

Not an Issue report, just a helpful pointer when the JSON Error pops up when writing or sharing a tag, it's due to the follow user error writing the method signature for nfc.share or nfc.write

 var record = ndef.textRecord("or any other ndef record creation method.");
 nfc.share(record,  onSuccessFunc, onFailFunc); // this will throw a JSON Error

The record must be in an array, ie.

 var record = ndef.textRecord("or any other ndef record creation method.");
 nfc.share( [ record ] ,  onSuccessFunc, onFailFunc); 
 //         ⬆       ⬆ 

If this was an issue report (it's a bit late since this will already be used in implementation details downstream.) it'd be a suggestion to remove the array syntax (unless multiple tags are sharable/writable at once? @don possible?)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.