ClipboardItem:getType() 方法

Baseline 2024
新推出

自 2024 年 6 月起,此功能已在最新的裝置和瀏覽器版本中可用。此功能可能不適用於較舊的裝置或瀏覽器。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

getType()ClipboardItem 介面的一個方法。它返回一個 Promise,該 Promise 在解決時會提供請求的 MIME 型別對應的 Blob 物件,如果未找到該 MIME 型別則會返回錯誤。

語法

js
getType(type)

引數

type

一個有效的 MIME 型別

返回值

一個 Promise,它在解決時會提供一個 Blob 物件。

異常

NotFoundError DOMException

type 與已知的 MIME 型別不匹配。

TypeError

未指定引數,或 type 不屬於 ClipboardItem 的型別。

示例

在以下示例中,我們使用 clipboard.read() 方法返回剪貼簿上的所有專案。對於每個專案,我們將 ClipboardItem.types 屬性傳遞給 getType() 方法,該方法返回相應的 Blob 物件。

js
async function getClipboardContents() {
  try {
    const clipboardItems = await navigator.clipboard.read();

    for (const clipboardItem of clipboardItems) {
      for (const type of clipboardItem.types) {
        const blob = await clipboardItem.getType(type);
        // we can now use blob here
      }
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}

規範

規範
Clipboard API 和事件
# dom-clipboarditem-gettype

瀏覽器相容性

另見