Skip to content

⚡️ Capacitor plugin for reading and writing NFC tags.

License

Notifications You must be signed in to change notification settings

rbaumi/capacitor-nfc

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation


NFC

@capawesome-team/capacitor-nfc

Capacitor plugin for reading and writing NFC tags.

Maintainers

Maintainer GitHub Social
Robin Genz robingenz @robin_genz

Sponsors

This is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd like to join them, please read more here.

Base Sponsor


Sponsorware

This project is available as Sponsorware.

Sponsorware is a release strategy for open-source software that enables developers to be compensated for their open-source work with fewer downsides than traditional open-source funding models. (Source)

This means...

  • The source code will be published as soon as our GitHub Sponsors goal is reached.
  • Any GitHub sponsor with a sponsorware tier gets immediate access to our sponsors-only repository and can start using the project right away.

Terms

This project is licensed under the terms of the MIT license.
However, we kindly ask you to respect our fair use policy:

  • Please don't distribute the source code of the sponsors-only repository. You may freely use it for public, private or commercial projects, privately fork or mirror it, but please don't make the source code public, as it would counteract the sponsorware strategy.
  • If you cancel your subscription, you're automatically removed as a collaborator and will miss out on all future updates. However, you may use the latest version that's available to you as long as you like.

Demo

A working example can be found here: capawesome-team/capacitor-nfc-demo

Android iOS

Roadmap

This plugin is still under development. This is our approximate roadmap:

Q4 2022
- Android Reader Mode

⚠️ Disclaimer: This roadmap does not represent a commitment, guarantee, obligation or promise to deliver any product or feature, or to deliver any product and feature by any particular date, and is intended to outline the general development plans. You should not rely on this roadmap to make any sponsorship decision.

FAQ

  1. Which platforms are supported?
    This plugin supports Android 5+, iOS 13+ and Web (see Browser compatibility). But not all platforms and devices support all technologies. You can read more about this in the plugin documentation.
  2. Which Capacitor versions are supported?
    There is a version for Capacitor 3 and Capacitor 4. However, new updates are only ever provided for the latest Capacitor major version (currently Capacitor 4).
  3. What do I do when I have a feature request?
    This always depends on your device and the specific tag. The easiest way to find out is to download our demo app and give it a try.
  4. What do I do when I have a feature request?
    Please submit your feature request here. We will then review it and possibly put it on our roadmap.
  5. What do I do when I have found a bug?
    Bug reports have top priority. Please submit your bug report here. We will take a look at it as soon as possible.

Installation

As long as the project is available as Sponsorware, the project will be distributed via GitHub packages.

  1. Log in to GitHub package registry (GitHub Docs):

    $ npm login --scope=@capawesome-team --registry=https://npm.pkg.github.com
    
    > Username: USERNAME
    > Password: TOKEN
    > Email: PUBLIC-EMAIL-ADDRESS
    
  2. In the same directory as your package.json file, create or edit an .npmrc file to include the following line (GitHub Docs):

    @capawesome-team:registry=https://npm.pkg.github.com
    
  3. Install the package with Capacitor 3:

    npm install @capawesome-team/[email protected]
    npx cap sync

    Install the package with Capacitor 4:

    npm install @capawesome-team/capacitor-nfc
    npx cap sync

    🆘 If you have any problems please contact us by mail or create a GitHub discussion in this repository.
    ⚠️ Attention: Be careful not to disclose your npm auth token! If you have any questions (CI configuration etc.) please let us know.

Android

This API requires the following permissions be added to your AndroidManifest.xml before the application tag:

<!-- To get access to the NFC hardware. -->
<uses-permission android:name="android.permission.NFC" />
<!-- The minimum SDK version that your application can support. -->
<uses-sdk android:minSdkVersion="10"/>
<!-- (Optional) This will ensure that your app appears in Google Play only for devices with NFC hardware. -->
<uses-feature android:name="android.hardware.nfc" android:required="true" />

If you want to launch your app through an NFC tag, please take a look at the Android documentation. There you will find which changes you have to apply to your AndroidManifest.xml (example).

iOS

Ensure Near Field Communication Tag Reading capabilities have been enabled in your application in Xcode. See Add a capability to a target for more information.

Finally, add the NFCReaderUsageDescription key to the ios/App/App/Info.plist file, which tells the user why the app needs to use NFC:

+ <key>NFCReaderUsageDescription</key>
+ <string>The app enables the reading and writing of various NFC tags.</string>

