Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,
I am trying to access the clipboard data on button click event in Chrome, but I am not able to access it. But if I am pressing Ctrl+v in keyboard, chrome can find the clipboard data. So for that, from a button click event I tried to call/trigger the paste event of a textbox/editor, but the clipboard is not accessible, however if I directly fire the paste event of the textbox/editor by pressing Ctrl+V, the clipboard data is accessed.

Kindly help me to get the clipboard data by trigger the paste event from a button click event. Below is my code:

This code works
---------------
JavaScript
$(window).on("paste", function(e) {   
    $.each(e.originalEvent.clipboardData.items, function() {       
        this.getAsString(function(str) {            
            alert(str);
        });
    });
});


When I tried to trigger the above event from a buttonclick event, it cannot access the clipboardData, hence throws exception. Below is the code:

----------------------
JavaScript
$(document).ready(function(){ 
  $("#btnSubmit").click( function() {
    //$("#txtText").trigger("paste"); 
    var event = $.Event('paste');
    $("#txtText").triggerHandler(event); });
    
    $('#txtText').on("paste", function(e) {   
    // e.preventDefault();
    $.each(e.originalEvent.clipboardData.items, function() {       
         var dataa = e.clipboardData.getData("text/plain");
         alert(dataa);       
       });
    });
  });


Thanks in advance.
Posted
Updated 12-May-15 1:01am
v2

1 solution

The problem is that jQuery does not trigger native events, but internally calls all the registered handlers for the specified event name...
So a fake event will never be originalEvent (not for fake click either!)...
From this - you can not use jQuery to fake a paste event...
I would say that plain JavaScript dispatchEven may do the work with KeyboardEvent...
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events[^]
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900