71

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>

2

7 Answers 7

102

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)

EDIT:

Using execCommand is deprecated! Please have a look at the new ClipboardAPI. I highly recommend reading this post by Artemis.

6
  • Thank you. I tested this by copying and pasting into Word. It works beautifully on Chrome. It does not seem to work on IE11 at all. On Edge it will paste the text but without formatting.
    – gordon613
    May 30, 2018 at 14:37
  • Sorry about that. I didn't test it on IE 11 or edge. I wonder... if you reverse the two e.clipboardData.setData then perhaps you can paste rich text with IE edge... ? just a thought May 31, 2018 at 21:22
  • 2
    Doesn't work in Safari 11.1.1. Nothing copies, whatever was previously on the clipboard is still there.
    – John Smith
    Jun 11, 2018 at 7:47
  • 1
    This works for me in FF, Chrome, Edge, and IE11. IE11 prompts the user if to allow access to the clipboard. It does not work in Safari. Another method is required for that, and as far as I can tell you can't copy the "rich text", just plain text.
    – Mmm
    Aug 22, 2018 at 21:24
  • 3
    You can use a little bit modified code to also provide text-only version for editors that can not render html: jsfiddle.net/kt4jdm95/1 Mar 29, 2022 at 12:52
12

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."
});
6
  • 1
    Works like a charm, and is indeed simple.
    – Mat
    Dec 9, 2016 at 9:02
  • 9
    With modern browsers, if you want COPY RICH TEXT only, there is a very easy solution without using any packages. See jsfiddle.net/jdhenckel/km7prgv4/3 Dec 14, 2017 at 17:55
  • 1
    @JohnHenckel, that is fantastic! You ought to make it an answer!
    – Dan Lenski
    Apr 24, 2018 at 3:50
  • 3
    Just to point out that for IE @SFlagg's solution will not copy rich text, but only plain text
    – gordon613
    May 30, 2018 at 14:56
  • i can't get this working if the rich text contains images. Sep 5, 2018 at 9:36
8

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.

2
  • 1
    This does not work on Firefox. Please see my answer in a similar post.
    – tst
    Oct 27, 2022 at 5:00
  • If trying this in the console, it may fail because the document itself doesn't have focus, in which case you might need to put this code in a setTimeout so that you have time to move focus back to the document. Mar 21 at 16:21
3

Here's a simple function which uses the Clipboard API where it is supported (as I write this, that's everywhere but Firefox), and falls back to the document.execCommand("copy") method from John Henckel where it is not (deprecated, but currently works everywhere), in the hope that Firefox will add support for the Clipboard API before it drops support for execCommand :)

/** Paste richly formatted text.
 *
 * @param {string} rich - the text formatted as HTML
 * @param {string} plain - a plain text fallback
 */
async function pasteRich(rich, plain) {
  if (typeof ClipboardItem !== "undefined") {
    // Shiny new Clipboard API, not fully supported in Firefox.
    // https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API#browser_compatibility
    const html = new Blob([rich], { type: "text/html" });
    const text = new Blob([plain], { type: "text/plain" });
    const data = new ClipboardItem({ "text/html": html, "text/plain": text });
    await navigator.clipboard.write([data]);
  } else {
    // Fallback using the deprecated `document.execCommand`.
    // https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#browser_compatibility
    const cb = e => {
      e.clipboardData.setData("text/html", rich);
      e.clipboardData.setData("text/plain", plain);
      e.preventDefault();
    };
    document.addEventListener("copy", cb);
    document.execCommand("copy");
    document.removeEventListener("copy", cb);
  }
}

You might also like to try a proper polyfill for the Clipboard API.

1

The Document.execCommand() is apparently becoming obsolete:

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand),

There is a new Clipboard API:

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API

There are some examples here https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard

And also here: https://web.dev/async-clipboard/

1

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

7
  • The OP mentions zeroclipboard in his question, and I talk about it in my comment.
    – Andy
    May 29, 2014 at 13:44
  • i just figured id offer an answer. Since there is no reliable JS method for doing it May 29, 2014 at 13:55
  • @codenamejames: ok, i tried using the help on ZC and dont think i'm being very successful here. here is my code which isnt working still :(
    – marv
    May 29, 2014 at 16:53
  • <div id="d_clip_button">Copy To Clipboard</div> <script type="text/javascript" src="ZeroClipboard.js"></script> <script type="text/javascript"> ZeroClipboard.setMoviePath("ZeroClipboard.swf"); var client = new ZeroClipboard( document.getElementById('d_clip_button') ); </script> `
    – marv
    May 29, 2014 at 16:55
  • i think it should be more like this ZeroClipboard.config({ moviePath: "ZeroClipboard.swf" }); var client = new ZeroClipboard(document.getElementById('d_clip_button')); Jun 3, 2014 at 13:56
-3

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 :)

Copying an image to clipboard using JavaScript/jquery

1
  • 2
    That's for images, not rich text. And anyway it is IE only :-( Dec 14, 2017 at 16:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.