0

I have the following function to copy to the clipboard:

function getScreenShot(target){

var src = document.getElementById(target);


html2canvas(src).then(function(canvas) {
    //document.src.appendChild(canvas);
    canvas.toBlob(function(blob) {
        navigator.clipboard
        .write([
            new ClipboardItem(
            Object.defineProperty({}, blob.type, {
                value: blob,
                enumerable: true
            })
            )
        ])
        .then(function() {
            // do something
        });
    });
}

This works only on my localhost. When I run it on the server, the content doesn't get copied. I read that it has to do with security issue. How do I solve it?

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
AAA
  • 3
  • 2

1 Answers1

2

Here's a working version of the code. Note that images need to be on the same origin, or proxied.

const button = document.querySelector('button');

const createScreenshot = async (root) => {
  const canvas = await html2canvas(root);
  return new Promise((resolve) => {
    canvas.toBlob((blob) => {
      resolve(blob);
    });
  });
};

button.addEventListener('click', async () => {
  button.style.display = 'none';
  const blob = await createScreenshot(document.body);
  try {
    await navigator.clipboard.write([
      new ClipboardItem({
        [blob.type]: blob,
      }),
    ]);    
  } catch (err) {
    alert(`${err.name}: ${err.message}.`);
  } finally {
    button.style.display = '';
  }
});

You can see this code in action at https://sugary-hickory-pixie.glitch.me/.

DenverCoder9
  • 2,024
  • 11
  • 32