JavaScript get clipboard data on paste event (Cross browser)

前端 未结 20 2391
小蘑菇
小蘑菇 2020-11-21 11:22

How can a web application detect a paste event and retrieve the data to be pasted?

I would like to remove HTML content before the text is pasted into a rich text edi

相关标签:
20条回答
  • 2020-11-21 12:07

    Simple version:

    document.querySelector('[contenteditable]').addEventListener('paste', (e) => {
        e.preventDefault();
        const text = (e.originalEvent || e).clipboardData.getData('text/plain');
        window.document.execCommand('insertText', false, text);
    });
    

    Using clipboardData

    Demo : http://jsbin.com/nozifexasu/edit?js,output

    Edge, Firefox, Chrome, Safari, Opera tested.

    Document.execCommand() is obsolete now.


    Note: Remember to check input/output at server-side also (like PHP strip-tags)

    0 讨论(0)
  • 2020-11-21 12:07

    This solution is replace the html tag, it's simple and cross-browser; check this jsfiddle: http://jsfiddle.net/tomwan/cbp1u2cx/1/, core code:

    var $plainText = $("#plainText");
    var $linkOnly = $("#linkOnly");
    var $html = $("#html");
    
    $plainText.on('paste', function (e) {
        window.setTimeout(function () {
            $plainText.html(removeAllTags(replaceStyleAttr($plainText.html())));
        }, 0);
    });
    
    $linkOnly.on('paste', function (e) {
        window.setTimeout(function () {
            $linkOnly.html(removeTagsExcludeA(replaceStyleAttr($linkOnly.html())));
        }, 0);
    });
    
    function replaceStyleAttr (str) {
        return str.replace(/(<[\w\W]*?)(style)([\w\W]*?>)/g, function (a, b, c, d) {
            return b + 'style_replace' + d;
        });
    }
    
    function removeTagsExcludeA (str) {
        return str.replace(/<\/?((?!a)(\w+))\s*[\w\W]*?>/g, '');
    }
    
    function removeAllTags (str) {
        return str.replace(/<\/?(\w+)\s*[\w\W]*?>/g, '');
    }
    

    notice: you should do some work about xss filter on the back side because this solution cannot filter strings like '<<>>'

    0 讨论(0)
提交回复
热议问题