Soy un verdadero principiante cuando se trata de programación. Mi intención es controlar un dispositivo con la API integrada en Google Chrome a través del puerto COM RS485. Intento reproducir el siguiente tutorial: https://web.dev/serial/
Aparece el siguiente mensaje de error en la consola:
"No detectada (en promesa) DOMException: no se pudo ejecutar 'requestPort' en 'Serial': debe estar manejando un gesto de usuario para mostrar una solicitud de permiso".
¿Cómo puedo solucionar este error?
Muchas gracias por su ayuda.
<!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>El mensaje de error "Must be handling a user gesture to show a permission request." significa que se debe llamar a navigator.serial.requestPort() dentro de una función que responde a un gesto del usuario, como un clic.
En su caso, sería algo como a continuación.
<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>El siguiente código funciona. Espero que ayude a otros que estén interesados.
<!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>