Is it possible to read the clipboard in Firefox, Safari and Chrome using Javascript?

混江龙づ霸主 提交于 2019-11-26 05:28:03

问题


I\'m trying to read the contents of the clipboard using Javascript. With Internet Explorer it\'s possible using the function

window.clipboardData.getData(\"Text\")

Is there a similar way of reading the clipboard in Firefox, Safari and Chrome?


回答1:


Safari supports reading the clipboard during onpaste events:

Information

You want to do something like:

someDomNode.onpaste = function(e) {
    var paste = e.clipboardData && e.clipboardData.getData ?
        e.clipboardData.getData('text/plain') :                // Standard
        window.clipboardData && window.clipboardData.getData ?
        window.clipboardData.getData('Text') :                 // MS
        false;
    if(paste) {
        // ...
    }
};



回答2:


Online Spreadsheets hook Ctrl+C, Ctrl+V events and transfer focus to a hidden TextArea control and either set it contents to desired new clipboard contents for copy or read its contents after the event had finished for paste.




回答3:


NO. And if you do find a hack (e.g. old version of flash) do not depend on it.

Can I ask why you want to read from the clipboard? If the user wants to pass along the clipboard contents, all they need to do is paste.




回答4:


I believe people use a hidden Flash element to read the clipboard data from the browsers you mentioned.




回答5:


Using @agsamek suggestion I created a little test snipped and got it to work. In my case I need to wait after a fresh pageload for pasted input, so I focus on an out-of-view textarea and read the text from there.

You could extend this to listen to specific keys (paste combination) and then focus on the hidden field. There would definitely more work to be done as I think you need to re-focus then on the last focused element and paste content there.

For my use-case though this was enough to make it work in latest Chrome and Firefox. Suggestions welcome.

https://jsfiddle.net/wuestkamp/91dxjv7s/11/

$(function () {

    $('body').prepend('<input type="text" id="hidden_textbox" style="position: absolute; width:0px; height: 0px; top: -100px; left: -100px">');

    var $hiddenTextbox = $('#hidden_textbox');
    $hiddenTextbox.focus();

    $(document).on('paste', function () {
        setTimeout(function () {
            var val = $hiddenTextbox.val();

            console.log('pasted: ' + val);

        }, 50);

    });

});


来源:https://stackoverflow.com/questions/233719/is-it-possible-to-read-the-clipboard-in-firefox-safari-and-chrome-using-javascr

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