7

I would like to trigger onpaste event on element to retrieve data in clipboard (I want to check if image exists in clipboard and upload it into the server). It works perfect on Chrome:

$('#textarea')[0].onpaste = function(event)
{
    var items = event.clipboardData.items;

    if (items.length)
    {
        var blob = items[0].getAsFile();
        var fr = new FileReader();

        fr.onload = function(e)
        {
            alert('got it!');
        }

        fr.readAsDataURL(blob);
    }
}

Does not work on Firefox: event.clipboardData.items does not exists. Do you have any idea how to retrive onpaste event in element?

Bald
  • 1,888
  • 3
  • 23
  • 31
  • Firefox does not allow you to access the clipboard because of security reasons. Anyway your question is a duplicate of http://stackoverflow.com/questions/127040/copy-put-text-on-the-clipboard-with-firefox-safari-and-chrome – Jason Yeo Feb 10 '12 at 21:36

3 Answers3

2

You need to create one contenteditable div which will hold the image on paste

var pasteCatcher = $('<div/>',{'id':'container'});
$('body').append(pasteCatcher);
var pasteCatcher = document.getElementById('container');
               pasteCatcher.setAttribute("contenteditable", "");

then you need to wait for paste event and process it

 window.addEventListener("paste",processEvent);
function processEvent(e) {
//some functionality
}

Also write the code to grab the image data from contenteditable div and send it to server.

Mahendra
  • 123
  • 1
  • 5
  • 15
1

It seems not. Sorry.

http://support.mozilla.org/en-US/kb/Granting%20JavaScript%20access%20to%20the%20clipboard

JavaScript get clipboard data on paste event (Cross browser)

Community
  • 1
  • 1
anders.norgaard
  • 1,042
  • 13
  • 23
0

Sure I can. In this example I retrieve image from clipboard after using Ctrl+V:

 <div id="foo" style="width: 200px; height: 200px" contenteditable="true">Paste here!</div>
 $('#foo')[0].onpaste = function(e)
{                   
    setTimeout(function()
    {
        var blob = $('#foo img').attr('src');


        $.post('/upload/image', {'data': blob}, function(result)
        {


        }, 'json'); 

    }, 200);
}

It works with <div> element that has contenteditable attribute, but does not work with <textarea>

P.S. Sorry for answering my own question but this piece of code might help someone.

Bald
  • 1,888
  • 3
  • 23
  • 31
  • Hey i need your help. Your solution is correct but i have one doubt if contenteditable div is already contains 2 images and when i Crtl+V then it upload total 3 images on server ? –  Jul 07 '15 at 06:31
  • Well... above code uploads everything that is in `src` attribute. – Bald Jul 07 '15 at 10:35
  • i know it upload src attribute value, but i want to know if there is 3 src already available in the div then it upload total 4 src ( in which 3 is already there and 4th is newly pasted ) ?? –  Jul 07 '15 at 10:54