1

I'm currently working on a VSCode extension and would like to copy an image created using dom-to-image to my system clipboard when an event is fired.

Right now I can save image to PC using a file reader and serialization, but I would like to directly copy to clipboard instead.

Right now I'm using a click event to trigger a different few functions to serialize and save the image to PC, using the following method:

// Click event.
button.addEventListener('click', () => {
  const width = myDiv.offsetWidth * 2
  const height = myDiv.offsetHeight * 2
  const config = {
    width,
    height,
    style: {
      transform: 'scale(2)',
      'transform-origin': 'left top'
    }
  }
  domtoimage.toBlob(myDiv, config).then(blob => {
    serializeBlob(blob, serializedBlob => {
      shoot(serializedBlob)
    })
  })
})

// Serialization.
const serializeBlob = (blob, cb) => {
  const fileReader = new FileReader()

  fileReader.onload = () => {
    const bytes = new Uint8Array(fileReader.result)
    cb(Array.from(bytes).join(','))
  }
  function getBrightness(color) {
    const rgb = this.toRgb()
    return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000
  }
  fileReader.readAsArrayBuffer(blob)
}

// This function is passed the serialized data.
let lastUsedImageUri = vscode.Uri.file(path.resolve(homedir(), 'Desktop/image.png'))
  vscode.commands.registerCommand('shoot', serializedBlob => {
    vscode.window
      .showSaveDialog({
        defaultUri: lastUsedImageUri,
        filters: {
          Images: ['png']
        }
      })
      .then(uri => {
        if (uri) {
          writeSerializedBlobToFile(serializedBlob, uri.fsPath)
          lastUsedImageUri = uri
        }
      })
  })

Currently this saves directly to PC, prompted by a file dialog. However instead of this happening, I would like to copy the image gotten from domtoimage to my system clipboard instead, much like when I copy from my browser. I know that there is a copy event somewhere in the DOM that's used, but unsure what to do with that knowledge or how to make it work.

How can I accomplish saving the image to system clipboard?

Gama11
  • 31,714
  • 9
  • 78
  • 100
Rietty
  • 1,116
  • 9
  • 24
  • I don't think you can do that for security reasons. https://stackoverflow.com/questions/2321606/copy-image-to-clipboard-from-browser-in-javascript. Unless there is some kind of vscode specific way to do it. – Spinnaker Jan 29 '19 at 20:32

1 Answers1

1

I don't think you can do that for security reasons. Copy Image to Clipboard from Browser in Javascript?. Unless there is some kind of vscode specific way to do it

Spinnaker
  • 326
  • 1
  • 12