Async Clipboard API 適用的網路自訂格式

目前,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 " 開頭的剪貼簿項目。

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 這類的網路自訂格式並不是一般平台特定應用程式能夠理解的機制 (因為會預期 image/jpeg)。如果開發人員認為應用程式支援與使用者相關的網頁自訂格式,就會逐漸支援這類格式。在作業系統剪貼簿中,多種格式會以多種格式呈現以供使用,如下方 macOS 螢幕截圖所示。

macOS 剪貼簿預期者,顯示列出兩種網路自訂格式的自訂格式地圖。

操作示範

您可以試用下方的示範方法,並查看原始碼,瞭解示範的運作方式。

特別銘謝

本文由 Joe MedleyFrançois Beaufort 審查。Neon Tommy 的主頁橫幅,用於 CC BY-SA 2.0 授權。