实现一键复制功能遇到的问题

实现一键复制功能遇到的问题

之前做了一个项目,是仿着chat-gpt写的,现在优化,添加了一键复制功能

在这里插入图片描述

function copyCode(codeToCopy) {
  navigator.clipboard
      .writeText(codeToCopy)
      .then(() => {
        ElMessage.success({
          message: "复制成功",
          type: "success",
        });
      })
      .catch((err) => {
        console.error("Failed to copy code: ", err);
      });
}

在本地运行是可以实现的,但是放到线上会报这样的!错误:
在这里插入图片描述

他说navigator.clipboardundefined,但是打印navigator是存在的,并且本地打印是存在navigator.clipboard的,经查询是浏览器禁用了非安全域的 navigator.clipboard 对象。

什么是安全域呢?

安全域包括本地访问与开启TLS安全认证的地址,如 https 协议的地址、127.0.0.1localhost

由于公司内部使用的是http协议,所以被浏览器禁用了,所以需要添加兼容性代码,在安全域下使用 navigator.clipboard 提升效率,非安全域退回到 document.execCommand('copy');

function copyCode(codeToCopy) {
  if (navigator.clipboard && window.isSecureContext) {  // 只能在安全域下使用 安全域包括本地访问与开启TLS安全认证的地址,如 https 协议的地址、127.0.0.1 或 localhost
    // navigator clipboard 向剪贴板写文本
    navigator.clipboard
      .writeText(codeToCopy)
      .then(() => {
        ElMessage.success({
          message: "复制成功",
          type: "success",
        });
      })
      .catch((err) => {
        console.error("Failed to copy code: ", err);
      });
  } else {
    // 创建text area
    let textArea = document.createElement("textarea");
    textArea.value = codeToCopy;
    // 使text area不在viewport,同时设置不可见
    textArea.style.position = "absolute";
    textArea.style.opacity = 0;
    textArea.style.left = "-999999px";
    textArea.style.top = "-999999px";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    
    return new Promise((res, rej) => {
      // 执行复制命令并移除文本框
      document.execCommand("copy") ? res() : rej();
      textArea.remove();
    }).then(() => {
        ElMessage.success({
          message: "复制成功",
          type: "success",
        });
      }).catch((err) => {
        console.error("Failed to copy code: ", err);
      });
  }
}

这样就实现啦,本地环境和正式环境都可以使用啦。

参考js 复制内容到剪贴板,解决navigator.clipboard Cannot read properties of undefined (reading ‘writeText‘)_cannot read properties of undefined (reading 'writ-CSDN博客

至于文章中说的微信浏览器打开不生效我这边测试是没有问题的,可能是那端优化了吧。

  • 26
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值