Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clipboard API #101

Open
dcharlie123 opened this issue Jan 12, 2024 · 0 comments
Open

Clipboard API #101

dcharlie123 opened this issue Jan 12, 2024 · 0 comments

Comments

@dcharlie123
Copy link
Owner

MDN

Clipboard 接口实现了 Clipboard API,如果用户授予了相应的权限,其就能提供系统剪贴板的读写访问能力。在 Web 应用程序中,Clipboard API 可用于实现剪切、复制和粘贴功能。
系统剪贴板暴露于全局属性 Navigator.clipboard 之中。

如果用户没有适时使用 Permissions API (en-US) 授予 "clipboard-read" 或 "clipboard-write" 权限,调用 Clipboard 对象的方法不会成功。

所有 Clipboard API 的方法都是异步的;它们返回一个 Promise 对象,在剪贴板访问完成后被兑现。如果剪贴板访问被拒绝,promise 也会被拒绝。

将数据写入剪切板

  • writeText
async function copyURL(){
  try {
     await navigator.clipboard.writeText(location.href);
     console.log("页面地址已经被拷贝到剪贴板中");
   } catch (err) {
     console.error("页面地址拷贝失败: ", err);
   }
}
  • write
async function setClipboard(text) {
  const type = "text/plain";
  const blob = new Blob([text], { type });
  const data = [new ClipboardItem({ [type]: blob })];
  await navigator.clipboard.write(data);
}

从读取剪切板数据

  • readText
async function readClipboardText(){
  const text = await navigator.readText()
  console.log("已读取剪贴板中的内容:", text);
}
  • read
async function pasteImage() {
  try {
    const clipboardContents = await navigator.clipboard.read();
    for (const item of clipboardContents) {
      if (!item.types.includes("image/png")) {
        throw new Error("Clipboard does not contain PNG image data.");
      }
      const blob = await item.getType("image/png");
      destinationImage.src = URL.createObjectURL(blob);
    }
  } catch (error) {
    log(error.message);
  }
}

请求剪贴板写权限

async function askWritePermission() {
  try {
    const { state } = await navigator.permissions.query({
      name: "clipboard-write",
    });
      return state === "granted";
  } catch (error) {
      return false;
  }
}

请求剪贴板读取权限

async function askReadPermission() {
  try {
    const { state } = await navigator.permissions.query({
      name: "clipboard-read",
    });
    return state === "granted";
  } catch (error) {
    return false;
  }
}

复制图片

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant