Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy image to clipboard with javascript in Chrome only

Is it possible to have javascript copy an image to a clipboard? I'm looking to replicate the "Copy Image" function that Chrome has when you Right/Control click an image in the browser.

I've seen solutions for text, some Flash based solutions for text as well. But I'm interested in image data only. And only in Chrome. Don't care about IE or FF for this requirement.

like image 412
Mike Jaffe Avatar asked Sep 18 '13 01:09

Mike Jaffe


People also ask

How do I copy from chrome clipboard?

To copy text, highlight the section of text you want and use. Then hit Ctrl+C to copy and save it to the clipboard.

How do you insert a picture into clipboard?

Go to the Images folder and look for the image you want to copy. Long press the image. Tap on the copy icon at the bottom left. Your image is now copied to the clipboard.


2 Answers

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.

like image 177
Alan Tam Avatar answered Oct 06 '22 02:10

Alan Tam


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

like image 43
Ivan Kuckir Avatar answered Oct 06 '22 02:10

Ivan Kuckir