Get html from clipboard in javascript

試著忘記壹切 提交于 2019-11-29 01:23:43

You won't be able to get data from the clipboard using JavaScript alone, which is the way it should be. The way current versions of TinyMCE and CKEditor do this is as follows:

  1. Detect a ctrl-v / shift-ins event using a keypress event handler
  2. In that handler, save the current user selection, add a div element off-screen (say at left -1000px) to the document, move the caret to be inside that div, thus effectively redirecting the paste
  3. Set a very brief timer (say 1 millisecond) in the event handler to call another function that retrieves the HTML content from the div and does whatever processing is required, removes the div from the document, restores the user selection and inserts the processed HTML.

Note that this will only work for keyboard paste events and not pastes from the context or edit menus. By the time the paste event fires, it's too late to redirect the caret into the div (in some browsers, at least).

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.

<div id="ie-clipboard-contenteditable" class="hidden" contenteditable="true"></div>
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);
}

In Chrome, I access clipboardData through the event using this code:

$(document).bind('paste', function(e) {
    var clipboardData = e.originalEvent.clipboardData;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!