前端实现复制功能,Uncaught TypeError: Cannot read property ‘writeText‘ of undefined

必须在安全域中运行

安全域指的是 HTTPS 或 localhost 环境。非安全域(如 http://example.com)下调用 navigator.clipboard.writeText() 会报错,例如:

bash 复制代码
Uncaught TypeError: Cannot read property 'writeText' of undefined

该 API 必须在用户触发的事件(如点击按钮)中调用,否则会被浏览器拦截。

为了在所有环境中实现复制功能,可以采用以下兼容方案:

  1. 优先使用现代 API 如果环境支持 navigator.clipboard,优先使用它以确保性能和安全性。

  2. 回退到传统方法 在非安全域或旧版浏览器中,可以使用 document.execCommand('copy') 实现文本复制。

实现代码:

bash 复制代码
function copyToClipboard(text) {
  // 检查 Clipboard API 是否可用
  if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
    return navigator.clipboard.writeText(text).then(() => {
      console.log("文本已成功复制到剪贴板(安全域)。");
    }).catch((err) => {
      console.error("复制失败:", err);
    });
  } else {
    // 非安全域或不支持 Clipboard API,使用 execCommand 兼容
    const textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.style.position = "fixed"; // 避免影响页面布局
    textarea.style.top = "-9999px";
    document.body.appendChild(textarea);
    textarea.select();
    try {
      const successful = document.execCommand("copy");
      console.log(successful ? "文本已成功复制到剪贴板(非安全域)。" : "复制失败");
    } catch (err) {
      console.error("复制失败:", err);
    }
    document.body.removeChild(textarea);
  }
}
相关推荐
zihan5182 天前
自己做软件日记9/21 得到了一个良好的文件结构框架
后端·flutter·前端框架·android studio
慧一居士2 天前
Nuxt 框架 插件plugins功能介绍和使用示例
前端框架
我命由我123453 天前
CSS - CSS 媒体查询 orientation
前端·javascript·css·html·css3·html5·js
GISer_Jing3 天前
Come on,工作总结
前端·ai·前端框架
Flynt5 天前
Shopify 弃 React Native 上了 HN 1272 分,我复现了它给 Agent 用的那套无头架构
react native·前端框架·agent
aichitang20245 天前
前端小skill
前端·人工智能·算法·ai·前端框架
光影少年5 天前
setImmediate 和 setTimeout(0) 的区别
android·前端·react.js·ios·前端框架
码云之上6 天前
Skill 里的脚本终于能跑了,星悟接 CubeSandbox 的纪实
前端·人工智能·前端框架
flash俊杰6 天前
Electron 自定义协议与视频流式加载:从 moov atom 到 Range 请求的工程化实践
electron·前端框架