简体   繁体   中英

How do I copy from Javascript variable to Clipboard

I was trying to copy my JavaScript variable to my clipboard in Chrome. I found a lot of information on the web but none of the results were exactly what I needed.

The answer ended up being pretty simple. Though, I'm unsure if all this is needed.

document.body.appendChild(element);
element.value = "foo";
element.select();
document.execCommand('copy', element.value); <--- solution
document.body.removeChild(element);

I was also unable to find documentation that mentions the ability to pass a value parameter to the execCommand copy function and actually guessed its existence. Other examples used.focus and.select methods instead, hence the element.select(). Those did not work for me. Adding the parameter to the execCommand function seemed to fix the problem.

So my question is how can this snippet be improved? Does that additional parameter have to be an html element?

Try the code below:

var text = "text";
function copyVar(text) {
    var textElement = document.createElement('textarea');
    textElement.value = text;
    textElement.setAttribute('readonly', '');
    document.body.appendChild(textElement);
    textElement.select();
    document.execCommand('copy');
    document.body.removeChild(textElement);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM