2021年3月12日星期五

Why copy to clipboard doesn't work using JavaScript?

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?

https://stackoverflow.com/questions/66608810/why-copy-to-clipboard-doesnt-work-using-javascript March 13, 2021 at 08:09AM

没有评论:

发表评论