0

I am trying to explore on web NFC and found a simple sample (https://googlechrome.github.io/samples/web-nfc/). So, I copy the sample code to test it on local:

<html><head>
    <title>Web NFC Sample</title>
    <script>
      // Add a global error event listener early on in the page load, to help ensure that browsers
      // which don't support specific functionality still end up displaying a meaningful message.
      window.addEventListener('error', function(error) {
        if (ChromeSamples && ChromeSamples.setStatus) {
          console.error(error);
          ChromeSamples.setStatus(error.message + ' (Your browser may not support this feature.)');
          error.preventDefault();
        }
      });
    </script>
    
    
    <link rel="stylesheet" href="Web%20NFC%20Sample_files/main.css">
    
    
  </head>

  <body>
<button id="scanButton">Scan</button>
<button id="writeButton">Write</button>

<script>
  var ChromeSamples = {
    log: function() {
      var line = Array.prototype.slice.call(arguments).map(function(argument) {
        return typeof argument === 'string' ? argument : JSON.stringify(argument);
      }).join(' ');

      document.querySelector('#log').textContent += line + '\n';
    },

    clearLog: function() {
      document.querySelector('#log').textContent = '';
    },

    setStatus: function(status) {
      document.querySelector('#status').textContent = status;
    },

    setContent: function(newContent) {
      var content = document.querySelector('#content');
      while(content.hasChildNodes()) {
        content.removeChild(content.lastChild);
      }
      content.appendChild(newContent);
    }
  };
</script>

<h3>Live Output</h3>
<div id="output" class="output">
  <div id="content"></div>
  <div id="status">Web NFC is not available.
Please make sure the "Experimental Web Platform features" flag is enabled on Android.</div>
  <pre id="log"></pre>
</div>


<script>
  if (/Chrome\/(\d+\.\d+.\d+.\d+)/.test(navigator.userAgent)){
    // Let's log a warning if the sample is not supposed to execute on this
    // version of Chrome.
    if (89 > parseInt(RegExp.$1)) {
      ChromeSamples.setStatus('Warning! Keep in mind this sample has been tested with Chrome ' + 89 + '.');
    }
  }
</script>



<script>
log = ChromeSamples.log;

if (!("NDEFReader" in window))
  ChromeSamples.setStatus(
    "Web NFC is not available.\n" +
      'Please make sure the "Experimental Web Platform features" flag is enabled on Android.'
  );
</script>


  
    
      <script>scanButton.addEventListener("click", async () => {
  log("User clicked scan button");

  try {
    const ndef = new NDEFReader();
    await ndef.scan();
    log("> Scan started");

    ndef.addEventListener("readingerror", () => {
      log("Argh! Cannot read data from the NFC tag. Try another one?");
    });

    ndef.addEventListener("reading", ({ message, serialNumber }) => {
      log(`> Serial Number: ${serialNumber}`);
      log(`> Records: (${message.records.length})`);
    });
  } catch (error) {
    log("Argh! " + error);
  }
});

writeButton.addEventListener("click", async () => {
  log("User clicked write button");

  try {
    const ndef = new NDEFReader();
    await ndef.write("Hello world!");
    log("> Message written");
  } catch (error) {
    log("Argh! " + error);
  }
});
</script>
  

</body></html>

But when I run it, it shows Web NFC is not available. Please make sure the "Experimental Web Platform features" flag is enabled on Android. on the message. When I click on "scan" button, it shows Argh! ReferenceError: NDEFReader is not defined.

May I know why the sample code work well when it is on https://googlechrome.github.io but can't work when I have it on my local PC? Thank you.

1 Answer 1

1

As documented in https://web.dev/nfc/#security-and-permissions, Web NFC is only available in secure browsing contexts. It means you either have to serve your webpage over https:// or localhost such as http://127.0.0.1 or http://localhost.

  • If you have installed npm, you can use npx http-serve.
  • If you have installed Python 2, use python -m SimpleHTTPServer
  • If you have installed Python 3, use python -m http.server

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.