前端实现复制功能,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);
  }
}
相关推荐
hoLzwEge13 小时前
node-linker VS shamefully-hoist
前端·前端框架
星栈18 小时前
SPA 写累了?试试 LiveView:服务端管状态,前端不写 JS
前端·前端框架·elixir
星栈2 天前
写 Dioxus Demo 不难,难的是把它写成项目
前端·rust·前端框架
用户2204603958683 天前
HBuilder + uniapp 项目切换到VsCode
前端框架
薛定喵的谔3 天前
我开源了一个精致的 Next.js 博客模板:Skyplume
前端·前端框架·next.js
星栈4 天前
我用 Rust + Dioxus 做了个全栈跨平台笔记应用:再把新建、编辑和交付补上
前端·rust·前端框架
donecoding4 天前
3 条命令搞定闭环 Monorepo:Lerna 版本管理 + 拓扑构建 + 自定义分发
前端·前端框架·node.js
星栈5 天前
我用 Rust + Dioxus 做了个全栈跨平台笔记应用:第一版先把列表和详情跑通
前端·rust·前端框架
下家5 天前
我放弃了 Vue/React,选择自研框架
前端·前端框架
hoLzwEge6 天前
pnpm-lock.yaml
前端框架