Async Clipboard API 的 Web 自定义格式

到目前为止,Async Clipboard API 支持从系统剪贴板复制和粘贴一组有限的 MIME 类型,具体来说是:text/plaintext/htmlimage/png。浏览器通常会执行清理操作,例如从 HTML 字符串中移除嵌入的 script 元素或 javascript: 链接,或者防止 PNG 解压缩炸弹攻击。

但在某些情况下,最好支持剪贴板上未经过清理的内容:

  • 应用处理清理本身的情况。
  • 在此类情况下,复制的数据必须与粘贴的数据完全相同。

对于此类情况,Async Clipboard API 现在支持网页自定义格式,让开发者能够将任意数据写入剪贴板。

浏览器支持

从 Chromium 76 开始,支持 Async Clipboard API 本身,支持图片。从 104 版开始,桌面设备和移动版 Chromium 均支持 Async Clipboard API 的网页自定义格式。

将网页自定义格式写入剪贴板

将网络自定义格式写入剪贴板与编写经过净化的格式几乎完全相同,但要求在 blob 的 MIME 类型前面加上字符串 "web "(包括尾随空格)。

// Fetch remote JPEG and GIF images and obtain their blob representations.
const [jpegBlob, gifBlob] = await Promise.all([
  fetch('image.jpg').then((response) => response.blob()),
  fetch('image.gif').then((response) => response.blob()),
]);

try {
  // Write the image data to the clipboard, prepending the blobs' actual
  // types (`"image/jpeg"` and "image/gif") with the string `"web "`, so
  // they become `"web image/jpeg"` and `"web image/gif"` respectively.
  // The code elegantly makes use of computed property names:
  // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names.
  const clipboardItem = new ClipboardItem({
    [`web ${jpegBlob.type}`]: jpegBlob,
    [`web ${gifBlob.type}`]: gifBlob,
  });
  await navigator.clipboard.write([clipboardItem]);
} catch (err) {
  console.error(err.name, err.message);
}

从剪贴板读取网页自定义格式

与写入一样,从剪贴板读取 Web 自定义格式与读取已清理后的格式几乎完全相同。唯一的区别是,应用现在需要查找类型以 "web " 开头的剪贴板项。

try {
  // Iterate over all clipboard items.
  const clipboardItems = await navigator.clipboard.read();
  for (const clipboardItem of clipboardItems) {
    for (const type of clipboardItem.types) {
      // Discard any types that are not web custom formats.
      if (!type.startsWith('web ')) {
        continue;
      }
      const blob = await clipboardItem.getType(type);
      // Sanitize the blob if you need to, then process it in your app.
    }
  }
} catch (err) {
  console.error(err.name, err.message);
}

与平台专用应用实现互操作性

web image/jpeg 这样的 Web 自定义格式不是典型的平台应用能够理解的格式(因为它们需要 image/jpeg)。随着时间的推移,如果相关应用的开发者认为支持 Web 自定义格式与用户相关,他们应该会添加对此类格式的支持,作为选择启用格式。在操作系统剪贴板上,各种格式以多种格式随时可供使用,如下方针对 macOS 的屏幕截图所示。

macOS 上的剪贴板预期器,显示了一个自定义格式地图,其中列出了两种网页自定义格式。

演示

您可以试用下面的演示版,并查看源代码,了解演示版的工作原理。

致谢

本文由 Joe MedleyFrançois Beaufort 审核。主打图片由 Neon Tommy 提供,根据 CC BY-SA 2.0 许可使用。