If you want to launch your app through an NFC tag, please take a look at the Core NFC documentation. The NFC tag requires a URI record (see createNdefUriRecord(...)) that must contain either a universal link (see Deep Linking with Universal and App Links) or a supported URL scheme.

Configuration

No configuration required for this plugin.

Usage

import { Nfc, NfcUtils, NfcTagTechType } from '@capawesome-team/capacitor-nfc';

const createNdefTextRecord = async () => {
  const utils = new NfcUtils();
  const { record } = utils.createNdefTextRecord({ text: 'Capacitor NFC Plugin' });
  return record;
};

const write = async () => {
  const record = createNdefTextRecord();

  Nfc.addListener('nfcTagScanned', async (event) => {
    await Nfc.write({ message: { records: [record] } });
  });

  await Nfc.startScanSession();
};

const read = async () => {
  return new Promise((resolve) => {
    Nfc.addListener('nfcTagScanned', async (event) => {
      resolve(event.nfcTag);
    });

    Nfc.startScanSession();
  });
};

const makeReadOnly = async () => {
  Nfc.addListener('nfcTagScanned', async (event) => {
    await Nfc.makeReadOnly();
  });

  await Nfc.startScanSession();
};

const erase = async () => {
  Nfc.addListener('nfcTagScanned', async (event) => {
    await Nfc.erase();
  });

  await Nfc.startScanSession();
};

const format = async () => {
  Nfc.addListener('nfcTagScanned', async (event) => {
    await Nfc.format();
  });

  await Nfc.startScanSession();
};

const isSupported = async () => {
  const { isSupported } = await Nfc.isSupported();
  return isSupported;
};

const isEnabled = async () => {
  const { isEnabled } = await Nfc.isEnabled();
  return isEnabled;
};

const openSettings = async () => {
  await Nfc.openSettings();
};

const checkPermissions = async () => {
  const { nfc } = await Nfc.checkPermissions();
  return nfc;
};

const requestPermissions = async () => {
  const { nfc } = await Nfc.requestPermissions();
  return nfc;
};

const removeAllListeners = async () => {
  await Nfc.removeAllListeners();
};

const readSignature = async () => {
  Nfc.addListener('nfcTagScanned', async (event) => {
    const { response } = await Nfc.transceive({ techType: NfcTagTechType.NfcA, data: [60, 0] });
    return response;
  });

  await Nfc.startScanSession();
};

API

startScanSession(...)

startScanSession(options?: StartScanSessionOptions | undefined) => Promise<void>

Start a scan session. Only one session can be active at a time.

On iOS, this will trigger the NFC Reader Session alert.

Param Type
options StartScanSessionOptions

Since: 0.0.1


stopScanSession(...)

stopScanSession(options?: StopScanSessionOptions | undefined) => Promise<void>

Stop the active scan session.

Param Type
options StopScanSessionOptions

Since: 0.0.1


write(...)

write(options: WriteOptions) => Promise<void>

Write to a NFC tag.

This method must be called from within a nfcTagScanned handler.

Param Type
options WriteOptions

Since: 0.0.1


makeReadOnly()

makeReadOnly() => Promise<void>

Make a NFC tag readonly.

This method must be called from within a nfcTagScanned handler.

Attention: This is permanent and can not be undone.

Since: 0.0.1


erase()

erase() => Promise<void>

Erase the NFC tag by writing an empty NDEF message.

This method must be called from within a nfcTagScanned handler.

Since: 0.3.0


format()

format() => Promise<void>

Format the NFC tag as NDEF and write an empty NDEF message.

This method must be called from within a nfcTagScanned handler.

Only available on Android.

Since: 0.3.0


transceive(...)

transceive(options: TransceiveOptions) => Promise<TransceiveResult>

Send raw command to the tag and receive the response.

This method must be called from within a nfcTagScanned handler.

⚠️ Experimental: This method could not be tested extensively yet. Please let us know if you discover any issues!

⚠️ Attention: A bad command can damage the tag forever. Please read the Android and iOS documentation linked below first.

More information on how to use this method on Android: https://developer.android.com/reference/android/nfc/tech/package-summary More information on how to use this method on iOS with...

Only available on Android and iOS.

Param Type
options TransceiveOptions

Returns: Promise<TransceiveResult>

Since: 0.3.0


isSupported()

isSupported() => Promise<IsSupportedResult>

Returns whether or not NFC is supported.

Returns: Promise<IsSupportedResult>

Since: 0.0.1


isEnabled()

isEnabled() => Promise<IsEnabledResult>

Returns whether or not NFC is enabled.

Only available on Android.

Returns: Promise<IsEnabledResult>

