Juniper Scott
Juniper Scott

Reputation: 113

How to Preserve HTML (Strictly) in Copied Text?

To add extra info in bottom of copied text - I want to use the following JS:

<script>
    document.addEventListener('copy', (event) => {
      const pagelink = `\n\nRead more at: ${document.location.href}`;
      event.clipboardData.setData('text', document.getSelection() + pagelink);
      event.preventDefault();
    });
</script>


Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br/>
<textarea name="textarea" rows="7" cols="50" placeholder="paste your copied text here"></textarea>

Since it's the most recent version. But the problem is, it does NOT preserve the HTML tags and attributes like a, style, textarea etc. unlike default copy/paste (verified the results in MS-Word). It's not even hyperlink the url.

Is there anyway I can preserve the HTML stuff (like default or better) and also add reference in copied text?

Or is any better small piece of code that works cross-browser?

Upvotes: 0

Views: 268

Answers (1)

SpiritOfDragon
SpiritOfDragon

Reputation: 1432

You need to have a custom method that returns the HTML of the selected contents. Below is the working snippet.

function getSelectionHtml() {
  var html = "";
  if (typeof window.getSelection != "undefined") {
    var sel = window.getSelection();
    if (sel.rangeCount) {
      var container = document.createElement("div");
      for (var i = 0, len = sel.rangeCount; i < len; ++i) {
        container.appendChild(sel.getRangeAt(i).cloneContents());
      }
      html = container.innerHTML;
    }
  } else if (typeof document.selection != "undefined") {
    if (document.selection.type == "Text") {
      html = document.selection.createRange().htmlText;
    }
  }
  return html;
}

document.addEventListener('copy', (event) => {
  const pagelink = `\n\nRead more at: ${document.location.href}`;
  var html = getSelectionHtml();
  event.clipboardData.setData('text/plain', html + pagelink);
  event.preventDefault();
});
<p>
  Lorem <b>ipsum</b> dolor sit amet, consectetur adipiscing elit.<br/>
</p>

<textarea name="textarea" rows="7" cols="50" placeholder="paste your copied text here"></textarea>

Upvotes: 1

Related Questions