Search code examples
javascripthtmlgoogle-chromeserial-portmodbus

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


I am a real beginner when it comes to programming. It is my intention to control a device with the API integrated in Google Chrome via the COM port RS485. I try to reproduce the following tutorial: https://web.dev/serial/

The following error message appears in the console:

"Uncaught (in promise) DOMException: Failed to execute 'requestPort' on 'Serial': Must be handling a user gesture to show a permission request."

How can I fix this error?

Thank you very much for your help.

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


Solution

  • The error message "Must be handling a user gesture to show a permission request." means navigator.serial.requestPort() must be called inside a function that responds to a user gesture such as a click.

    In your case, it would be something like below.

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