0

我正在尝试在网络 NFC 上进行探索,并找到了一个简单的示例(https://googlechrome.github.io/samples/web-nfc/)。所以,我复制示例代码在本地进行测试:

<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>

但是当我运行它时,它会显示Web NFC is not available. Please make sure the "Experimental Web Platform features" flag is enabled on Android.在消息上。当我点击“扫描”按钮时,它显示Argh! ReferenceError: NDEFReader is not defined.

我可以知道为什么示例代码在打开时运行良好,https://googlechrome.github.io但在我的本地 PC 上运行时无法运行?谢谢你。

4

1 回答 1

1

https://web.dev/nfc/#security-and-permissions中所述,Web NFC 仅在安全浏览上下文中可用。https://这意味着您必须通过或本地主机(例如http://127.0.0.1或)提供您的网页http://localhost

  • 如果你已经安装了npm,你可以使用npx http-serve.
  • 如果您已安装 Python 2,请使用python -m SimpleHTTPServer
  • 如果您已安装 Python 3,请使用python -m http.server
于 2021-12-01T07:25:44.987 回答