Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Image to Clipboard from Browser in Javascript?

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?

like image 747
Lance Avatar asked Feb 23 '10 20:02

Lance


1 Answers

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)
  }
}

like image 96
Lana Avatar answered Sep 28 '22 16:09

Lana