views:

6346

answers:

5

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

window.clipdData.getData("Text")

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

+1  A: 

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

Nick Berardi
+2  A: 

Dupe of this question: http://stackoverflow.com/questions/127040

In addition to the correct answer there, Flash 10 now only allows write-access to the clipboard during user interaction (eg. a click handler).

bobince
The other question asks how to write, he's asking how to read.
Achille
A: 

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.

scunliffe
I'm reading the clipboard on the onpaste event (in IE) to filter out invalid chars (eg. to remove whitespace from an integer value).
gilfaria
use onchange on the field they're pasting into?
nickf
+5  A: 

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) {
        // ...
    }
};
eyelidlessness
If only firefox would support this! Its secure and allows access to the clipboard.
Nico Burns
+6  A: 

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.

agsamek
How do you test for 'after the event had finished for paste'?
schwerwolf
Don't know. But since the entire method is not a piece of art in anyway I would sleep for 1 second ;)
agsamek
We just added (thanks to the above comment for inspiration) something like this in CodeMirror (http://marijn.haverbeke.nl/codemirror). It listens for onbeforepaste, creates a textarea, focuses it, sleeps 10 milliseconds, grabs the content, removes the textarea, returns the focus where it was before, and has its dirty way with the pasted text. Only works reliably on IE. By reacting to ctrl-V (and command-V) presses, you can also get it to work in FF and maybe some other browsers.
Marijn
@Marijn: I've used the same approach for an editor I'm working on and the hidden textarea trick works fine in all the major browers for keyboard pastes. Unfortunately IE fires `onbeforepaste` as soon as you open the context menu: have you managed to deal with this?
Tim Down