Chrome 网络系列 API 中的 "Must be handling a user gesture to show a permission request." 错误消息是什么?

What is "Must be handling a user gesture to show a permission request." errror message in Chrome Web Serial API?

在编程方面,我是一个真正的初学者。我的目的是通过 COM 端口 RS485 控制 API 集成在 Google Chrome 中的设备。我尝试重现以下教程:https://web.dev/serial/

控制台中出现以下错误信息:

“未捕获(承诺)DOMException:无法在 'Serial' 上执行 'requestPort':必须处理用户手势以显示权限请求。”

我该如何解决这个错误?

非常感谢您的帮助。

<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>examplepage</title>
    <script>
    async function caller() {
        // Prompt user to select any serial port.
    const port = await navigator.serial.requestPort();

    // Wait for the serial port to open.
    await port.open({ baudRate: 9600 });
    };
    
    if ("serial" in navigator) {
  alert("Your browser supports Web Serial API!");
  caller();
}
    else {alert("Your browser does not support Web Serial API, the latest version of Google Chrome is recommended!");};
    
    
    </script>
  </head>
  <body>
  
  </body>
</html>

错误消息 "Must be handling a user gesture to show a permission request." 意味着 navigator.serial.requestPort() 必须在响应用户手势(例如单击)的函数中调用。

在你的情况下,它会像下面这样。

<button>Request Serial Port</button>
<script>
  const button = document.querySelector('button');
  button.addEventListener('click', async function() {

    // Prompt user to select any serial port.
    const port = await navigator.serial.requestPort();

    // Wait for the serial port to open.
    await port.open({ baudRate: 9600 });
  });
</script>

以下代码有效。希望对有兴趣的朋友有所帮助。

<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>examplepage</title>
    <script>
    async function start() 
    {
            // Prompt user to select any serial port.
            const port = await navigator.serial.requestPort();

            // Wait for the serial port to open.
            await port.open({ baudRate: 9600 });
    }
    
    if ("serial" in navigator) {
  alert("Your browser supports Web Serial API!");
}
    else {alert("Your browser does not support Web Serial API, the latest version of Google Chrome is recommended!");};
    
    </script>
  </head>
  <body>
   <button onclick="start()">Click me</button> 
  </body>
</html>