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

JavascriptHtmlClipboard

Javascript Problem Overview


Premise

I need help copying rich text to the clipboard using JavaScript. I have searched around and haven't found anything to suit my specific needs.

Code

function ctrlA1(corp) {
  with(corp) {}
  if (document.all) {
    txt = corp.createTextRange()
    txt.execCommand("Copy")
  } else
    setTimeout("window.status=''", 5000)
}

<div id="sc1">hello <br> <b> world </b> </div>
<button onclick="ctrlA1(document.getElementById('sc1') )"></button>

Problem

The aforementioned code isn't working and is resulting in an object expected error. Any help is appreciated! I have seen a library out there called zeroclipboard, but would prefer to write my own function.


Edit:

I now have this function to select text on the page. is it possible to write a formula to copy the selected range as is?

function containerSelect(id) {
  containerUnselect();
  if (document.selection) {
    var range = document.body.createTextRange();
    range.moveToElementText(id);
    range.select();
  } else if (window.getSelection) {
    var range = document.createRange();
    range.selectNode(id);
    window.getSelection().addRange(range);
  }
}

<label onclick="containerSelect(this); select_all()">
  <p>hello world</p>
  <img src="imagepath.png">
</label>

Javascript Solutions


Solution 1 - 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)

Solution 2 - Javascript

This tiny JS plugin copies richtext without using Flash: https://www.npmjs.com/package/clipboard-js

It's based on https://clipboardjs.com/ - but it's an upgrade in my opinion, because the original only supports plain text.

The code is simple:

clipboard.copy({
    "text/html": "<i>Markup</i> <b>text</b>. Paste me into a rich text editor."
});

Solution 3 - Javascript

Here's an old Flash-based solution. Due to the discontinuation of Flash, it should no longer be used in production environments.

https://github.com/zeroclipboard/zeroclipboard

Solution 4 - Javascript

Solution 5 - Javascript

Here is an example I tested using the new Clipboard API:

const content = '<a href="http://google.com/">test</a>';
const blob = new Blob([content], {type: 'text/html'});
const clipboardItem = new window.ClipboardItem({ 'text/html': blob });
navigator.clipboard.write([clipboardItem]);

Using this method, you can copy html to the clipboard. One useful thing to note is that this can include images (which can be dataURLs). This is the only way I found to paste multiple images to the clipboard.

Solution 6 - Javascript

i searched for a week now and finally found my answer!!! for those of you looking to copy rich text to the clipboard with javascript, then use the function at the link below, works like a charm. no need of flash and other stuff suggested :)

https://stackoverflow.com/questions/8743559/copying-an-image-to-clipboard-using-javascript-jquery

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarvView Question on Stackoverflow
Solution 1 - JavascriptJohn HenckelView Answer on Stackoverflow
Solution 2 - JavascriptSFlaggView Answer on Stackoverflow
Solution 3 - JavascriptJames HarringtonView Answer on Stackoverflow
Solution 4 - JavascriptJungle EditorView Answer on Stackoverflow
Solution 5 - JavascriptantoineMoPaView Answer on Stackoverflow
Solution 6 - JavascriptmarvView Answer on Stackoverflow