Copy Image to Clipboard from Browser in Javascript?

The last answer is from 2010 and browsers have changed a lot since then.
With this simple function, you can copy whatever you want (text, images, tables, etc) (on your page) to the clipboard.
The function receives the element id or the element itself.

function copyElementToClipboard(element) {
  window.getSelection().removeAllRanges();
  let range = document.createRange();
  range.selectNode(typeof element === 'string' ? document.getElementById(elementName) : element);
  window.getSelection().addRange(range);
  document.execCommand('copy');
  window.getSelection().removeAllRanges();
 }

Leave a Comment