Clipboard API
The ClipboardItem() constructor creates a new ClipboardItem object, which represents data to be stored or retrieved via the Clipboard API clipboard.write() and clipboard.read() methods, respectively.
[!NOTE] The
read()andwrite()methods can be used to work with text strings and arbitrary data items represented by Blob instances. However, if you are solely working with text, it is more convenient to use the Clipboard.readText() and Clipboard.writeText() methods.
[!NOTE] Image format support varies by browser. See the browser compatibility table for the
Clipboardinterface.
Syntax
new ClipboardItem(data)
new ClipboardItem(data, options)
Parameters
data-
: An Object with one or more properties, each representing a different format of the same clipboard entry. The key of each property is a MIME type, such as
"text/plain"or"text/html", and its value is the data for that format.Each value can be represented as one of the following:
- a Blob
- a string
- a Promise that resolves to either a
Blobor string.
-
options- : An object with the following properties:
presentationStyle-
: One of the three strings:
unspecified,inlineorattachment. The default isunspecified.inlinesignifies to apps that receive the paste that theClipboardItemshould be inserted inline at the point of paste.attachmentsignifies to apps that receive the paste that theClipboardItemshould be added as an attachment.unspecifieddoesn't signify any information to apps that receive the paste.
-
- : An object with the following properties:
Examples
The following example requests a PNG image using Window/fetch and uses it, via the Response.blob() method, to create a new ClipboardItem. This item is then written to the clipboard, using the Clipboard.write() method.
For an example that writes and reads back several MIME-type representations in one ClipboardItem, see Reading multiple formats from the clipboard.
[!NOTE] Clipboard.write() takes an array of
ClipboardItemobjects, but if the underlying OS doesn't support writing multiple items, only the first item will be written. Some browser versions throw an exception if more than one item is passed in the array (see Browser compatibility inClipboard.write()).
async function writeClipImg() {
try {
if (ClipboardItem.supports("image/png")) {
const imgURL = "/my-image.png";
const data = await fetch(imgURL);
const blob = await data.blob();
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob,
}),
]);
console.log("Fetched image copied.");
} else {
console.log("image png is not supported");
}
} catch (err) {
console.error(err.name, err.message);
}
}
Specifications
Browser compatibility
See also
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
