How can I copy rich text contents to the clipboard with JavaScript?

With modern browsers, if you want copy rich text only, there is a very easy solution without using any packages. See http://jsfiddle.net/jdhenckel/km7prgv4/3

Here is the source code from the fiddle

<button onclick="copyToClip(document.getElementById('foo').innerHTML)">
  Copy the stuff
  </button>
  
<div id=foo style="display:none">
  This is some data that is not visible. 
  You can write some JS to generate this data. 
  It can contain rich stuff.  <b> test </b> me <i> also </i>
  <span style="font: 12px consolas; color: green;">Hello world</span> 
  You can use setData to put TWO COPIES into the same clipboard, 
  one that is plain and one that is rich. 
  That way your users can paste into either a
  <ul>
    <li>plain text editor</li>
    <li>or into a rich text editor</li>
  </ul>
</div>

the function

function copyToClip(str) {
  function listener(e) {
    e.clipboardData.setData("text/html", str);
    e.clipboardData.setData("text/plain", str);
    e.preventDefault();
  }
  document.addEventListener("copy", listener);
  document.execCommand("copy");
  document.removeEventListener("copy", listener);
};

⚠️ ClipboardEvent.clipboardData is experimental technology. Check the browser compatibility table in MDN (05-03-21)

Leave a Comment