You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome Web Serial API出现'Must be handling a user gesture to show a permission request.'错误如何解决?

Web Serial API 权限报错修复方案

错误原因

  • Chrome 对 Web Serial API 有强制安全策略约束:navigator.serial.requestPort() 接口需要弹出用户授权弹窗,必须在用户主动触发的交互事件(如按钮点击、键盘输入等)中调用,不允许页面加载完成后自动触发,防止恶意页面未经用户同意私自调用设备权限。
  • 你的代码在页面加载完成后直接执行caller()触发串口请求,此时不存在用户交互手势,因此被浏览器拦截抛出对应异常。

修复方法

在页面中添加可交互元素(例如按钮),将串口请求逻辑绑定到用户点击事件上即可,修复后的完整代码如下:

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Serial 控制示例</title>
    <script>
    async function caller() {
        try {
            // 提示用户选择串口
            const port = await navigator.serial.requestPort();
            // 等待串口打开完成
            await port.open({ baudRate: 9600 });
            alert("串口打开成功!");
            // 后续串口读写逻辑可在此处补充
        } catch (e) {
            alert("串口操作失败:" + e.message);
        }
    };
    
    window.onload = function() {
        if ("serial" in navigator) {
            // 绑定串口请求逻辑到按钮点击事件
            document.getElementById("openSerialBtn").addEventListener("click", caller);
            alert("您的浏览器支持 Web Serial API!请点击按钮选择串口");
        } else {
            alert("您的浏览器不支持 Web Serial API,建议使用最新版谷歌浏览器!");
        }
    }
    </script>
  </head>
  <body>
    <button id="openSerialBtn" style="padding: 10px 20px; font-size: 16px;">打开串口连接</button>
  </body>
</html>

额外注意事项

  • 页面必须通过 HTTPS 或者 localhost 本地地址访问,否则navigator.serial接口会被浏览器禁用
  • 串口打开后如果需要收发数据,可以调用port.readable、port.writable接口实现读写逻辑

内容的提问来源于stack exchange,提问作者5-HT2A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:45:05