Lukas
Lukas

Reputation: 1864

jQuery Detect Paste Event Anywhere on Page and "Redirect" it to Textarea

I'm looking to create an "easy paste experience", where the user can hit ctrl-v anywhere on the page to paste their clipboard data into a textarea. I want them to be able to paste text into the textarea without the textarea being focused.

I know I can use this code to detect a paste event:

$('html').bind('paste', function(e) {

});

But I don't know how to grab the clipboard data and "move" it to the textarea, or if this is even possible (what with the restrictions on accessing the user's clipboard).

Upvotes: 2

Views: 4221

Answers (3)

Jack Culhane
Jack Culhane

Reputation: 781

It is possible to do what you are trying in firefox, capture Ctrl-V and redirect it to a textarea / text input.

However you can't do it by listening to the onpaste event in firefox due to security as the other poster said, but it is possible by listening to the keydown event and capturing Ctrl+V.

In all browsers, in general you can't access the clipboard directly (it's possible to set using flash, or I think in some versions of Internet Explorer it may have been possible).

You can listen for the keydown event on the window and check if Ctrl+V is pressed.

Then you can focus the input / textarea, don't cancel propagation of the event, and firefox will happily stick the text where you want it to go.

You can then listen to the onpaste or onchange event of the input to process the text further.

HTML:

<textarea id='redirect_ta'></textarea>

JS:

$(window).keydown(function(event) {
    if(event.ctrlKey && event.keyCode == 0x56) {
        $('#redirect_ta').focus();
    }
});

Here is a JSFiddle illustrating this:

http://jsfiddle.net/DK536/2/

Works on Firefox, Chrome and Internet Explorer.

Upvotes: 0

Jeremy Atkinson
Jeremy Atkinson

Reputation: 134

It is not possible in Firefox. In IE, Safari and Chrome you can do the following:

$('html').bind('paste', function(e) {
    e.preventDefault();
    if(e.originalEvent.clipboardData){
       var text = e.originalEvent.clipboardData.getData("text/plain");
       alert(text);
     }
});

Upvotes: 4

Jason Sperske
Jason Sperske

Reputation: 30416

It is not possible to access the copy buffer from JavaScript (or Flash, though there is a Flash project called ZeroClipboard that can add text to the copy buffer it cannot read it back).

Upvotes: 0

Related Questions