Ad

How To Copy Plain Text Value From Using Javascript

- 1 answer

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}

I found this code on Reddit and I thought it would work as it was logical to create a element then SELECT IT then after that execute the command 'copy'. But I was surprised that it didn't and I do not know why.

No error is given when running this script on Chrome Dev Console which is where I want to execute it and that's exactly why I don't want to hear as an answer ANY API that has to do with copying. If you can tell me how to use an API on chrome dev tools then feel free to let me know about that.

If there are some things I left out or you have questions about.

Ad

Answer

the code wont work without user interaction, if you try to run it from the console, it will not work.

the only way to run the code is to bind the function to a button or something like that.

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
  }
<button onclick='copytext("some text")'>copy some text!</button>

You can try calling document.queryCommandSupported("copy") or document.queryCommandEnabled("copy") from the dev console as well as from buttons to verify this.

Google Developers

See the known bugs section at the bottom.

Ad
source: stackoverflow.com
Ad