We can interact with the system clipboard in two ways:
document.execCommand
document.execCommand("copy")
: copy the selected textdocument.execCommand("cut")
: cut the selected textdocument.execCommand("paste")
: paste the text in the clipboardThe problem with the execCommand
command is that we can only cut or copy the selected text. To overcome this, we can use the Clipboard API.
Using the Clipboard API, we can specify what information is to be placed in the system clipboard. Then, the Clipboard API performs operations asynchronously.
if (navigator.clipboard) {
// yes 😎
} else {
// nope 😢
}
navigator.clipboard.writeText("TEXT_TO_BE_COPIED")
.then(() => alert("Copied"))
navigator.clipboard.readText()
.then(() => alert("Copied"))
Don’t try the above code in the console. To use the Clipboard API, the document needs to be in a focused state. Otherwise, a DOMException
will be thrown.
If you need to use the Clipboard API in an iframe
, then set iframe
permissions to allow clipboard read/write operations.
<iframe
src="ifram_index.html"
allow="clipboard-read; clipboard-write"
>
</iframe>
The Clipboard API is not limited to copying and pasting text. It can also be used to copy and paste images.
To copy an image, we need an image blob and we need to write the blob to the clipboard. When clicking the image, we will copy the image to the clipboard.
Our image tag is:
// HTML;
<img id="img" src="imgfile.png" alt="image" title="click to copy" />
To copy an image to the clipboard, first convert the image to a blob, and then write it as a ClipboardItem
with the key as the image type and the value as the image blob.
//js
async function convertImageToBlob(ele) {
let canvas = document.createElement('canvas');
canvas.width = img.clientWidth;
canvas.height = img.clientHeight;
let context = canvas.getContext('2d');
// copy image to
context.drawImage(img, 0, 0);
// toBlob is async operation
let blob = await canvas.toBlob(blob => blob);
return blob;
}
let img = document.getElementById('img');
img.onclick = async () =>{
let blob = await convertImageToBlob(img);
try {
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob //storing in clipboard
})
]);
console.log('Image copied.');
} catch (err) {
console.error(err.name, err.message);
}
};
Let’s write code to read the image from the clipboard. We will read the available blob data using the read
method – it will return the clipboardItems
.
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);
console.log(URL.createObjectURL(blob)); //image as url
}
}
} catch (err) {
console.error(err.name, err.message);
}
}