问题
I'm trying to write a Javascript function to edit content from clipboard before pasting. Right now i got bound event 'paste' to function via JQuery.
$(this.elementDoc).bind('paste', function(event){
self.OnPaste(event);
});
But that's not important. Now I would like to get Data from clipboard, but I can't find out how. I would be glad for every hint.
回答1:
This is a toughie. If I recall correctly, IE allows access to the clipboard, but by default Firefox does not due to security issues. I had to do this for a project I was working on, and was forced to use a small SWF file that did the copying.
http://www.jeffothy.com/weblog/clipboard-copy/
回答2:
The clipboardData can contains data in various potential formats. Its possible a program will add clipboard data in multiple formats. To look through the formats, look through clipboardData.types.
Often the clipboard data contains plain text, and the first type listed in types will be the MIME type "text/plain". If you copy text from a browser tho, you will see two types in the list: "text/plain" and "text/html". Depending on which string you pass into getData, you can grab the plain text, or the html. It seems that "text" is shorthand for "text/plain" and "url" is short for "text/uri-list".
element.addEventListener('paste', function(event) {
var cb = event.clipboardData
if(cb.types.indexOf("text/html") != -1) { // contains html
var pastedContent = cb.getData("text/html")
} else if(cb.types.indexOf("text/html") != -1) { // contains text
var pastedContent = cb.getData("text/html")
} else {
var pastedContent = cb.getData(cb.types[0]) // get whatever it has
}
// do something with pastedContent
})
For more info on how to use clipboardData.getData, see the ugly spec.
回答3:
Here is how to get it from IE or from Chrome. First it prevents the actual paste from happening, then it does a feature check and then sets the variable text to the clipboard text. With that you can manipulate the text, and then set it as the value for the input/element your pasting to, or whatever else you want to do with it.
//get clipboard text
event.preventDefault();
var text = null;
if (window.clipboardData)
text = window.clipboardData.getData("Text");
else if (event.originalEvent && event.originalEvent.clipboardData)
text = event.originalEvent.clipboardData.getData("Text");
//manipulate the text
text = '..do stuff with it..';
//set the text
$(this).val(text);
来源:https://stackoverflow.com/questions/1144184/get-clipboard-data