当前位置: 首页 > article >正文

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

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

Uncaught TypeError: Cannot read property 'writeText' of undefined

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

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

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

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

实现代码:

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);
  }
}


http://www.kler.cn/a/430480.html

相关文章:

  • Baklib推动数字化内容管理解决方案助力企业数字化转型
  • STM32 DMA+AD多通道
  • 圆上取点(例题)
  • 可视化大屏在石油方面的应用。
  • 读写锁: ReentrantReadWriteLock
  • C语言实现字符串排序:从代码到原理深度解析
  • CUDA编程 | 5.5 常量内存
  • Web游戏开发指南:在 Phaser.js 中读取和管理游戏手柄输入
  • 图的割点、割边(Tarjan算法)
  • 第4章:颜色和背景 --[CSS零基础入门]
  • 20241209给Ubuntu20.04系统的的交换分区增加为20GB的步骤
  • wsl2子系统ubuntu发行版位置迁移步骤
  • 【FAQ】HarmonyOS SDK 闭源开放能力 —Push Kit(7)
  • 漫画之家Spring Boot:漫画资源的个性化推荐
  • wlanapi.dll丢失怎么办?有没有什么靠谱的修复wlanapi.dll方法
  • Vulnhub---kioptirx5 超详细wp
  • qt http通信请求demo (get post )其余类似
  • Unity类银河战士恶魔城学习总结(P171 After image fx残影)
  • 基于ZYNQ-7000系列的FPGA学习笔记8——呼吸灯
  • 在 OAuth 2.0 中,refreshToken(刷新令牌)存在的意义
  • 新浪财经-数据中心-基金重仓GU-多页数据批量获取
  • HarmonyOS-中级(三)
  • BERT:用于语言理解的深度双向 Transformer 的预训练。
  • SQLAlchemy: Python中的强大数据库工具
  • 线段树模板
  • 微服务架构之旅-消息队列的应用