これまで、Async Clipboard API は、システム クリップボードとの間でコピーと貼り付けを行う MIME タイプを限定的にサポートしていました。具体的には、text/plain
、text/html
、image/png
です。通常、ブラウザはこれをサニタイズします。たとえば、HTML 文字列から埋め込まれた script
要素や javascript:
リンクを削除したり、PNG の圧縮ボム攻撃を防いだりします。
ただし、クリップボードに未処理のコンテンツをサポートすることが望ましい場合もあります。
- アプリケーションがサニタイズ自体を処理する状況。
- コピーしたデータが貼り付けたデータと完全に一致することが重要な状況。
このような場合、Async Clipboard API は、デベロッパーが任意のデータをクリップボードに書き込むことができるウェブ カスタム形式をサポートするようになりました。
ブラウザ サポート
画像をサポートする Async Clipboard API 自体は、Chromium 76 でサポートされています。Async Clipboard API のウェブ カスタム形式は、バージョン 104 以降のデスクトップ版とモバイル版の Chromium でサポートされています。
ウェブのカスタム形式をクリップボードに書き込む
ウェブ カスタム形式をクリップボードに書き込むことは、クリーンな形式を書き込むとほぼ同じですが、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 が確認しました。