Angular/Typescript copying an image(blob) to clipboard programmatically
Asked Answered
P

1

6

In an Angular 7 application, we're using html-to-image to render an HTML block into a png, we save that image using file-saver.

    htmlToImage.toBlob(element).then(function (blob) {
      saveAs(blob, `image.png`);
    });

This is working well, but the business requirement is to put that image into the clipboard so it can be pasted in another tool (Word, Excel...).

Have done some googling about the Async Clipboard API, but it seems the API isn't supported by all the browser's yet.

Is there any workaround for this to work without relying on the Clipboard API?

Pancho answered 22/11, 2019 at 16:5 Comment(3)
As I am seeing why don't use a different library in first place such as html2canvas.hertzen.com , that would be a pure client side solution. The other way would be to pass to server side and do it there but I do not recommend this solutionCellulous
Maybe this cal help you out: #400712 comment by Chase SeibertFocalize
@Cellulous HTML2Canvas does not copy to the clipboard, only creates the picturePera
D
3

Your best bet is indeed the Async Clipboard API, which has growing browser support now. The article has an example that shows exactly how to use it:

try {
  const imgURL = '/images/generic/file.png';
  const data = await fetch(imgURL);
  const blob = await data.blob();
  await navigator.clipboard.write([
    new ClipboardItem({
      [blob.type]: blob
    })
  ]);
  console.log('Image copied.');
} catch (err) {
  console.error(err.name, err.message);
}
Demb answered 16/12, 2020 at 14:27 Comment(4)
seem do not work in FirefoxPera
Yes, Firefox is unfortunately really behind there. They only support navigator.clipboard.writeText() (for copying text). They also don't seem to have a Standards Position on the API either, or no one has asked for one.Demb
so, no universal solution then...Pera
Unfortunately not. But everyone is free to ask for a standards position, so developer interest gets on the Firefox team's radar.Demb

© 2022 - 2024 — McMap. All rights reserved.