Create a gist now

Instantly share code, notes, and snippets.

@tauzen /app.js
Last active Aug 29, 2015

What would you like to do?
FirefoxOS tag writing example, requires NFC capable device running FirefoxOS 2.1. App needs to be certified! Privileged APIs comming soon!
window.addEventListener('DOMContentLoaded', function() {
'use strict';
console.log('DOMContentLoaded, checking for NFC');
if (!navigator.mozNfc) {
console.log('NFC not available');
return;
}
navigator.mozSetMessageHandler('activity', (activity) => {
var data = activity.source.data;
// prepare NDEF record to write using NfcUtils from shared/js/nfc_utils.js
var nfcUtils = new NfcUtils();
var tnf = NDEF.TNF_WELL_KNOWN;
var type = NDEF.RTD_URI;
var url = nfcUtils.fromUTF8('\u0003mozilla.org');
var record = new MozNDEFRecord({tnf:tnf, type:type, payload:url});
// getting the tag
var tag = navigator.mozNfc.getNFCTag(data.sessionToken);
// writing array of NDEF records (NDEF message) to the tag
var request = tag.writeNDEF([record]);
request.onsuccess = () => {
console.log('wrote data to tag');
};
request.onerror = () => {
console.log('failed to write data to tag');
};
return true;
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tag Write</title>
<meta name="viewport" content="width=device-width">
<script type="text/javascript" src="shared/js/nfc_utils.js" defer></script>
<script type="text/javascript" src="js/app.js" defer></script>
</head>
<body></body>
</html>
{
"version": "0.1.0",
"name": "Tag write",
"description": "Quick example of writing contents on tag",
"launch_path": "/index.html",
"type": "certified",
"permissions": {
"nfc": { "access": "readwrite" }
},
"activities": {
"nfc-ndef-discovered": {
"filters": {
"type": "empty"
}
}
},
"default_locale": "en"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment