Skip to content

Commit 6eb8658

Browse files
committed
ClipboardItem data DOMString support usage document
1 parent 22637b1 commit 6eb8658

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# How to create ClipboardItem with DOMString
2+
**Last updated: October, 2024**
3+
4+
ClipboardItem constructor extends support to string data. ClipboardItem data can now be a blob, a string, or a promise that resolves to either a blob or a string.
5+
6+
The feature is available in Chromium-based browsers in M132 or later behind the flag `ClipboardItemWithDOMStringSupport`
7+
8+
1. Download Microsoft Edge ([Canary Channel](https://www.microsoftedgeinsider.com/en-us/download/canary)).
9+
2. Launch Edge with the command line flag `--enable-blink-features=ClipboardItemWithDOMStringSupport`.
10+
11+
This enhancement allows web authors to directly write text data to the clipboard as a string, without needing to create a blob.
12+
13+
```javascript
14+
const data = new ClipboardItem({
15+
"text/plain": "Hello World", // DOMString
16+
"text/html": Promise.resolve("<h1>Hello World</h1>") // Promise<DOMString>
17+
});
18+
```
19+
20+
If the flag is not enabled, a blob is required for the same.
21+
22+
```javascript
23+
const data = new ClipboardItem({
24+
"text/plain": new Blob(["Hello World"], {type: 'text/plain'}),
25+
"text/html": new Blob(["<h1>Hello World</h1>"], {type: 'text/html'})
26+
});
27+
```
28+
29+
Here is an example of writing a ClipboardItem with different supported data types.
30+
31+
## Example
32+
33+
```javascript
34+
async function writeToClipboard() {
35+
try {
36+
const plain_string = "Hello World";
37+
const html_string_promise = Promise.resolve("<h1>Hello World</h1>");
38+
const png_blob_promise = await fetch("/url/to/a/png/image").blob();
39+
40+
const data = new ClipboardItem({
41+
"text/plain": plain_string,
42+
"text/html": html_string_promise,
43+
"image/png": png_blob_promise
44+
});
45+
46+
await navigator.clipboard.write([data]);
47+
console.log('Data copied to clipboard');
48+
} catch (e) {
49+
console.error(e.message);
50+
}
51+
}
52+
```

0 commit comments

Comments
 (0)