The Clipboard
method write()
writes arbitrary data, such as images, to the clipboard. This can be used to implement cut and copy functionality.
The "clipboard-write"
permission of the Permissions API, is granted automatically to pages when they are in the active tab.
Note: For parity with Google Chrome, Firefox only allows this function to work with text, HTML, and PNG data.
A Promise
which is resolved when the data has been written to the clipboard. The promise is rejected if the clipboard is unable to complete the clipboard access.
This example function replaces the current contents of the clipboard with a specified string.
function setClipboard(text) {
const type = "text/plain";
const blob = new Blob([text], { type });
const data = [new ClipboardItem({ [type]: blob })];
navigator.clipboard.write(data).then(
() => {
},
() => {
},
);
}
The code begins by creating a new a Blob
object. This object is required to construct a ClipboardItem
object which is sent to the clipboard. The Blob
constructor takes in the content we want to copy and its type. This Blob
object can be derived from many sources; for example, a canvas.
Next, we create a new ClipboardItem
object into which the blob will be placed for sending to the clipboard. The key of the object passed to the ClipboardItem
constructor indicates the content type, the value indicates the content. Then write()
is called, specifying both a fulfillment function and an error function.
function copyCanvasContentsToClipboard(canvas, onDone, onError) {
canvas.toBlob((blob) => {
let data = [new ClipboardItem({ [blob.type]: blob })];
navigator.clipboard.write(data).then(
() => {
onDone();
},
(err) => {
onError(err);
},
);
});
}
Note: You can only pass in one clipboard item at a time.