cordova-plugin-nfc-android
A plugin to handle read/write NDEF messages from NFC on Android.
Installation:
For stable relases type:
cordova plugin add cordova-plugin-nfc-android
For latest releases type:
cordova plugin add https://github.com/bkamenov/cordova-plugin-nfc-android
API & Usage:
cordova.plugins.NFC.status(
(status) => {
console.log('NFC status:', status);
if(status === "NFC_DISABLED") {
cordova.plugins.NFC.showSettings();
}
});
cordova.plugins.NFC.askForPermission(
(granted) => {
console.log('NFC permission granted:', granted);
});
cordova.plugins.NFC.setMimeTypeFilter(["text/plain"],
() => {
console.log('MIME type filter set');
},
(error: string) => {
console.error('Failed to set MIME type filter:', error);
});
function arrayBufferToString(buffer) {
const decoder = new TextDecoder('utf-8');
const view = new Uint8Array(buffer);
return decoder.decode(view);
}
document.addEventListener('ndef',
(event) => {
const ndef = event.detail;
console.log("NDEF tag detected: " + ndef.tagSerial);
if (ndef.mimeType)
console.log("NDEF tag MIME: " + ndef.mimeType);
console.log("NDEF data as text: " + arrayBufferToString(ndef.ndefData));
const message = {
mimeType: "text/plain",
ndefData: new TextEncoder().encode("My message").buffer
};
cordova.plugins.NFC.write(message,
() => {
console.log('NDEF message written successfully');
},
(error) => {
console.log('Failed to write NDEF message:', error);
});
});
document.addEventListener('nfcstatechange',
(event) => {
console.log("NFC state changed to: " + event.detail);
});
It is recomended to use cordova-plugin-nfc-launcher-android if you want your app to launch automatically when a NDEF message with specific MIME type is detected.
If you like my work and want more nice plugins, you can get me a beer or stake.