Copy text innerHTML of element to clipboard

Viewed 14827

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

3 Answers

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>
Related