Is it possible to copy an image to the clipboard in javascript? I know how to copy text, but can you copy images?
Is it a security limitation?
Use Clipboard API. There is an example on MDN specifically for images.
Note: today in 2021 ClipboardItem
can be enabled in Firefox by setting dom.events.asyncClipboard.clipboardItem
to true
. The rest major browsers support it. So, add some checks and inform a user how the feature can be turned on.
Here is an example:
async function writeClipImg() {
if (!('ClipboardItem' in window)) {
return alert(
"Your browser doesn't support copying images into the clipboard."
+ " If you use Firefox you can enable it"
+ " by setting dom.events.asyncClipboard.clipboardItem to true."
)
}
try {
const imgURL = document.getElementById('image').src
const data = await fetch(imgURL)
const blob = await data.blob()
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
])
console.log('Fetched image copied.')
} catch(err) {
console.error(err.name, err.message)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With