Skip to content

Instantly share code, notes, and snippets.

@don
Last active December 17, 2015 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save don/5544034 to your computer and use it in GitHub Desktop.
Save don/5544034 to your computer and use it in GitHub Desktop.
phonegap-nfc - write a message to unformatted tags, read text message from NDEF tags
// handle unformatted tags
nfc.addNdefFormatableListener(
function (nfcEvent) {
// NDEF message with one record
var message = [
ndef.textRecord("hello, world")
];
nfc.write(
message,
function() {
alert("Wrote message to tag");
},
function(error) {
alert("Write failed " + JSON.stringify(error));
}
);
},
function () {
console.log("Listening for NDEF Formatable Tags");
},
function (error) {
alert("Failed to add listener for NDEF Formatable Tags");
}
);
// handle NDEF tags
nfc.addNdefListener(
function (nfcEvent) {
var tag = nfcEvent.tag,
ndefMessage = tag.ndefMessage,
firstRecord = ndefMessage[0],
payload = firstRecord.payload,
text;
// assume we read a text message with "en" encoding
// remove the encoding info and convert to string
text = nfc.bytesToString(payload.slice(3));
alert(text);
},
function () {
console.log("Listening for NDEF Tags");
},
function (error) {
alert("Failed to add listener for NDEF Tags");
}
);
@valemunoz
Copy link

hi!

thank for the code, do you know if can i read mifare classic witho some phonegap plugin?

thanks

@cappelaere
Copy link

Hi Don,
I tried your code to write a tag. It seems to work...I get into Listening mode for NDF Formattable Tags.
Problem is that when I tap a tag, the NFC service detects it and bring up a popup rather than let my app handle it.
What do I need to do to disable this?
Thanks,
Pat.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment