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?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
acheddir
  • 71
  • 1
  • 6
  • As I am seeing why don't use a different library in first place such as https://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 solution – ZetaPR Nov 22 '19 at 16:18
  • 2
    Maybe this cal help you out: https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript comment by Chase Seibert – Jacopo Sciampi Nov 22 '19 at 16:20
  • @ZetaPR HTML2Canvas does not copy to the clipboard, only creates the picture – serge Aug 11 '22 at 18:38

1 Answers1

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);
}
DenverCoder9
  • 2,024
  • 11
  • 32
  • seem do not work in Firefox – serge Aug 09 '22 at 13:25
  • 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](https://mozilla.github.io/standards-positions/) on the API either, or no one has asked for one. – DenverCoder9 Aug 10 '22 at 16:50
  • so, no universal solution then... – serge Aug 11 '22 at 18:39
  • Unfortunately not. But [everyone is free to ask for a standards position](https://github.com/mozilla/standards-positions/blob/main/CONTRIBUTING.md#requesting-a-mozilla-position-on-a-web-specification), so developer interest gets on the Firefox team's radar. – DenverCoder9 Aug 22 '22 at 08:21