vdegenne
vdegenne

Reputation: 13290

Can't simulate a paste event with image data

I want to automate a process and create a paste event programmatically with content from the clipboard (the clipboard permission is granted).

I am using chrome, here's my code

setTimeout(async function () {

    // create image url
    const item = (await navigator.clipboard.read())[0]
    const data = await item.getType('image/png')
    const url = URL.createObjectURL(data)
    
    // create paste event
    const pasteEvent = new ClipboardEvent('paste', {
        bubbles: true,
        cancelable: true,
        dataType: 'image/png',
        data: url
    })

    // dispatch Event
    document.dispatchEvent(pasteEvent)

}, 2000)

(the timeout here is used to focus on the document before the script run)

Unfortunately this code produces no error, but the paste event doesn't seem to do anything either, it should update the interface but it doesn't. What am I doing wrong?

Upvotes: 1

Views: 878

Answers (1)

vdegenne
vdegenne

Reputation: 13290

I finally made my code work using the DataTransfer API.
Thanks to anyone that helped me.

const clipboardItems = await navigator.clipboard.read()
const firstItem = clipboardItems[0]

try { // if there is an image
  const blob = await firstItem.getType('image/png')
  const file = new File([blob], 'image.png', {type: 'image/png'})

  const dataTransfer = new DataTransfer()
  dataTransfer.items.add(file)

  const pasteEvent = new ClipboardEvent('paste', {
    bubbles: true,
    cancelable: true,
    clipboardData: dataTransfer,
  })


  document.dispatchEvent(pasteEvent)
}
catch (e) {
    /* ignore */
}

Upvotes: 1

Related Questions