Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript paste event working fine in Chrome but not Firefox

My initial goal is to get an image pasted from the clipboard. But I've troubles getting the paste event.

In JSFiddle, where I reproduced the problem, the HTML only contains a div:

<div style="width: 200px; height: 200px; background: grey" id="pasteTarget" > </div>

The JavaScript first binds my function handlePaste() to the paste event.

window.onload = function() {
    //adding paste event listener on the div
    document.getElementById("pasteTarget").
        addEventListener("paste", handlePaste);
};

This function is supposed to be called when the user presses Ctrl+V or selects "paste" in the browser's menus.

function handlePaste(e) {
    alert("I'm in handlePaste");    
    for (var i = 0 ; i < e.clipboardData.items.length ; i++) {
         var item = e.clipboardData.items[i];
         console.log("Item: " + item.type);
         alert(item.type);
     }   
}

Important: that function accesses e.clipboardData to get the content of the clipboard. For example, if you press the PrtScrn key, then Ctrl+V, you send a print screen image to the handlePaste method. The last alert shows "image/png" when it works fine.

Chrome v37: the JsFiddle works fine. Firefox v32: the handlePaste() method is not called, the first alert does not popup.

The jsFiddle code: http://jsfiddle.net/demeylau/ke44bufm/1/

like image 290
Demey Laurent Avatar asked Oct 20 '22 01:10

Demey Laurent


1 Answers

As far as I can tell, you're going to have to handle the pasting separately per browser agent. Joshua Gross covers a lot of the intricacies of the paste event in this article: Paste Wasteland

Firefox likes to be even more obtuse, but it's possible to read the image data as a file by treating the clipboard data as a Blob. (see the postscript in Gross' article) This is pretty much untackled legacy code in browsers handling OS events in slightly different ways and succinctly sums up why we have most newer features standardised in things like WebAPI. I hope this helps.

like image 197
Minothor Avatar answered Oct 24 '22 04:10

Minothor