How to put an image to clipboard in Javascript?

3.8k views Asked by At

How to put image to clipboard using Javascript (in handler of copy event) as if it would by done by right click on image in browser and selecting "Copy Image" from context menu.

This script shows details of clipboard content. For copied image it prints:

DataTransfer { dropEffect: "none", effectAllowed: "uninitialized", items: DataTransferItemList[2], types: Array[2], files: FileList[1], mozItemCount: 1, mozCursor: "auto", mozUserCancelled: false, mozSourceNode: null }
DataTransferItem { kind: "string", type: "text/html" }
DataTransferItem { kind: "file", type: "image/png" }
Array [ "text/html", "Files" ]
File { name: "image.png", lastModified: 1504122845696, lastModifiedDate: Date 2017-08-30T19:54:05.696Z, webkitRelativePath: "", size: 385273, type: "image/png" }

So the question can be probably reformulated - how to attach a file to clipboardData in copy event handler function?

document.addEventListener('copy', (event) => {
  // event.clipboardData.?
  // maybe event.clipboardData.setData(?)
})

Not working demo using setData() method.

1

There are 1 answers

3
Koushik Chatterjee On

//get reference to the div
var div = document.getElementById('someDiv');

//attach a paste event
div.addEventListener('paste', function(ev){
    var imgFile = null;
    var idx;
    var items = ev.clipboardData.items;
    for(idx=0;idx<items.length;idx++) {
        //check if any content is file
        if(items[idx].kind==="file") {
            //take that file to imgFile
            imgFile = items[idx].getAsFile();
            break;
        }
    }
    if(imgFile==null) {return;}
    
    //create a File reader
    var reader = new FileReader();
    reader.onload = function() {
        //create an img DOM object
        var img = new Image();
        //reader.result is nothing but the Base64 representation
        img.src = reader.result;
        
        //operate the DOM, clear the div and append the img
        div.innerHTML = '';
        div.appendChild(img);
    }
    //read that file using the reader
    reader.readAsDataURL(imgFile);
});
<div id="someDiv" style="min-width: 200px;min-height: 200px; border: 1px solid red">
Paste an image here (using Ctrl + V)

</div>