發布日期:2025 年 4 月 30 日
慶祝:這項網頁功能現已支援所有三個主要瀏覽器引擎,並自 2025 年 3 月 30 日起成為新基準功能。
Async Clipboard API 讓剪貼簿的使用方式比以往更簡單。您現在可以呼叫 navigator.clipboard.writeText()
來處理純文字內容,也可以呼叫 navigator.clipboard.write()
來處理「幾乎」所有其他內容,例如圖片、文字內容或 HTML。
不過,我們目前還沒有量化「幾乎」這個詞。舉例來說,您必須先嘗試使用 API,才能知道該 API 是否支援 SVG,如果不支援,則會擷取擲回的例外狀況。這並不是判斷支援情況的最佳方式,因此我們指定了靜態 ClipboardItem.supports()
函式。
這項功能現在已達到 Baseline Newly available 狀態,這表示使用剪貼簿的效能更佳。如要瞭解瀏覽器是否支援特定格式,請將您感興趣的格式 MIME 類型傳遞至函式。
const format = 'image/svg+xml';
const supportsFormat = ClipboardItem.supports(format);
console.log(`This browser does${supportsFormat ? '' : ' not'} support ${format}.`);
// "This browser does support image/svg+xml."
之前我寫了「幾乎」所有內容,這裡就是最有趣的地方。網頁自訂格式可讓您使用瀏覽器不支援的原生格式。舉例來說,根據預設,瀏覽器不支援 AVIF 圖片。
const format = 'image/avif';
const supportsFormat = ClipboardItem.supports(format);
console.log(`This browser does${supportsFormat ? '' : ' not'} support ${format}.`);
// "This browser does not support image/avif."
不過,只要接收端也知道如何處理網路自訂格式,您就可以使用 AVIF 圖片,並自由複製及貼上這些圖片。
const format = 'web image/avif';
const supportsFormat = ClipboardItem.supports(format);
console.log(`This browser does${supportsFormat ? '' : ' not'} support ${format}.`);
// "This browser does support web image/avif."
有了 ClipboardItem.supports()
函式,您現在可以正確偵測剪貼簿支援的網頁自訂格式,並確保這項功能運作正常。
if (ClipboardItem.supports('web image/avif')) {
// Fetch remote AVIF image and obtain its blob representation.
const blob = await fetch('image.avif').then((response) => response.blob());
try {
// Write the image data to the clipboard, prepending the blob's actual
// type (`"image/avif"` with the string `"web "`, so it becomes
// `"web image/avif"`.
const clipboardItem = new ClipboardItem({
'web image/avif': blob,
});
await navigator.clipboard.write([clipboardItem]);
} catch (err) {
console.error(err.name, err.message);
}
}
ClipboardItem.supports()
函式現已納入 Baseline,網頁開發人員可可靠地偵測剪貼簿是否支援各種 MIME 類型,包括網頁自訂格式。這項強化功能可讓剪貼簿的運作更穩健、更可預測,進而改善所有瀏覽器的使用者體驗。