Chrome 120 页面复制按钮报 NotAllowedError 剪贴板怎么降级

内网运维后台用 http://10.20.3.41:8080 直接部署,复制 token 的按钮点下去没反应。Chrome 120 控制台报 Uncaught TypeError: Cannot read properties of undefined (reading 'writeText'),navigator.CLIpboard 在这台机器上是 undefined,线上 https 域名同一份代码却正常。

第一反应是包一层 try/catch 再提示复制失败,用户照样没法复制。翻文档才确认 Clipboard API 只在安全上下文暴露,http 加内网 IP 不算安全上下文,localhost 例外,所以本地开发一直没暴露这个问题。

换成 document.execCommand('copy') 配合临时 textarea,Chrome 120 能用。Safari 17 的要点是 textarea 必须在用户手势的同步栈里 select,中间隔一个 await 就会抛 NotAllowedError。也试过 navigator.permissions.query({name:'clipboard-write'}),http 下直接抛 TypeError,走不通。

最终写成两段分支:window.isSecureContext 为 true 且 navigator.clipboard 存在时走 writeText,否则走 execCommand;execCommand 返回 false 时把文本选中并提示手动复制。按钮的 click 回调里不做任何前置请求,token 在页面加载时就写进 data 属性。

还有一种情况是 iframe 嵌入,父页面没给 allow="clipboard-write",writeText 在 iframe 里同样被拒,异常名是 NotAllowedError。这个只能回父页面补 allow 属性。

确认口径:http 内网地址、https 线上、被 iframe 嵌入三种环境各点 10 次,剪贴板内容与页面 token 一致;被 iframe 包住时点下去给出提示不白屏;Chrome 120、Safari 17、微信内置浏览器各过一遍。

const btn = document.querySelector('#copy');
btn.addEventListener('click', async () => {
  const text = btn.dataset.text;
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
    } else {
      legacyCopy(text);
    }
    toast('已复制');
  } catch (e) {
    toast('请长按手动复制');
  }
});
function legacyCopy(text) {
  const ta = document.createElement('textarea');
  ta.value = text;
  ta.style.position = 'fixed';
  ta.style.opacity = '0';
  document.body.appendChild(ta);
  ta.select();
  document.execCommand('copy');
  ta.remove();
}

您可以还会对下面的文章感兴趣: