Reputation: 1864
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
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:
Works on Firefox, Chrome and Internet Explorer.
Upvotes: 0
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
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