JavaScript get clipboard data on paste event (Cross browser)

前端 未结 20 2371
小蘑菇
小蘑菇 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)

提交回复
热议问题