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

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?

Answers:

Answer

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) {
        // ...
    }
};
Answer

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.

Answer

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

Answer

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

    });

});
Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.