Since: 0.0.1


openSettings()

openSettings() => Promise<void>

Opens the NFC device settings so that the user can enable or disable NFC.

Only available on Android.

Since: 0.0.1


checkPermissions()

checkPermissions() => Promise<PermissionResult>

Check permission for reading and writing NFC tags.

This method is only needed on Web. On Android and iOS, granted is always returned.

Returns: Promise<PermissionResult>

Since: 0.0.1


requestPermissions()

requestPermissions() => Promise<PermissionResult>

Request permission for reading and writing NFC tags.

This method is only needed on Web. On Android and iOS, granted is always returned.

Returns: Promise<PermissionResult>

Since: 0.0.1


addListener('nfcTagScanned', ...)

addListener(eventName: 'nfcTagScanned', listenerFunc: (event: NfcTagScannedEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Called when a new NFC tag is scanned.

Param Type
eventName 'nfcTagScanned'
listenerFunc (event: NfcTagScannedEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 0.0.1


addListener('scanSessionCanceled', ...)

addListener(eventName: 'scanSessionCanceled', listenerFunc: () => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Called when the scan session was canceled.

Only available on iOS.

Param Type
eventName 'scanSessionCanceled'
listenerFunc () => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 0.0.1


addListener('scanSessionError', ...)

addListener(eventName: 'scanSessionError', listenerFunc: (event: ScanSessionErrorEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Called when an error occurs during the scan session.

Param Type
eventName 'scanSessionError'
listenerFunc (event: ScanSessionErrorEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 0.0.1


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for this plugin.

Since: 0.0.1


Interfaces

StartScanSessionOptions

Prop Type Description Default Since
alertMessage string A custom message, which is displayed in the NFC Reader Session alert. Only available on iOS. 0.0.1
techTypes NfcTagTechType[] The NFC tag technologies to filter on in this session. Only available on Android. 0.0.1
mimeTypes string[] Mime types to filter on in this session. Only available on Android. 0.0.1
pollingOptions PollingOption[] Type of tags to detect during a polling sequence. Only available on iOS. [PollingOption.iso14443, PollingOption.iso15693] 0.2.0

StopScanSessionOptions

Prop Type Description Since
errorMessage string A custom error message, which is displayed in the NFC Reader Session alert. Only available on iOS. 0.0.1

WriteOptions

Prop Type Description Since
message NdefMessage The NDEF message to write. 0.0.1

NdefMessage

Prop Type Description Since
records NdefRecord[] The records of the NDEF message. 0.0.1

NdefRecord

Prop Type Description Since
id number[] The record identifier as byte array. 0.0.1
payload number[] The payload field data as byte array. 0.0.1
tnf TypeNameFormat The record type name format which indicates the structure of the value of the type field. 0.0.1
type number[] The type of the record payload. This should be used in conjunction with the tnf field to determine the payload format. 0.0.1

TransceiveResult

Prop Type Description Since
response number[] Bytes received in response. 0.3.0

TransceiveOptions

Prop Type Description Since
techType NfcTagTechType The NFC tag technology to connect with. On iOS, only NfcTagTechType.NfcF and NfcTagTechType.NfcV are supported. 0.3.0
data number[] Bytes to send. 0.3.0
iso15693RequestFlags Iso15693RequestFlag[] The request flags for the NFC tag technology type NfcV (ISO 15693-3). Only available on iOS 14+ 0.3.0
iso15693CommandCode number The custom command code defined by the IC manufacturer for the NFC tag technology type NfcV (ISO 15693-3). Valid range is 0xA0 to 0xDF inclusively. Only available on iOS 14+ 0.3.0

IsSupportedResult

Prop Type Since
isSupported boolean 0.0.1

IsEnabledResult

Prop Type Since
isEnabled boolean 0.0.1

PermissionResult

Prop Type Description Since
nfc PermissionState Permission state for reading and writing NFC tags. 0.0.1

PluginListenerHandle

Prop Type
remove () => Promise<void>

NfcTagScannedEvent

Prop Type Description Since
nfcTag NfcTag The scanned NFC tag. 0.0.1

NfcTag

Prop Type Description Since
atqa number[] The ATQA/SENS_RES bytes of an NFC A tag. Only available on Android. 0.0.1
applicationData number[] The Application Data bytes from ATQB/SENSB_RES of an NFC B tag. Only available on Android and iOS. 0.0.1
barcode number[] The barcode bytes of an NfcBarcode tag. Only available on Android. 0.0.1
canMakeReadOnly boolean Whether the NDEF tag can be made read-only or not. Only available on Android. 0.0.1
dsfId number[] The DSF ID bytes of an NFC V tag. Only available on Android. 0.0.1
hiLayerResponse number[] The higher layer response bytes of an ISO-DEP tag. Only available on Android. 0.0.1
historicalBytes number[] The historical bytes of an ISO-DEP tag. Only available on Android and iOS. 0.0.1
id number[] The tag identifier (low level serial number) which is used for anti-collision and identification. 0.0.1
isWritable boolean Whether the NDEF tag is writable or not. Only available on Android and iOS. 0.0.1
manufacturer number[] The Manufacturer bytes of an NFC F tag. Only available on Android and iOS. 0.0.1
maxSize number The maximum NDEF message size in bytes. Only available on Android and iOS. 0.0.1
message NdefMessage The NDEF-formatted message. 0.0.1
protocolInfo number[] The Protocol Info bytes from ATQB/SENSB_RES of an NFC B tag. Only available on Android. 0.0.1
responseFlags number[] The Response Flag bytes of an NFC V tag. Only available on Android. 0.0.1
sak number[] The SAK/SEL_RES bytes of an NFC A tag. Only available on Android. 0.0.1
systemCode number[] The System Code bytes of an NFC F tag. Only available on Android and iOS. 0.0.1
techTypes NfcTagTechType[] The technologies available in this tag. Only available on Android and iOS. 0.0.1
type NfcTagType The NDEF tag type. Only available on Android and iOS. 0.0.1

ScanSessionErrorEvent

Prop Type Description Since
message string The error message. 0.0.1

Type Aliases

PermissionState

"denied" | "granted" | "prompt"

Enums

NfcTagTechType

Members Value Since
NfcA 'NFC_A' 0.0.1
NfcB 'NFC_B' 0.0.1
NfcF 'NFC_F' 0.0.1
NfcV 'NFC_V' 0.0.1
IsoDep 'ISO_DEP' 0.0.1
Ndef 'NDEF' 0.0.1
MifareClassic 'MIFARE_CLASSIC' 0.0.1
MifareUltralight 'MIFARE_ULTRALIGHT' 0.0.1
NfcBarcode 'NFC_BARCODE' 0.0.1
NdefFormatable 'NDEF_FORMATABLE' 0.0.1

PollingOption

Members Value Description Since
iso14443 'iso14443' The option for detecting ISO 7816-compatible and MIFARE tags. 0.2.0
iso15693 'iso15693' The option for detecting ISO 15693 tags. 0.2.0
iso18092 'iso18092' The option for detecting FeliCa tags. 0.2.0

TypeNameFormat

Members Value Description Since
Empty 0 An empty record with no type or payload. 0.0.1
WellKnown 1 A predefined type defined in the RTD specification of the NFC Forum. 0.0.1
MimeMedia 2 An Internet media type as defined in RFC 2046. 0.0.1
AbsoluteUri 3 A URI as defined in RFC 3986. 0.0.1
External 4 A user-defined value that is based on the rules of the NFC Forum Record Type Definition specification. 0.0.1
Unknown 5 Type is unknown. 0.0.1
Unchanged 6 Indicates the payload is an intermediate or final chunk of a chunked NDEF Record. 0.0.1

Iso15693RequestFlag

Members Value Since
address 'address' 0.3.0
commandSpecificBit8 'commandSpecificBit8' 0.3.0
dualSubCarriers 'dualSubCarriers' 0.3.0
highDataRate 'highDataRate' 0.3.0
option 'option' 0.3.0
protocolExtension 'protocolExtension' 0.3.0
select 'select' 0.3.0

NfcTagType

Members Value Since
NfcForumType1 'NFC_FORUM_TYPE_1' 0.0.1
NfcForumType2 'NFC_FORUM_TYPE_2' 0.0.1
NfcForumType3 'NFC_FORUM_TYPE_3' 0.0.1
NfcForumType4 'NFC_FORUM_TYPE_4' 0.0.1
MifareClassic 'MIFARE_CLASSIC' 0.0.1
MifareDesfire 'MIFARE_DESFIRE' 0.0.1
MifarePlus 'MIFARE_PLUS' 0.0.1
MifarePro 'MIFARE_PRO' 0.0.1
MifareUltralight 'MIFARE_ULTRALIGHT' 0.0.1
MifareUltralightC 'MIFARE_ULTRALIGHT_C' 0.0.1

Utils

See docs/utils/README.md.

Changelog

See CHANGELOG.md.

License

See LICENSE.

About

⚡️ Capacitor plugin for reading and writing NFC tags.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published