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

醉酒当歌 提交于 2019-12-04 16:45:05

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);
     }
});

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).

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!