From 4ca77d53847a3f7f4861bf4b41810daeb50c4009 Mon Sep 17 00:00:00 2001 From: Thomas Steiner Date: Mon, 27 Mar 2023 15:29:48 +0200 Subject: [PATCH] [Async clipboard article] Document the option to write a promise to the clipboard (#9816) * Update index.md Document promise option. Fixes https://github.com/GoogleChrome/web.dev/issues/9806. * Update src/site/content/en/blog/async-clipboard/index.md Co-authored-by: Rachel Andrew --------- Co-authored-by: Rachel Andrew --- .../content/en/blog/async-clipboard/index.md | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/site/content/en/blog/async-clipboard/index.md b/src/site/content/en/blog/async-clipboard/index.md index 52e30de3869..78d30a6d658 100644 --- a/src/site/content/en/blog/async-clipboard/index.md +++ b/src/site/content/en/blog/async-clipboard/index.md @@ -6,7 +6,7 @@ authors: - thomassteiner description: Async Clipboard API simplifies permissions-friendly copy and paste. date: 2020-07-31 -updated: 2022-11-04 +updated: 2023-03-27 tags: - blog - capabilities @@ -98,6 +98,7 @@ try { const blob = await data.blob(); await navigator.clipboard.write([ new ClipboardItem({ + // The key is determined dynamically based on the blob's type. [blob.type]: blob }) ]); @@ -107,6 +108,24 @@ try { } ``` +Alternatively, you can write a promise to the `ClipboardItem` object. +For this pattern, you need to know the MIME type of the data beforehand. + +```js +try { + const imgURL = '/images/generic/file.png'; + await navigator.clipboard.write([ + new ClipboardItem({ + // Set the key beforehand and write a promise as the value. + 'image/png': fetch(imgURL).then(response => response.blob()), + }) + ]); + console.log('Image copied.'); +} catch (err) { + console.error(err.name, err.message); +} +``` + {% Aside 'warning' %} Safari (WebKit) treats user activation differently than Chromium (Blink) (see [WebKit bug #222262](https://bugs.webkit.org/show_bug.cgi?id=222262)).