โ†

Javascript: get an image from the browser clipboard

First get the permission from (Firefox doesn't implement this currently...) to read from the browser clipboard (i.e. things copied from the desktop won't be pasted).

var permission = await navigator.permissions.query({ name: 'clipboard-read' })

Then check it

if (permission.state === 'denied') {
  alert('Not allowed to read clipboard.')
  return null
}

Then read it

var clipboardContents = await navigator.clipboard.read()

Then look at all the types that are associated with this item, looking for something that contains image, and return it if it's an image with its type, otherwise look at the rest of the items.

 for (const item of clipboardContents) {
   var types = [...item.types].filter(i => i.includes("image"))
   if (types.length != 0) return [item, types[0]]
 }
 alert("No image to paste")
 return null

In full

// returns [image, type]
// returns null on no permission or no image data
async function get_image_type() {
  var permission = await navigator.permissions.query({ name: 'clipboard-read' })
  if (permission.state === 'denied') {
    alert('Not allowed to read clipboard.')
    return null
  }
  const clipboardContents = await navigator.clipboard.read()
  for (const item of clipboardContents) {
    var types = [...item.types].filter(i => i.includes("image"))
    if (types.length == 0) return [item, types[0]]
  }
  console.log("No image data")
  return null
}

With the image you can use it as a blob and use it with item.getType(type) and FileReader().readAsDataURL(), i.e.

var blob = await item.getType(type)
var reader = new FileReader()
reader.onload = ev => {
  ev.target.result // the blob url
}
reader.readAsDataURL(blob)
javascript
I've removed disqus comments
Instead, press this
to express thanks
So far, 0 people have pressed the octopus
I'm no longer visiting the Reddit tabloid. It's anger-inducing and divisive
I'm writing small thoughts here