JS 剪切板 Clipboard API

Yukino 882 2022-05-12

背景: 最近遇到一个需求,需要展示一个键值的列表,并能点击复制按钮将Key值复制到系统的剪切板中(这个需求好像还挺常见的)

一、简介

Clipboard API提供系统剪切板的功能,其暴露于全局属性navigator.clipboard中,其包含writereadwriteTextreadText四个方法,这四个方法均返回一个Promise对象,具体可见https://developer.mozilla.org/zh-CN/docs/Web/API/Clipboard

二、使用示例

  1. writeText
<input id="copy-target" value="this is a string" />
<button onclick="copy()">Copy</button>

<script>
async function copy() {
  try {
    const copyTarget = document.getElementById("copy-target");
    const value = copyTarget.value;
    const clipboard = navigator && navigator.clipboard;
    if (clipboard) {
      await clipboard.write(value);
      console.log("copy success");
    }
  } catch (e) {
    console.log(e);
    console.log("copy failed");
  }
}
</script>
  1. readText
<button onclick="paste()">Paste</button>
<div id="clipboard-content"></div>

<script>
async function paste() {
  try {
    const clipboard = navigator && navigator.clipboard;
    if (clipboard) {
      const res = await clipboard.readText();
      const showContent = document.getElementById("clipboard-content");
      showContent.innerText = res;
      console.log("read success");
    }
  } catch (e) {
    console.log(e);
    console.log("read failed");
  }
}
</script>

tips

  1. 读取剪切板会弹窗申请权限
  2. 读取和写入都需要localhost或者HTTPS链接,HTTP链接下想试用这个API需要设置浏览器,在Chrome中可在chrome://flags -> Insecure origins treated as secure中添加忽略安全校验的Host