Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Types for WebNFC as implemented by Chrome
/**
* Types for the version of Web NFC available in Chrome for Android
*
* The spec is similar to, but does not exactly match https://w3c.github.io/web-nfc/releases/20151112/
*/
declare global {
interface Navigator {
nfc: WebNFC
}
interface WebNFC {
watch(messageScanned: MessageCallback, options?: NFCWatchOptions): Promise<number>
cancelWatch(id?: number): Promise<void>;
push(message: NFCPushMessage): Promise<void>;
cancelPush(target?: NFCPushTarget): Promise<void>;
}
interface NFCMessage {
records: NFCRecord[],
url: string
}
interface NFCRecord {
data: NFCRecordData,
mediaType: string,
recordType: NFCRecordType
}
type NFCRecordData = string | number | ArrayBuffer | object;
interface MessageCallback {
(message: NFCMessage): void
}
interface NFCWatchOptions {
url?: string,
kind?: NFCRecordType,
mediaType?: string,
mode?: NFCWatchMode
}
type NFCWatchMode =
"web-nfc-only" |
"any";
type NFCRecordType =
"empty" |
"text" |
"url" |
"json" |
"opaque";
type NFCPushMessage =
string |
ArrayBuffer |
NFCMessage;
interface NFCPushOptions {
target?: NFCPushTarget,
timeout?: number,
ignoreRead?: boolean,
}
type NFCPushTarget =
"tag" |
"peer" |
"any";
}
export {}
@samuanv
Copy link

samuanv commented Jun 18, 2019

thanks for sharing this! it is really helpful. I would like to kindly ask you if we can have a quick chat about WebNFC in production? Working in a personal project currently that would benefit from it. Thanks in advance!

Loading

@richardszalay
Copy link
Author

richardszalay commented Jun 18, 2019

@samuanv Sure, shoot me an email. firstname at firstnamelastname dot com

Loading

@MustafaUzumcu
Copy link

MustafaUzumcu commented Jun 19, 2019

hi richard, thanks for sharing this post.
but I don't understand how to use this object via chrome. set the android chrome options. Experimental Web Platform features and WebNFC enabled.
Use the javascript code. "https://whatwebcando.today/nfc.html"
But, return this message = NFC API not supported. Please help me?

function readWriteNfc() {
  if ('nfc' in navigator) {
    navigator.nfc.watch(function (message) {
        consoleLog("NFC message received from URL " + message.url);
        if (message.data[0].recordType === 'empty') {
          navigator.nfc.push([{
            url: message.url,
            data: [{
              recordType: "text",
              data: 'Hello World'
            }]
          }]);
        }
        processMessage(message);
      }, {mode: 'any'})
      .then(() => consoleLog("Added a watch."))
      .catch(err => consoleLog("Adding watch failed: " + err.name));
  } else {
    consoleLog('NFC API not supported.');
  }
}

function consoleLog(data) {
  var logElement = document.getElementById('log');
  logElement.innerHTML += '\n' + data;
}

function processMessage(message) {
  message.data.forEach(function (record) {
    if (record.recordType == "string") {
      consoleLog('Data is string: ' + record.data);
    } else if (record.recordType == "json") {
      processJSON(record.data);
    } else if (record.recordType == "url") {
      consoleLog("Data is URL: " + record.data);
    } else if (record.recordType == "opaque" && record.mediaType == 'image/png') {
      processPng(record.data);
    };
  });
}

function processPng(data) {
  consoleLog("Known image/png data");

  var img = document.createElement("img");
  img.src = URL.createObjectURL(new Blob(data, 'image/png'));
  img.onload = function () {
    window.URL.revokeObjectURL(this.src);
  };
};

function processJSON(data) {
  var obj = JSON.parse(data);
  consoleLog("JSON data: " + obj.myProperty.toString());
};

Loading

@richardszalay
Copy link
Author

richardszalay commented Jun 25, 2019

@MustafaUzumcu That detection code looks fine. Are you accessing the site via HTTPS? That's a restriction, if I recall correctly.

Btw if you get passed the detection, it should be message.records not message.data

Loading

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