Intercept Paste data in JavaScript

↘锁芯ラ 提交于 2019-12-22 06:39:35

问题


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

回答1:


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




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!