前端实现复制功能,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);
  }
}
相关推荐
看浪的路人7 小时前
第2讲:ReAct 模式从零实现——不用框架,手写一个 Agent 内核
前端·react.js·前端框架
Amos_Web17 小时前
Rspack 源码解析(二十四):AssetPlugin 如何让图片同时是「URL 字符串」和「真实文件」
前端·rust·前端框架
Java后端的Ai之路1 天前
08_React组件API
前端·react.js·前端框架
Java后端的Ai之路2 天前
09-React组件生命周期
前端·react.js·前端框架
Java后端的Ai之路2 天前
06-React-Props
前端·react.js·前端框架
总要学点什么2 天前
第55篇:空间分析-剖面分析——红线走大圆,剖面却按经纬直线采样
前端框架·gis·webgl·cesium·空间分析
Amos_Web3 天前
Rspack 源码解析(二十一):Cacheable 与 Storage 如何持久化编译结果
前端·rust·前端框架
Amos_Web3 天前
Rspack 源码解析(二十二):ExternalsPlugin 如何在 Factorize 阶段换掉整个模块
前端·rust·前端框架
总要学点什么3 天前
第51篇:数据分析-热力图——笔刷画的是圆,落到地上却成了椭圆
3d·数据挖掘·数据分析·前端框架·gis·webgl·cesium
Amos_Web4 天前
Rspack 源码解析(二十):Typed Hook 系统如何靠宏生成
前端·rust·前端框架