【问题标题】:What is "Must be handling a user gesture to show a permission request." errror message in Chrome Web Serial API?什么是“必须处理用户手势才能显示权限请求”。 Chrome Web Serial API 中的错误消息?
【发布时间】:2021-12-28 14:25:05
【问题描述】:
在编程方面,我是一个真正的初学者。我打算通过 COM 端口 RS485 控制具有集成在 Google Chrome 中的 API 的设备。我尝试重现以下教程: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>
【问题讨论】:
标签:
javascript
html
google-chrome
serial-port
modbus
【解决方案1】:
错误消息"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>
【解决方案2】:
以下代码有效。希望对有兴趣的朋友有所帮助。
<!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>