Intercept Paste data in JavaScript

我怕爱的太早我们不能终老 提交于 2019-12-05 10:24:04

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

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.

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