Get html from clipboard in javascript

前端 未结 3 855
一整个雨季
一整个雨季 2020-12-15 05:25

I need to implement task which is quite common feature for RichTextEditors - take HTML from clipboard. Can anyone help with guide on how to solve this task?

3条回答
  •  执笔经年
    2020-12-15 06:21

    I actually have done a lot of work on this, and just wrote a nice blog post describing how we did it in detail at Lucidchart (as a disclaimer, I work at Lucidchart). We have a JSFiddle that shows copying and pasting (tested in Firefox, Safari, Chrome, and IE9+).

    The short of the answer is that you will need to get the HTML during the system paste event. In most (non-IE) browsers, this can be done with something as simple as the following:

    document.addEventListener('paste', function(e) {
      var html = e.clipboardData.getData('text/html');
      // Whatever you want to do with the html
    }
    

    The problem is when you want to get HTML in IE. For whatever reason, IE doesn't make the text/html clipboard data accessible via javascript. What you have to do is let the browser paste to a contenteditable div and then get the html after the paste event is over.

    
    
    var ieClipboardDiv = $('#ie-clipboard-contenteditable'); 
    
    var focusIeClipboardDiv = function() {
      ieClipboardDiv.focus();
      var range = document.createRange();
      range.selectNodeContents((ieClipboardDiv.get(0)));
      var selection = window.getSelection();
      selection.removeAllRanges();
      selection.addRange(range);
    };
    
    document.addEventListener('beforepaste', function() {
      if (hiddenInput.is(':focus')) {
        focusIeClipboardDiv();
      }
    }, true);
    
    document.addEventListener('paste', function(e) {
      ieClipboardDiv.empty();
      setTimeout(function() {
        var html = ieClipboardDiv.html();
        // Do whatever you want with the html
        ieClipboardDiv.empty();
        // Return focus here
      }, 0);
    }
    

提交回复
热议问题