tqk2811
tqk2811

Reputation: 567

Copy text innerHTML of element to clipboard

I was try many solutions in stackoverflow, but it not work.(here and here)

I try it in Website and use chrome extension for run code (chrome 59.0.3071.104 64bit)

<h4 align="center">text data to copy</h4>

var copy_text = document.getElementsByTagName("h4")[0];
copy_text.select(); //-> error: select is not a function

and

var range = document.createRange();
range.selectNode(copy_text);
window.getSelection().addRange(range);
document.execCommand("copy"); //-> clipboard not change

Any solution for this? Thankyou.


Edit: I think my problem is page loading (security brower), all solution work with user interactive

Upvotes: 5

Views: 19125

Answers (3)

MetaTron
MetaTron

Reputation: 1091

Here, the first example. https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f. My example is re-written by my needs but You'll get the point :)

<div onclick="bufferText()">Миньор Перник!</div>
<script>
   function bufferText() {    
        const el = document.createElement("textarea");
        el.value = event.target.innerHTML;
        document.body.appendChild(el);
        el.select();
        document.execCommand("copy");
        document.body.removeChild(el);
   }
</script>

Upvotes: 4

qiAlex
qiAlex

Reputation: 4346

This works for me.

var copyTextareaBtn = document.querySelector('.copybtn');

copyTextareaBtn.addEventListener('click', function(event) {
  var copy_text = document.getElementsByTagName("h4")[0];
  var range = document.createRange();
  range.selectNode(copy_text);
  window.getSelection().addRange(range);

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
<button class="copybtn">Copy</button>
<h4 align="center">text data to copy</h4>

But it isn't working if I try to copy not on click, but when the page is loaded

Upvotes: 2

Andrew Bone
Andrew Bone

Reputation: 7291

Here is a quick hacky way to do what you want, there is a hidden input that we put the data in and then copy it from there. (The text area is just somewhere to paste into)

function copyText(e) {
  var textToCopy = document.querySelector(e);
  var textBox = document.querySelector(".clipboard");
  textBox.setAttribute('value', textToCopy.innerHTML);

  textBox.select();
  document.execCommand('copy');
}
.hidden {
  position: fixed;
  bottom: 0;
  right: 0;
  pointer-events: none;
  opacity: 0;
  transform: scale(0);
}
<h4 class="text" align="center">Text data to copy</h4>

<button onclick="copyText('.text')" class="copy">Copy</button>
<br><br>
<textarea></textarea>

<input class="clipboard hidden" />

Upvotes: 2

Related Questions