当涉及到编程时,我是真正的初学者。我的意图是通过COM端口RS485控制一个集成在Google Chrome中的设备。我尝试重现以下教程:https://web.dev/serial/
控制台中会出现以下错误消息:
“未捕获(在promise中) 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>
发布于 2021-11-18 09:49:10
错误消息"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>
发布于 2021-11-19 09:16:46
下面的代码可以工作。我希望它能对其他感兴趣的人有所帮助。
<!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>
https://stackoverflow.com/questions/70007274
复制相似问题