Best JavaScript code snippet using wpt
phonegap-nfc.js
Source:phonegap-nfc.js
1cordova.define("phonegap-nfc.NFC", function(require, exports, module) {2/*jshint bitwise: false, camelcase: false, quotmark: false, unused: vars */3/*global cordova, console */4"use strict";5function handleNfcFromIntentFilter() {6 // This was historically done in cordova.addConstructor but broke with PhoneGap-2.2.0.7 // We need to handle NFC from an Intent that launched the application, but *after*8 // the code in the application's deviceready has run. After upgrading to 2.2.0,9 // addConstructor was finishing *before* deviceReady was complete and the10 // ndef listeners had not been registered.11 // It seems like there should be a better solution.12 if (cordova.platformId === "android" || cordova.platformId === "windows") {13 setTimeout(14 function () {15 cordova.exec(16 function () {17 console.log("Initialized the NfcPlugin");18 },19 function (reason) {20 console.log("Failed to initialize the NfcPlugin " + reason);21 },22 "NfcPlugin", "init", []23 );24 }, 1025 );26 }27}28document.addEventListener('deviceready', handleNfcFromIntentFilter, false);29var ndef = {30 // see android.nfc.NdefRecord for documentation about constants31 // http://developer.android.com/reference/android/nfc/NdefRecord.html32 TNF_EMPTY: 0x0,33 TNF_WELL_KNOWN: 0x01,34 TNF_MIME_MEDIA: 0x02,35 TNF_ABSOLUTE_URI: 0x03,36 TNF_EXTERNAL_TYPE: 0x04,37 TNF_UNKNOWN: 0x05,38 TNF_UNCHANGED: 0x06,39 TNF_RESERVED: 0x07,40 RTD_TEXT: [0x54], // "T"41 RTD_URI: [0x55], // "U"42 RTD_SMART_POSTER: [0x53, 0x70], // "Sp"43 RTD_ALTERNATIVE_CARRIER: [0x61, 0x63], // "ac"44 RTD_HANDOVER_CARRIER: [0x48, 0x63], // "Hc"45 RTD_HANDOVER_REQUEST: [0x48, 0x72], // "Hr"46 RTD_HANDOVER_SELECT: [0x48, 0x73], // "Hs"47 /**48 * Creates a JSON representation of a NDEF Record.49 *50 * @tnf 3-bit TNF (Type Name Format) - use one of the TNF_* constants51 * @type byte array, containing zero to 255 bytes, must not be null52 * @id byte array, containing zero to 255 bytes, must not be null53 * @payload byte array, containing zero to (2 ** 32 - 1) bytes, must not be null54 *55 * @returns JSON representation of a NDEF record56 *57 * @see Ndef.textRecord, Ndef.uriRecord and Ndef.mimeMediaRecord for examples58 */59 record: function (tnf, type, id, payload) {60 // handle null values61 if (!tnf) { tnf = ndef.TNF_EMPTY; }62 if (!type) { type = []; }63 if (!id) { id = []; }64 if (!payload) { payload = []; }65 // convert strings to arrays66 if (!(type instanceof Array)) {67 type = nfc.stringToBytes(type);68 }69 if (!(id instanceof Array)) {70 id = nfc.stringToBytes(id);71 }72 if (!(payload instanceof Array)) {73 payload = nfc.stringToBytes(payload);74 }75 return {76 tnf: tnf,77 type: type,78 id: id,79 payload: payload80 };81 },82 /**83 * Helper that creates an NDEF record containing plain text.84 *85 * @text String of text to encode86 * @languageCode ISO/IANA language code. Examples: âfiâ, âen-USâ, âfr- CAâ, âjpâ. (optional)87 * @id byte[] (optional)88 */89 textRecord: function (text, languageCode, id) {90 var payload = textHelper.encodePayload(text, languageCode);91 if (!id) { id = []; }92 return ndef.record(ndef.TNF_WELL_KNOWN, ndef.RTD_TEXT, id, payload);93 },94 /**95 * Helper that creates a NDEF record containing a URI.96 *97 * @uri String98 * @id byte[] (optional)99 */100 uriRecord: function (uri, id) {101 var payload = uriHelper.encodePayload(uri);102 if (!id) { id = []; }103 return ndef.record(ndef.TNF_WELL_KNOWN, ndef.RTD_URI, id, payload);104 },105 /**106 * Helper that creates a NDEF record containing an absolute URI.107 *108 * An Absolute URI record means the URI describes the payload of the record.109 *110 * For example a SOAP message could use "http://schemas.xmlsoap.org/soap/envelope/"111 * as the type and XML content for the payload.112 *113 * Absolute URI can also be used to write LaunchApp records for Windows.114 *115 * See 2.4.2 Payload Type of the NDEF Specification116 * http://www.nfc-forum.org/specs/spec_list#ndefts117 *118 * Note that by default, Android will open the URI defined in the type119 * field of an Absolute URI record (TNF=3) and ignore the payload.120 * BlackBerry and Windows do not open the browser for TNF=3.121 *122 * To write a URI as the payload use ndef.uriRecord(uri)123 *124 * @uri String125 * @payload byte[] or String126 * @id byte[] (optional)127 */128 absoluteUriRecord: function (uri, payload, id) {129 if (!id) { id = []; }130 if (!payload) { payload = []; }131 return ndef.record(ndef.TNF_ABSOLUTE_URI, uri, id, payload);132 },133 /**134 * Helper that creates a NDEF record containing an mimeMediaRecord.135 *136 * @mimeType String137 * @payload byte[]138 * @id byte[] (optional)139 */140 mimeMediaRecord: function (mimeType, payload, id) {141 if (!id) { id = []; }142 return ndef.record(ndef.TNF_MIME_MEDIA, nfc.stringToBytes(mimeType), id, payload);143 },144 /**145 * Helper that creates an NDEF record containing an Smart Poster.146 *147 * @ndefRecords array of NDEF Records148 * @id byte[] (optional)149 */150 smartPoster: function (ndefRecords, id) {151 var payload = [];152 if (!id) { id = []; }153 if (ndefRecords)154 {155 // make sure we have an array of something like NDEF records before encoding156 if (ndefRecords[0] instanceof Object && ndefRecords[0].hasOwnProperty('tnf')) {157 payload = ndef.encodeMessage(ndefRecords);158 } else {159 // assume the caller has already encoded the NDEF records into a byte array160 payload = ndefRecords;161 }162 } else {163 console.log("WARNING: Expecting an array of NDEF records");164 }165 return ndef.record(ndef.TNF_WELL_KNOWN, ndef.RTD_SMART_POSTER, id, payload);166 },167 /**168 * Helper that creates an empty NDEF record.169 *170 */171 emptyRecord: function() {172 return ndef.record(ndef.TNF_EMPTY, [], [], []);173 },174 /**175 * Helper that creates an Android Application Record (AAR).176 * http://developer.android.com/guide/topics/connectivity/nfc/nfc.html#aar177 *178 */179 androidApplicationRecord: function(packageName) {180 return ndef.record(ndef.TNF_EXTERNAL_TYPE, "android.com:pkg", [], packageName);181 },182 /**183 * Encodes an NDEF Message into bytes that can be written to a NFC tag.184 *185 * @ndefRecords an Array of NDEF Records186 *187 * @returns byte array188 *189 * @see NFC Data Exchange Format (NDEF) http://www.nfc-forum.org/specs/spec_list/190 */191 encodeMessage: function (ndefRecords) {192 var encoded = [],193 tnf_byte,194 type_length,195 payload_length,196 id_length,197 i,198 mb, me, // messageBegin, messageEnd199 cf = false, // chunkFlag TODO implement200 sr, // boolean shortRecord201 il; // boolean idLengthFieldIsPresent202 for(i = 0; i < ndefRecords.length; i++) {203 mb = (i === 0);204 me = (i === (ndefRecords.length - 1));205 sr = (ndefRecords[i].payload.length < 0xFF);206 il = (ndefRecords[i].id.length > 0);207 tnf_byte = ndef.encodeTnf(mb, me, cf, sr, il, ndefRecords[i].tnf);208 encoded.push(tnf_byte);209 type_length = ndefRecords[i].type.length;210 encoded.push(type_length);211 if (sr) {212 payload_length = ndefRecords[i].payload.length;213 encoded.push(payload_length);214 } else {215 payload_length = ndefRecords[i].payload.length;216 // 4 bytes217 encoded.push((payload_length >> 24));218 encoded.push((payload_length >> 16));219 encoded.push((payload_length >> 8));220 encoded.push((payload_length & 0xFF));221 }222 if (il) {223 id_length = ndefRecords[i].id.length;224 encoded.push(id_length);225 }226 encoded = encoded.concat(ndefRecords[i].type);227 if (il) {228 encoded = encoded.concat(ndefRecords[i].id);229 }230 encoded = encoded.concat(ndefRecords[i].payload);231 }232 return encoded;233 },234 /**235 * Decodes an array bytes into an NDEF Message236 *237 * @bytes an array bytes read from a NFC tag238 *239 * @returns array of NDEF Records240 *241 * @see NFC Data Exchange Format (NDEF) http://www.nfc-forum.org/specs/spec_list/242 */243 decodeMessage: function (bytes) {244 var bytes = bytes.slice(0), // clone since parsing is destructive245 ndef_message = [],246 tnf_byte,247 header,248 type_length = 0,249 payload_length = 0,250 id_length = 0,251 record_type = [],252 id = [],253 payload = [];254 while(bytes.length) {255 tnf_byte = bytes.shift();256 header = ndef.decodeTnf(tnf_byte);257 type_length = bytes.shift();258 if (header.sr) {259 payload_length = bytes.shift();260 } else {261 // next 4 bytes are length262 payload_length = ((0xFF & bytes.shift()) << 24) |263 ((0xFF & bytes.shift()) << 26) |264 ((0xFF & bytes.shift()) << 8) |265 (0xFF & bytes.shift());266 }267 if (header.il) {268 id_length = bytes.shift();269 }270 record_type = bytes.splice(0, type_length);271 id = bytes.splice(0, id_length);272 payload = bytes.splice(0, payload_length);273 ndef_message.push(274 ndef.record(header.tnf, record_type, id, payload)275 );276 if (header.me) { break; } // last message277 }278 return ndef_message;279 },280 /**281 * Decode the bit flags from a TNF Byte.282 *283 * @returns object with decoded data284 *285 * See NFC Data Exchange Format (NDEF) Specification Section 3.2 RecordLayout286 */287 decodeTnf: function (tnf_byte) {288 return {289 mb: (tnf_byte & 0x80) !== 0,290 me: (tnf_byte & 0x40) !== 0,291 cf: (tnf_byte & 0x20) !== 0,292 sr: (tnf_byte & 0x10) !== 0,293 il: (tnf_byte & 0x8) !== 0,294 tnf: (tnf_byte & 0x7)295 };296 },297 /**298 * Encode NDEF bit flags into a TNF Byte.299 *300 * @returns tnf byte301 *302 * See NFC Data Exchange Format (NDEF) Specification Section 3.2 RecordLayout303 */304 encodeTnf: function (mb, me, cf, sr, il, tnf) {305 var value = tnf;306 if (mb) {307 value = value | 0x80;308 }309 if (me) {310 value = value | 0x40;311 }312 // note if cf: me, mb, li must be false and tnf must be 0x6313 if (cf) {314 value = value | 0x20;315 }316 if (sr) {317 value = value | 0x10;318 }319 if (il) {320 value = value | 0x8;321 }322 return value;323 },324 /**325 * Convert TNF to String for user friendly display326 *327 */328 tnfToString: function (tnf) {329 var value = tnf;330 switch (tnf) {331 case ndef.TNF_EMPTY:332 value = "Empty";333 break;334 case ndef.TNF_WELL_KNOWN:335 value = "Well Known";336 break;337 case ndef.TNF_MIME_MEDIA:338 value = "Mime Media";339 break;340 case ndef.TNF_ABSOLUTE_URI:341 value = "Absolute URI";342 break;343 case ndef.TNF_EXTERNAL_TYPE:344 value = "External";345 break;346 case ndef.TNF_UNKNOWN:347 value = "Unknown";348 break;349 case ndef.TNF_UNCHANGED:350 value = "Unchanged";351 break;352 case ndef.TNF_RESERVED:353 value = "Reserved";354 break;355 }356 return value;357 }358};359// nfc provides javascript wrappers to the native phonegap implementation360var nfc = {361 addTagDiscoveredListener: function (callback, win, fail) {362 document.addEventListener("tag", callback, false);363 cordova.exec(win, fail, "NfcPlugin", "registerTag", []);364 },365 addMimeTypeListener: function (mimeType, callback, win, fail) {366 document.addEventListener("ndef-mime", callback, false);367 cordova.exec(win, fail, "NfcPlugin", "registerMimeType", [mimeType]);368 },369 addNdefListener: function (callback, win, fail) {370 document.addEventListener("ndef", callback, false);371 cordova.exec(win, fail, "NfcPlugin", "registerNdef", []);372 },373 addNdefFormatableListener: function (callback, win, fail) {374 document.addEventListener("ndef-formatable", callback, false);375 cordova.exec(win, fail, "NfcPlugin", "registerNdefFormatable", []);376 },377 write: function (ndefMessage, win, fail) {378 cordova.exec(win, fail, "NfcPlugin", "writeTag", [ndefMessage]);379 },380 makeReadOnly: function (win, fail) {381 cordova.exec(win, fail, "NfcPlugin", "makeReadOnly", []);382 },383 share: function (ndefMessage, win, fail) {384 cordova.exec(win, fail, "NfcPlugin", "shareTag", [ndefMessage]);385 },386 unshare: function (win, fail) {387 cordova.exec(win, fail, "NfcPlugin", "unshareTag", []);388 },389 handover: function (uris, win, fail) {390 // if we get a single URI, wrap it in an array391 if (!Array.isArray(uris)) {392 uris = [ uris ];393 }394 cordova.exec(win, fail, "NfcPlugin", "handover", uris);395 },396 stopHandover: function (win, fail) {397 cordova.exec(win, fail, "NfcPlugin", "stopHandover", []);398 },399 erase: function (win, fail) {400 cordova.exec(win, fail, "NfcPlugin", "eraseTag", [[]]);401 },402 enabled: function (win, fail) {403 cordova.exec(win, fail, "NfcPlugin", "enabled", [[]]);404 },405 removeTagDiscoveredListener: function (callback, win, fail) {406 document.removeEventListener("tag", callback, false);407 cordova.exec(win, fail, "NfcPlugin", "removeTag", []);408 },409 removeMimeTypeListener: function(mimeType, callback, win, fail) {410 document.removeEventListener("ndef-mime", callback, false);411 cordova.exec(win, fail, "NfcPlugin", "removeMimeType", [mimeType]);412 },413 removeNdefListener: function (callback, win, fail) {414 document.removeEventListener("ndef", callback, false);415 cordova.exec(win, fail, "NfcPlugin", "removeNdef", []);416 },417 showSettings: function (win, fail) {418 cordova.exec(win, fail, "NfcPlugin", "showSettings", []);419 }420};421var util = {422 // i must be <= 256423 toHex: function (i) {424 var hex;425 if (i < 0) {426 i += 256;427 }428 hex = i.toString(16);429 // zero padding430 if (hex.length === 1) {431 hex = "0" + hex;432 }433 return hex;434 },435 toPrintable: function(i) {436 if (i >= 0x20 & i <= 0x7F) {437 return String.fromCharCode(i);438 } else {439 return '.';440 }441 },442 bytesToString: function(bytes) {443 // based on http://ciaranj.blogspot.fr/2007/11/utf8-characters-encoding-in-javascript.html444 var result = "";445 var i, c, c1, c2, c3;446 i = c = c1 = c2 = c3 = 0;447 // Perform byte-order check.448 if( bytes.length >= 3 ) {449 if( (bytes[0] & 0xef) == 0xef && (bytes[1] & 0xbb) == 0xbb && (bytes[2] & 0xbf) == 0xbf ) {450 // stream has a BOM at the start, skip over451 i = 3;452 }453 }454 while ( i < bytes.length ) {455 c = bytes[i] & 0xff;456 if ( c < 128 ) {457 result += String.fromCharCode(c);458 i++;459 } else if ( (c > 191) && (c < 224) ) {460 if ( i + 1 >= bytes.length ) {461 throw "Un-expected encoding error, UTF-8 stream truncated, or incorrect";462 }463 c2 = bytes[i + 1] & 0xff;464 result += String.fromCharCode( ((c & 31) << 6) | (c2 & 63) );465 i += 2;466 } else {467 if ( i + 2 >= bytes.length || i + 1 >= bytes.length ) {468 throw "Un-expected encoding error, UTF-8 stream truncated, or incorrect";469 }470 c2 = bytes[i + 1] & 0xff;471 c3 = bytes[i + 2] & 0xff;472 result += String.fromCharCode( ((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63) );473 i += 3;474 }475 }476 return result;477 },478 stringToBytes: function(string) {479 // based on http://ciaranj.blogspot.fr/2007/11/utf8-characters-encoding-in-javascript.html480 var bytes = [];481 for (var n = 0; n < string.length; n++) {482 var c = string.charCodeAt(n);483 if (c < 128) {484 bytes[bytes.length]= c;485 } else if((c > 127) && (c < 2048)) {486 bytes[bytes.length] = (c >> 6) | 192;487 bytes[bytes.length] = (c & 63) | 128;488 } else {489 bytes[bytes.length] = (c >> 12) | 224;490 bytes[bytes.length] = ((c >> 6) & 63) | 128;491 bytes[bytes.length] = (c & 63) | 128;492 }493 }494 return bytes;495 },496 bytesToHexString: function (bytes) {497 var dec, hexstring, bytesAsHexString = "";498 for (var i = 0; i < bytes.length; i++) {499 if (bytes[i] >= 0) {500 dec = bytes[i];501 } else {502 dec = 256 + bytes[i];503 }504 hexstring = dec.toString(16);505 // zero padding506 if (hexstring.length === 1) {507 hexstring = "0" + hexstring;508 }509 bytesAsHexString += hexstring;510 }511 return bytesAsHexString;512 },513 // This function can be removed if record.type is changed to a String514 /**515 * Returns true if the record's TNF and type matches the supplied TNF and type.516 *517 * @record NDEF record518 * @tnf 3-bit TNF (Type Name Format) - use one of the TNF_* constants519 * @type byte array or String520 */521 isType: function(record, tnf, type) {522 if (record.tnf === tnf) { // TNF is 3-bit523 var recordType;524 if (typeof(type) === 'string') {525 recordType = type;526 } else {527 recordType = nfc.bytesToString(type);528 }529 return (nfc.bytesToString(record.type) === recordType);530 }531 return false;532 }533};534// this is a module in ndef-js535var textHelper = {536 decodePayload: function (data) {537 var languageCodeLength = (data[0] & 0x3F), // 6 LSBs538 languageCode = data.slice(1, 1 + languageCodeLength),539 utf16 = (data[0] & 0x80) !== 0; // assuming UTF-16BE540 // TODO need to deal with UTF in the future541 // console.log("lang " + languageCode + (utf16 ? " utf16" : " utf8"));542 return util.bytesToString(data.slice(languageCodeLength + 1));543 },544 // encode text payload545 // @returns an array of bytes546 encodePayload: function(text, lang, encoding) {547 // ISO/IANA language code, but we're not enforcing548 if (!lang) { lang = 'en'; }549 var encoded = util.stringToBytes(lang + text);550 encoded.unshift(lang.length);551 return encoded;552 }553};554// this is a module in ndef-js555var uriHelper = {556 // URI identifier codes from URI Record Type Definition NFCForum-TS-RTD_URI_1.0 2006-07-24557 // index in array matches code in the spec558 protocols: [ "", "http://www.", "https://www.", "http://", "https://", "tel:", "mailto:", "ftp://anonymous:anonymous@", "ftp://ftp.", "ftps://", "sftp://", "smb://", "nfs://", "ftp://", "dav://", "news:", "telnet://", "imap:", "rtsp://", "urn:", "pop:", "sip:", "sips:", "tftp:", "btspp://", "btl2cap://", "btgoep://", "tcpobex://", "irdaobex://", "file://", "urn:epc:id:", "urn:epc:tag:", "urn:epc:pat:", "urn:epc:raw:", "urn:epc:", "urn:nfc:" ],559 // decode a URI payload bytes560 // @returns a string561 decodePayload: function (data) {562 var prefix = uriHelper.protocols[data[0]];563 if (!prefix) { // 36 to 255 should be ""564 prefix = "";565 }566 return prefix + util.bytesToString(data.slice(1));567 },568 // shorten a URI with standard prefix569 // @returns an array of bytes570 encodePayload: function (uri) {571 var prefix,572 protocolCode,573 encoded;574 // check each protocol, unless we've found a match575 // "urn:" is the one exception where we need to keep checking576 // slice so we don't check ""577 uriHelper.protocols.slice(1).forEach(function(protocol) {578 if ((!prefix || prefix === "urn:") && uri.indexOf(protocol) === 0) {579 prefix = protocol;580 }581 });582 if (!prefix) {583 prefix = "";584 }585 encoded = util.stringToBytes(uri.slice(prefix.length));586 protocolCode = uriHelper.protocols.indexOf(prefix);587 // prepend protocol code588 encoded.unshift(protocolCode);589 return encoded;590 }591};592// added since WP8 must call a named function593// TODO consider switching NFC events from JS events to using the PG callbacks594function fireNfcTagEvent(eventType, tagAsJson) {595 setTimeout(function () {596 var e = document.createEvent('Events');597 e.initEvent(eventType, true, false);598 e.tag = JSON.parse(tagAsJson);599 console.log(e.tag);600 document.dispatchEvent(e);601 }, 10);602}603// textHelper and uriHelper aren't exported, add a property604ndef.uriHelper = uriHelper;605ndef.textHelper = textHelper;606// create aliases607nfc.bytesToString = util.bytesToString;608nfc.stringToBytes = util.stringToBytes;609nfc.bytesToHexString = util.bytesToHexString;610// kludge some global variables for plugman js-module support611// eventually these should be replaced and referenced via the module612window.nfc = nfc;613window.ndef = ndef;614window.util = util;615window.fireNfcTagEvent = fireNfcTagEvent;...
nfcutil.js
Source:nfcutil.js
12var compatibleDevices = [3 {4 deviceName: 'ACR122U USB NFC Reader',5 productId: 0x2200,6 vendorId: 0x072f,7 thumbnailURL: 'images/acr122u.png'8 },9 {10 deviceName: 'SCL3711 Contactless USB Smart Card Reader',11 productId: 0x5591,12 vendorId: 0x04e6,13 thumbnailURL: 'images/scl3711.png'14 }15]16function log(message, object) {17 console.log(message);18 console.log(object);19 return;20 var logArea = document.querySelector('.logs');21 var pre = document.createElement('pre');22 pre.textContent = message;23 if (object)24 pre.textContent += ': ' + JSON.stringify(object, null, 2) + '\n';25 logArea.appendChild(pre);26 logArea.scrollTop = logArea.scrollHeight;27 document.querySelector('#logContainer').classList.remove('small');28}29function handleDeviceTimeout(func, args) {30 var timeoutInMs = 1000;31 var hasTags = false;32 setTimeout(function () {33 if (!hasTags) {34 log('Timeout! No tag detected');35 }36 }, timeoutInMs);37 var args = args || [];38 args = args.concat([function () { hasTags = true; }]);39 func.apply(this, args);40}41function onReadNdefTagButtonClicked() {42 handleDeviceTimeout(readNdefTag);43}44function readNdefTag(callback) {45 chrome.nfc.read(device, {}, function (type, ndef) {46 log('Found ' + ndef.ndef.length + ' NFC Tag(s)');47 for (var i = 0; i < ndef.ndef.length; i++)48 log('NFC Tag', ndef.ndef[i]);49 callback();50 });51}52function onReadMifareTagButtonClicked() {53 handleDeviceTimeout(readMifareTag);54}55function readMifareTagEx(callback) {56 var blockNumber = 0; // starting logic block number.57 var blocksCount = 2; // logic block counts.58 chrome.nfc.read_logic(device, blockNumber, blocksCount, function (rc, data) {59 log('Mifare Classic Tag', UTIL_BytesToHex(data));60 if (callback)61 callback(rc, data);62 });63}64function readMifareTag(callback) {65 var blockNumber = 0; // starting logic block number.66 var blocksCount = 2; // logic block counts.67 chrome.nfc.read_logic(device, blockNumber, blocksCount, function (rc, data) {68 log('Mifare Classic Tag', UTIL_BytesToHex(data));69 callback();70 });71}72function onWriteNdefTagButtonClicked() {73 var ndefType = document.querySelector('#write-ndef-type').value;74 var ndefValue = document.querySelector('#write-ndef-value').value;75 handleDeviceTimeout(writeNdefTag, [ndefType, ndefValue]);76}77function writeNdefTag(ndefType, ndefValue, callback) {78 var ndef = {};79 ndef[ndefType] = ndefValue;80 chrome.nfc.write(device, { "ndef": [ndef] }, function (rc) {81 if (!rc) {82 log('NFC Tag written!');83 } else {84 log('NFC Tag write operation failed', rc);85 }86 callback();87 });88}89function onWriteMifareTagButtonClicked() {90 try {91 var mifareData = JSON.parse(document.querySelector('#mifare-data').value);92 handleDeviceTimeout(writeMifareTag, [mifareData]);93 }94 catch (e) {95 log('Error', 'Mifare Data is not an Array.');96 }97}98function writeMifareTag(mifareData, callback) {99 var data = new Uint8Array(mifareData);100 var blockNumber = 0; // starting logic block number.101 chrome.nfc.write_logic(device, 0, data, function (rc) {102 if (!rc) {103 log('Mifare Tag written!');104 } else {105 log('Mifare Tag write operation failed', rc);106 }107 callback();108 });109}110function onEmulateTagButtonClicked() {111 var ndefType = document.querySelector('#emulate-ndef-type').value;112 var ndefValue = document.querySelector('#emulate-ndef-value').value;113 handleDeviceTimeout(emulateTag, [ndefType, ndefValue]);114}115function emulateTag(ndefType, ndefValue, callback) {116 var ndef = {};117 ndef[ndefType] = ndefValue;118 chrome.nfc.emulate_tag(device, { "ndef": [ndef] }, function (rc) {119 if (!rc) {120 log('NFC Tag emulated!');121 } else {122 log('NFC Tag emulate operation failed', rc);123 }124 callback();125 });...
Using AI Code Generation
1var ndef = require('ndef');2var nfc = require('nfc').nfc;3var nfc = new NFC();4var tag = nfc.connect();5var message = ndef.decodeMessage(tag.ndefMessage);6console.log(message);7 throw err;8var nfc = require('nfc').nfc;9var nfc = new NFC();10var tag = nfc.connect();11var message = ndef.decodeMessage(tag.ndefMessage);12console.log(message);
Using AI Code Generation
1var ndef = require("ndef");2var encoded = ndef.encodeMessage([3 ndef.textRecord("Hello World")4]);5console.log(encoded);6var ndef = require("ndef");7var encoded = ndef.encodeMessage([8 ndef.textRecord("Hello World")9]);10console.log(encoded);11var ndef = require("ndef");12var encoded = ndef.encodeMessage([13 ndef.textRecord("Hello World")14]);15console.log(encoded);16var ndef = require("ndef");17var encoded = ndef.encodeMessage([18 ndef.textRecord("Hello World")19]);20console.log(encoded);21var ndef = require("ndef");22var encoded = ndef.encodeMessage([23 ndef.textRecord("Hello World")24]);25console.log(encoded);26var ndef = require("ndef");27var encoded = ndef.encodeMessage([28 ndef.textRecord("Hello World")29]);30console.log(encoded);31var ndef = require("ndef");32var encoded = ndef.encodeMessage([33 ndef.textRecord("Hello World")34]);35console.log(encoded);36var ndef = require("ndef");37var encoded = ndef.encodeMessage([38 ndef.textRecord("Hello World")39]);40console.log(encoded);41var ndef = require("ndef");42var encoded = ndef.encodeMessage([43 ndef.textRecord("Hello World")44]);45console.log(encoded);46var ndef = require("ndef");47var encoded = ndef.encodeMessage([48 ndef.textRecord("Hello World")49]);50console.log(encoded);51var ndef = require("ndef");52var encoded = ndef.encodeMessage([53 ndef.textRecord("Hello World")54]);55console.log(encoded);56var ndef = require("ndef");57var encoded = ndef.encodeMessage([58 ndef.textRecord("Hello World")59]);60console.log(encoded);61var ndef = require("
Using AI Code Generation
1var ndef = navigator.ndef;2var message = ndef.createMessage([3 ndef.textRecord("Hello, World!"),4 ndef.mimeMediaRecord("application/custom", "custom data")5]);6ndef.write(message).then(function() {7 console.log("Message written to tag.");8}, function(error) {9 console.log("Write failed :-( try again: " + error);10});11ndef.read().then(function(message) {12 console.log("Message read from tag: " + JSON.stringify(message));13}, function(error) {14 console.log("Read failed :-( try again: " + error);15});16ndef.onreading = function(event) {17 console.log("Message read from tag: " + JSON.stringify(event.message));18};19ndef.stopListening().then(function() {20 console.log("Stopped reading tags.");21}, function(error) {22 console.log("Stop listening failed :-( try again: " + error);23});24ndef.onchange = function(event) {25 console.log("Tag changed: " + event.serialNumber);26};27ndef.stopMonitoring().then(function() {28 console.log("Stopped monitoring tags.");29}, function(error) {30 console.log("Stop monitoring failed :-( try again: " + error);31});32var nfc = navigator.nfc;33nfc.write("Hello, World!").then(function() {34 console.log("Message written to tag.");35}, function(error) {36 console.log("Write failed :-( try again: " + error);37});38nfc.read().then(function(message) {39 console.log("Message read from tag: " + message);40}, function(error) {41 console.log("Read failed :-( try again: " + error);42});43nfc.onreading = function(event) {44 console.log("Message read from tag: " + event.message);45};46nfc.stopListening().then(function() {47 console.log("Stopped reading tags.");
Using AI Code Generation
1var ndef = require('ndef');2var NdefLib = require('ndeflib');3var ndeflib = new NdefLib();4var text = 'Hello World';5var textRecord = ndef.textRecord(text);6var uriRecord = ndef.uriRecord(uri);7var records = [textRecord, uriRecord];8var message = ndef.encodeMessage(records);9var buffer = ndef.decodeMessage(message);10console.log(buffer);11var ndef = require('ndef');12var NdefLib = require('ndeflib');13var ndeflib = new NdefLib();14var text = 'Hello World';15var textRecord = ndeflib.textRecord(text);16var uriRecord = ndeflib.uriRecord(uri);17var records = [textRecord, uriRecord];18var message = ndeflib.encodeMessage(records);19var buffer = ndeflib.decodeMessage(message);20console.log(buffer);21var ndef = require('ndef');22var NdefLib = require('ndeflib');23var ndeflib = new NdefLib();24var text = 'Hello World';25var textRecord = ndeflib.textRecord(text);26var uriRecord = ndeflib.uriRecord(uri);27var records = [textRecord, uriRecord];28var message = ndeflib.encodeMessage(records);29var buffer = ndeflib.decodeMessage(message);30console.log(buffer);31var ndef = require('ndef');32var NdefLib = require('ndeflib');33var ndeflib = new NdefLib();34var text = 'Hello World';35var textRecord = ndef.textRecord(text);36var uriRecord = ndef.uriRecord(uri);37var records = [textRecord, uriRecord];38var message = ndef.encodeMessage(records);39var buffer = ndef.decodeMessage(message);40console.log(buffer);41var ndef = require('ndef');42var NdefLib = require('ndeflib');43var ndeflib = new NdefLib();44var text = 'Hello World';45var textRecord = ndef.textRecord(text);
Using AI Code Generation
1var ndef = new NDEF();2var ndefMessage = ndef.textRecord("Hello, World!");3var success = ndef.writeNDEF(ndefMessage);4console.log("Wrote NDEF message: " + success);5var nfc = new NFC();6var success = nfc.writeNDEF(ndefMessage);7console.log("Wrote NDEF message: " + success);8var nfc = new NFC();9var success = nfc.writeNDEF(ndefMessage);10console.log("Wrote NDEF message: " + success);11var ndef = new NDEF();12var ndefMessage = ndef.textRecord("Hello, World!");13var success = ndef.writeNDEF(ndefMessage);14console.log("Wrote NDEF message: " + success);15var nfc = new NFC();16var success = nfc.writeNDEF(ndefMessage);17console.log("Wrote NDEF message: " + success);18var nfc = new NFC();19var success = nfc.writeNDEF(ndefMessage);20console.log("Wrote NDEF message: " + success);
Using AI Code Generation
1var nfc = require("nfc");2var ndef = nfc.ndef;3var util = require("util");4function writeNdefMessage(ndefMessage) {5 nfc.writeNdefMessage(ndefMessage, function(err) {6 if (err) {7 console.log("Error writing NDEF message: " + err);8 } else {9 console.log("Successfully wrote NDEF message");10 }11 });12}13function readNdefMessage() {14 nfc.readNdefMessage(function(err, ndefMessage) {15 if (err) {16 console.log("Error reading NDEF message: " + err);17 } else {18 console.log("Successfully read NDEF message: " + util.inspect(ndefMessage));19 }20 });21}22function readNdefMessage2() {23 nfc.readNdefMessage(function(err, ndefMessage) {24 if (err) {25 console.log("Error reading NDEF message: " + err);26 } else {27 console.log("Successfully read NDEF message: " + util.inspect(ndefMessage));28 }29 });30}31function readNdefMessage3() {32 nfc.readNdefMessage(function(err, ndefMessage) {33 if (err) {34 console.log("Error reading NDEF message: " + err);35 } else {36 console.log("Successfully read NDEF message: " + util.inspect(ndefMessage));37 }38 });39}40function readNdefMessage4() {41 nfc.readNdefMessage(function(err, ndefMessage) {42 if (err) {43 console.log("Error reading NDEF message: " + err);44 } else {45 console.log("Successfully read NDEF message: " + util.inspect(ndefMessage));46 }47 });48}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!