到目前為止,Async Clipboard API 僅支援一組有限的 MIME 類型,可從系統剪貼簿複製及貼上,具體來說是 text/plain
、text/html
和 image/png
。瀏覽器通常會清除這類內容,例如從 HTML 字串中移除內嵌的 script
元素或 javascript:
連結,或是防止 PNG 解壓縮炸彈攻擊。
不過,在某些情況下,您可能會希望在剪貼簿中支援未經過淨化的內容:
- 應用程式自行處理清理作業的情況。
- 複製的資料必須與貼上的資料完全相同的情況。
針對這類情況,Async Clipboard API 現已支援網頁自訂格式,可讓開發人員將任意資料寫入剪貼簿。
瀏覽器支援
從 Chromium 76 開始,系統支援非同步剪貼簿 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 的螢幕截圖所示。
示範
您可以試用這個示範,並查看原始碼,瞭解示範的運作方式。
特別銘謝
本文件由 Joe Medley 和 François Beaufort 審查。