实现复制粘贴功能

300 阅读1分钟

点击复制按钮,实现复制,粘贴功能,使用navigator.clipboard.writeText方法

另外,测试环境下可以正常复制 ,但放到线上会报错:找不到 .writeText, 像http不支持该功能。

经查找资料发现是浏览器禁用了非安全域的 navigator.clipboard 对象,哪些地址是安全的呢?

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

image.png

// text 复制的内容 
const copyToClipboard = (text) => {
  if (navigator.clipboard) {
    navigator.clipboard
      .writeText(text)
      .then(() => {
        ElMessage({
          type: "success",
          message: "copy success",
        });
      })
      .catch((error) => {
        ElMessage({
          type: "error",
          message: "copy error",
        });
      });
  } else {
    // 创建text area
    let textArea = document.createElement("textarea");
    textArea.value = text;
    // 使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();
    });
  }
};