Intercept Paste data in JavaScript

wibberding picture wibberding · Jul 2, 2014 · Viewed 14.9k times · Source

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.
    };
}

Answer

nmaier picture nmaier · Jul 2, 2014

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

fiddle