Copy image to clipboard with javascript in Chrome only Copy image to clipboard with javascript in Chrome only google-chrome google-chrome

Copy image to clipboard with javascript in Chrome only


Update: From Chrome 43, Firefox 41, Opera 29 and Safari 10 onwards, any website can do document.execCommand("copy") and document.execCommand("cut") anytime.


Outdated:

Just as Copy Image to Clipboard from Browser in Javascript? explained, it is a security hole if any website is allowed to take/put data into users' OS just because she navigated to a malicious website.

If you are targeting Chrome only, you have two solutions.

  1. Write a Chrome Extension and ask your users to install it.

  2. Write a Chrome App and ask your users to install it. Your users need not to be running your Chrome App. Scripts in the domains the installed Chrome App registers will automatically gain this privilege.

Your app/extension has to declare the clipboardWrite privilege (see https://developer.chrome.com/extensions/permissions).

Then you can call document.execCommand("Copy") after you have manipulated the window.selection to point to the image you want to copy.


In 2020, it can be done with the Asynchronous Clipboard API, see here: https://arnellebalane.com/blog/async-clipboard-api/ (includes a demo).