I got the following code from Intercept paste event in Javascript.
I need to get it before it is pasted, otherwise i lose the "\n" characters i need to save.
It works great to intercept clipboard data for one element with an id. I need it to work on all input elements. When I try to use jQuery to get the input elements nothing.
Any help is appreciated.
var paster = function () {
var myElement = document.getElementByTagName('pasteElement');
myElement.onpaste = function(e) {
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) {
pastedText = e.clipboardData.getData('text/plain');
}
processExcel(pastedText); // Process and handle text...
return false; // Prevent the default handler from running.
};
}
Just add a paste
event listener to the document.
document.addEventListener("paste", function (e) {
console.log(e.target.id);
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) {
pastedText = e.clipboardData.getData('text/plain');
}
e.preventDefault();
e.target.value = "You just pasted '" + pastedText + "'";
return false;
});
What nmaier said, but you also need to check for the original event.
document.addEventListener("paste", function (e) {
console.log(e.target.id);
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else {
var clipboardData = (e.originalEvent || e).clipboardData;
if (clipboardData && clipboardData.getData) {
pastedText = clipboardData.getData('text/plain');
}
e.preventDefault();
e.target.value = "You just pasted '" + pastedText + "'";
return false;
}
});
Also, you should probably add the event listener just to the element, instead of the whole document.
来源:https://stackoverflow.com/questions/24540765/intercept-paste-data-in-javascript