复制粘贴 navigator.clipboard 在不同网络环境无法使用是咋回事?

1,859 阅读1分钟

原因: 因为 navigator.clipboard 只能在安全网络环境中才能使用,也就是,安全域包括本地访问与开启TLS安全认证的地址,如 https 协议的地址、127.0.0.1 或 localhos才能正常使用,那在非安全环境,比如HTTP 协议的地址,用服务器IP访问的模拟环境又该如何使用呢?

解决方案

<template>
    <div>
        <span>{{ text }}</span>
        <el-button type="text" @click="handleCopy(text)">复制</el-button>
    </div
</template>
<script>
export default {
  data() {
      text: "文本文本文本文本"
  },
  methods: {
    handleCopy(content) {
      // navigator clipboard 需要https等安全上下文
      if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        navigator.clipboard.writeText(content);
        this.$message({
          message: "复制成功",
          type: "success"
        });
      } else {
        // 创建text area
        let textArea = document.createElement("textarea");
        textArea.value = content;
        // 使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();
          this.$message({
            message: "复制成功",
            type: "success"
          });
        });
      }
    }
  }
}
</script>

参考:blog.csdn.net/u012586326/… www.jianshu.com/p/88d3f45af…