Skip to content

NFC Integration

In this post, you will learn how to design your pages and web applications to ensure optimal interaction with TheFlex Browser. We place special emphasis on utilizing NFC read/write capabilities, provided they are available on the end device. The library will be automatically injected by TheFlex Browser.

Enabling NFC Functionality

Here is an example code to enable NFC:

javascript
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
  nfc.enabled(
    function () {
      console.log("NFC enabled!");
    },
    function (error) {
      console.log("Error enabling NFC: " + JSON.stringify(error));
    }
  );
}

Reading NFC Data with ndef-reader

You can use the ndef-reader plugin to read data. Here is an example code:

javascript
document.addEventListener("ndefReady", function (e) {
  nfc.addNdefListener(
    function (nfcEvent) {
      var message = nfcEvent.tag.ndefMessage;
      for (var i = 0; i < message.length; i++) {
        console.log(
          "Record " + i + ": " + nfc.bytesToString(message[i].payload)
        );
      }
    },
    function () {
      console.log("NDEF Listener added successfully.");
    },
    function (error) {
      console.log("Error adding NDEF listener: " + JSON.stringify(error));
    }
  );
});

Writing NFC Data with ndef-reader

You can use the ndef-reader plugin to write data. Here is an example code:

javascript
function writeNfcTag(data) {
  const ndefMessage = [ndef.textRecord(data)];

  nfc.write(
    ndefMessage,
    function () {
      nfcData.innerText = "NFC tag written!";
    },
    function () {
      nfcData.innerText = "Error writing NFC tag!";
    }
  );
}

Here is an example of how you could write a webpage that reads/writes NFC tags:

html
<!DOCTYPE html>
<html>
  <head>
    <title>NFC Reader Example</title>
    <!-- Viewport settings for mobile devices -->
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      /* Styling for the Body */
      body {
        font-size: 20px; /* Adjust font size as needed */
        text-align: center;
      }

      /* Styling for the Button */
      button {
        font-size: 30px; /* Adjust button font size as needed */
        padding: 30px 40px; /* Adjust button size as needed */
        margin-bottom: 20px;
      }

      /* Styling for the link to app settings */
      #appSettingsLink {
        font-size: 20px;
      }

      /* Media Query for screen widths up to 300px */
      @media screen and (max-width: 300px) {
        body {
          font-size: 16px;
        }

        button {
          font-size: 20px;
          padding: 8px 16px;
        }

        #appSettingsLink {
          font-size: 14px;
        }
      }
    </style>
  </head>
  <body>
    <div class="container">
      <!-- Button to start NFC reading -->
      <button id="startNFC">Start NFC Reading</button>
      <!-- Display NFC tag ID -->
      <p id="nfcTagID"></p>
      <!-- Display NFC data -->
      <p id="nfcData"></p>
      <!-- Display NFC permission status -->
      <p id="nfcPermissionStatus"></p>
    </div>
    <script>
      // Function to initialize NFC functionality
      function init() {
        // Get elements in the HTML document
        const startNFCButton = document.getElementById("startNFC");
        const nfcDataParagraph = document.getElementById("nfcData");
        const nfcSerialParagraph = document.getElementById("nfcTagID");
        const nfcPermissionStatus = document.getElementById(
          "nfcPermissionStatus"
        );

        // Check if Cordova NFC API is available
        if (window.nfc) {
          // Function called when an NFC tag is detected
          var readingEvent = function (nfcEvent) {
            const tag = nfcEvent.tag;
            const ndefMessage = tag.ndefMessage;
            const serialNumber = nfc.bytesToHexString(tag.id);

            // Extract text from the NDEF message array
            if (ndefMessage && ndefMessage.length > 0) {
              const textRecord = ndefMessage[0];
              const message = ndef.textHelper.decodePayload(textRecord.payload);

              // Display NFC data and serial number (UID)
              nfcDataParagraph.textContent = `NFC Data: ${message}`;
            } else {
              nfcDataParagraph.textContent = "Empty NFC Tag!";
            }

            // Output the serial number to the console
            console.log(`NFC Tag detected: ${serialNumber}`);
            nfcSerialParagraph.textContent = `Serial Number (UID): ${serialNumber}`;
          };

          // Event listener for the button to start NFC reading
          startNFCButton.addEventListener("click", async () => {
            try {
              // Add an NFC tag listener to detect NFC tags
              nfc.addNdefListener(readingEvent);
              nfcDataParagraph.textContent = "NFC Reading started";
            } catch (error) {
              nfcDataParagraph.textContent =
                "Error starting NFC Reading: " + JSON.stringify(error);
            }
          });
        } else {
          // NFC support is not available
          console.error("Cordova NFC API is not supported on this device.");
          startNFCButton.disabled = true;
        }
      }

      // Event listener for the Cordova 'deviceready' event
      document.addEventListener("deviceready", init, false);
    </script>
  </body>
</html>