I'm trying this function:
function copyToClipboard(str) {
const el = document.createElement('textarea');
el.textContent = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) :
false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
alert("Success");}
I've tried with el.value = str; too. What am I doing wrong?
The document.execCommand
has been deprecated but still accessible across web browsers
The navigator.clipboard API
is an alternative navigator.clipboard
You pass in the text to be copied to the clipboard like so
navigator.clipboard.writeText(str_to_copy).then(success_callback, failure_callback);
Note that the tab must be active for this to work else you won’t have permissions to copy the clipboard
The API is asynchronous so you can use the .then
callback to alert the user if copying the clipboard was successful or not. Check out the Can I Use for its availability across web browsers.