在编程方面,我是一个真正的初学者。我的目的是通过 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>
错误信息"Must be handling a user gesture to show a permission request."
means 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)