NFC

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

Use to

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

Classes


NFC

addNdefListener

Registers an event listener for any NDEF tag.

addNdefListener(options: callback): Promise <any>

PARAMETERS
options: The callback that is called when an NDEF tag is read.

RETURN
returns: Promise <any>

Description:

  • Function addNdefListener registers the callback for ndef events.
  • On registered mimeTypeListeners takes precedence over this more generic NDEF listener.
removeNdefListener

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

removeNdefListener(option: callback): Promise <any>

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


PARAMETERS
option: The previously registered callback

RETURN
returns: Promise <any>
addTagDiscoveredListener

Registers an event listener for tags matching any tag type.

addTagDiscoveredListener(option: callback): Promise <any>

PARAMETERS
option: The callback that is called when a tag is detected

RETURN
returns: Promise <any>

Description

  • Function addTagDiscoveredListener registers the callback for tag events.
  • This event occurs when any tag is detected by the phone.
addMimeTypeListener

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

addMimeTypeListener(mimeType: string, call: callback): Promise <any>

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


PARAMETERS
mimeType: string. The MIME type to filter for messages
call: The callback that is called when an NDEF tag matching the MIME type is read

RETURN
returns: Promise <any>

Description

  • Function 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*);
        nfc.addMimeTypeListener("text/demo", *onNfc*);
removeMimeTypeListener

Removes the previously registered event listener added via addMimeTypeListener.

removeMimeTypeListener(mimeType: string, option: callback): Promise <any>

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.

RETURN
returns: Promise <any>
addNdefFormatableListener

Registers an event listener for formatable NDEF tags.

addNdefFormatableListener(option: callback): Promise <any>

PARAMETERS
option: The callback that is called when NDEF formatable tag is read.

RETURN
returns: Promise <any>

Description

  • Function 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.
write

Writes an NDEF Message to a NFC tag.

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

write(message: string): Promise <any>

PARAMETERS
message: string

RETURN
returns: Promise <any>

Description

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

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

makeReadOnly(): Promise <any>

RETURN
returns: Promise <any>

Description

  • Function makeReadOnly make a NFC tag read only. Warning this is permanent and can not be undone.
  • This method must be called from within an NDEF Event Handler.
share

Shares an NDEF Message via peer-to-peer.

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

share(message: string): Promise <any>

PARAMETERS
message: string

RETURN
returns: Promise <any>

Description

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

Stop sharing NDEF data via peer-to-peer.

unshare(): Promise <any>

PARAMETERS

RETURN
returns: Promise <any>

Description

  • Function unshare stops sharing data via peer-to-peer.
erase

Erase a NDEF tag

erase(): Promise <any>

RETURN
returns: Promise <any>

Description

  • Function unshare 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.
handover

Send a file to another device via NFC handover.

handover(uri: string): Promise <any>

PARAMETERS
uri: string

RETURN
returns: Promise <any>

Description

  • Function 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 code is responsible for building the handover NFC Message.
stopHandover

Stop sharing NDEF data via NFC handover.

stopHandover(): Promise <any>

RETURN
returns: Promise <any>

Description

  • Function stopHandover stops sharing data via peer-to-peer.
enabled

Check if NFC is available and enabled on this device.

enabled(): Promise <any>

RETURN
returns: Promise <any>

Description

  • Function enabled explicitly checks to see if the phone has NFC and if NFC is enabled.
  • The reason will be NO_NFC if the device doesn't support NFC and NFC_DISABLED if the user has disabled NFC.
showSettings

Show the NFC settings on the device.

showSettings(): Promise <any>

RETURN
returns: Promise <any>

Description

  • Function showSettings opens the NFC settings for the operating system.

Reader Mode Functions

readerMode

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

readerMode(flags: flagReader, option: readCallback): Promise <any>

PARAMETERS
flags: flagReader
option: readCallback

RETURN
returns: Promise <any>

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.

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.

disableReaderMode

Disable NFC reader mode.

disableNfcReaderMode(): Promise <any>

RETURN
returns: Promise <any>

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.

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('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;
    }
}
connect

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

connect(tech: string, timeout?: int): Promise <any>

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

RETURN
returns: Promise <any>
transceive

Send raw command to the tag and receive the response.

transceive(data: string): Promise <any>

PARAMETERS
data: string

RETURN
returns: Promise <any>
close

Close TagTechnology connection.

close(): Promise <any>

RETURN
returns: Promise <any>

NDEF


The ndef object provides NDEF constants, functions for creating NdefRecords, and functions for converting data.

NdefMessage

Represents an NDEF (NFC Data Exchange Format) data message that contains one or more NdefRecords. This API 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 Application Record (AAR)

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

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

Events


Events are fired when NFC tags are read. Listeners are added by registering callback functions with the nfc object. For example 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

Sample
{
    type: 'ndef',
    tag: {
        "isWritable": true,
        "id": [4, 96, 117, 74, -17, 34, -128],
        "techTypes": ["nfc.tech.IsoDep", "nfc.tech.NfcA", "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
        }]
    }
}

Getting Details about Events

The raw contents of the scanned tags are written to the log before the event is fired. Use adb logcat.

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.

Interfaces

readCallback
interface readCallback {
    "isWritable": boolean,
    "id": array,
    "techTypes": array,
    "type": string,
    "canMakeReadOnly": boolean,
    "maxSize": int,
    "ndefMessage": [{
        "id": array,
        "type": array,
        "payload": array,
        "tnf": int
    }]
}

Enumeration

flagReader

enum Direction {
    FLAG_READER_NFC_A: 0x1
    FLAG_READER_NFC_B: 0x2
    FLAG_READER_NFC_F: 0x4
    FLAG_READER_NFC_V: 0x8
    FLAG_READER_NFC_BARCODE: 0x10
    FLAG_READER_SKIP_NDEF_CHECK: 0x80
    FLAG_READER_NO_PLATFORM_SOUNDS: 0x100
}