JavaScript get clipboard data on paste event (Cross browser)

前端 未结 20 2362
小蘑菇
小蘑菇 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:50

    Live Demo

    Tested on Chrome / FF / IE11

    There is a Chrome/IE annoyance which is that these browsers add

    element for each new line. There is a post about this here and it can be fixed by setting the contenteditable element to be display:inline-block

    Select some highlighted HTML and paste it here:

    function onPaste(e){
      var content;
      e.preventDefault();
    
      if( e.clipboardData ){
        content = e.clipboardData.getData('text/plain');
        document.execCommand('insertText', false, content);
        return false;
      }
      else if( window.clipboardData ){
        content = window.clipboardData.getData('Text');
        if (window.getSelection)
          window.getSelection().getRangeAt(0).insertNode( document.createTextNode(content) );
      }
    }
    
    
    /////// EVENT BINDING /////////
    document.querySelector('[contenteditable]').addEventListener('paste', onPaste);
    [contenteditable]{ 
      /* chroem bug: https://stackoverflow.com/a/24689420/104380 */
      display:inline-block;
      width: calc(100% - 40px);
      min-height:120px; 
      margin:10px;
      padding:10px;
      border:1px dashed green;
    }
    
    /* 
     mark HTML inside the "contenteditable"  
     (Shouldn't be any OFC!)'
    */
    [contenteditable] *{
      background-color:red;
    }

提交回复
热议问题