JavaScript get clipboard data on paste event (Cross browser)

前端 未结 20 2364
小蘑菇
小蘑菇 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 11:46

    This is an existing code posted above but I have updated it for IE's, the bug was when the existing text is selected and pasted will not delete the selected content. This has been fixed by the below code

    selRange.deleteContents(); 
    

    See complete code below

    $('[contenteditable]').on('paste', function (e) {
        e.preventDefault();
    
        if (window.clipboardData) {
            content = window.clipboardData.getData('Text');        
            if (window.getSelection) {
                var selObj = window.getSelection();
                var selRange = selObj.getRangeAt(0);
                selRange.deleteContents();                
                selRange.insertNode(document.createTextNode(content));
            }
        } else if (e.originalEvent.clipboardData) {
            content = (e.originalEvent || e).clipboardData.getData('text/plain');
            document.execCommand('insertText', false, content);
        }        
    });
    

提交回复
热议问题