How To : Paste Image from Clipboard using JavaScript

Earlier access to clipboard data through JavaScript was restricted for few security reasons - but now thanks to the advancements in the browser technologies it is possible to directly paste raw images from system clipboard (eg: clicking the PrntScr key) in to a web page. Few we applications like Gmail, JIRA, etc have support for this feature - that makes this task very simple for their users which would otherwise be a tedious task of saving the image as a file and then attaching it. 

Given below are few code snippets / pseudo-code on how to paste images from clipboard for various browsers:

Google Chrome and Safari:
The core webkit of these two browsers supports the latest clipboard APIs and hence we can access the raw image data by binding an handler for the 'paste' event. Image data from the clipboard can be accessed via event.clipboard.items. Refer the below code snippet for more details:

document.onpaste = function(event)
    var items = event.clipboardData.items;
    console.log(JSON.stringify(items)); // will give you the mime types
    var blob = items[0].getAsFile();
    var reader = new FileReader();
    reader.onload = function(event)
    }; // data url  

Once we get access to the data URL we could either display the image or send it to server for further processing, if needed.

further reading:
There isn't much work needs to be done for Firefox. Firefox itself would paste the image in an Editable div - hence declaring the div as editable would suffice for firefox. If one needs to access the pasted image data for further processing we can do the following:
1. Make the div element editable and bind a handler method for the 'paste' event
2. The handler method sleeps for some time (until the browser displays the pasted image) 
3. access the newly added image element in the above mentioned div and process it further.

Microsoft Internet Explorer:
This one is a little complex one. Unfortunately the above mentioned Clipboard APIs aren't working in IE - hence we will have to use Applet or ActiveX components to support in this feature in IE. Pseudo-code for applet can be as follows:
1. Bind an handler method for 'key press' event
2. When the user press 'Ctrl+V' in the div, the handler method will load the applet.
3. The applet can have access to the clipboard data (for code refer the link below) > convert it to DataURI > return the image data to the browser (by calling a javascript method)
4. The Javascript method can then either display the image or send it to server for further processing.
5. For smooth functioning, the applet needs to be signed properly - otherwise every time the browser would prompt with a warning message.

further reading:

No comments:

Post a Comment