How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?

I spent some time experimenting with this. It seems to sort of follow the new Clipboard API spec. You can define a “paste” event handler and look at event.clipboardData.items, and call getAsFile() on them to get a Blob. Once you have a Blob, you can use FileReader on it to see what’s in it. This is how you can get a data url for the stuff you just pasted in Chrome:

document.onpaste = function (event) {
    var items = (event.clipboardData || event.originalEvent.clipboardData).items;
    console.log(JSON.stringify(items)); // might give you mime types
    for (var index in items) {
        var item = items[index];
        if (item.kind === 'file') {
            var blob = item.getAsFile();
            var reader = new FileReader();
            reader.onload = function (event) {
                console.log(event.target.result); // data url!
            }; 
            reader.readAsDataURL(blob);
        }
    }
};

Once you have a data url you can display the image on the page. If you want to upload it instead, you could use readAsBinaryString, or you could put it into an XHR using FormData.

Edit: Note that the item is of type DataTransferItem. JSON.stringify might not work on the items list, but you should be able to get mime type when you loop over items.

Leave a Comment