ClipboardItem
Baseline 2024
Newly available
Since June 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
The ClipboardItem
interface of the Clipboard API represents a single item format, used when reading or writing clipboard data using clipboard.read()
and clipboard.write()
respectively.
The benefit of having the ClipboardItem
interface to represent data, is that it enables developers to cope with the varying scope of file types and data.
Note: To work with text see the Clipboard.readText()
and Clipboard.writeText()
methods of the Clipboard
interface.
Constructor
ClipboardItem()
-
Creates a new
ClipboardItem
object, with the MIME type as the key andBlob
as the value.
Instance properties
This interface provides the following properties.
types
Read only-
Returns an
Array
of MIME types available within theClipboardItem
. presentationStyle
Read only-
Returns one of the following:
"unspecified"
,"inline"
or"attachment"
.
Static methods
This interface defines the following methods.
ClipboardItem.supports()
-
Checks whether a given MIME type is supported by the clipboard. This enables a website to detect whether a MIME type is supported by the clipboard before attempting to write data.
Instance methods
Examples
Writing to the clipboard
Here we use supports()
to check whether the image/svg+xml
MIME data type is supported.
If it is, we fetch the image with the "Fetch API", and then read it into a Blob
, which we can use to create a ClipboardItem
that is written to the clipboard.
async function writeClipImg() {
try {
if (ClipboardItem.supports("image/svg+xml")) {
const imgURL = "/my-image.svg";
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("SVG images are not supported by the clipboard.");
}
} catch (err) {
console.error(err.name, err.message);
}
}
Reading from the clipboard
Here we're returning all items on the clipboard via the clipboard.read()
method.
Then utilizing the ClipboardItem.types
property to set the getType()
argument and return the corresponding blob object.
async function getClipboardContents() {
try {
const clipboardItems = await navigator.clipboard.read();
for (const clipboardItem of clipboardItems) {
for (const type of clipboardItem.types) {
const blob = await clipboardItem.getType(type);
// we can now use blob here
}
}
} catch (err) {
console.error(err.name, err.message);
}
}
Specifications
Specification |
---|
Clipboard API and events # clipboarditem |
Browser compatibility
BCD tables only load in the browser