1

I'm trying to understand why this code does not work.

What i'm trying to accomplish is to copy into clipboard the current url, so as a workaround i try to create an hidden input in which i pass the current location, but i have no luck.

here an example of what i've tried so far:

var copyBtn = document.querySelector('#copy_btn');

copyBtn.addEventListener('click', function () {
 var input = document.createElement('input');
  input.style.display = "none";
  input.setAttribute('value', document.location)
 document.body.appendChild(input);
  // select the contents
  input.select();
  
  document.execCommand('copy');
}, false);
<input id="copy_btn" type="button" value="copy">
Stefano Saitta
  • 1,844
  • 1
  • 19
  • 34
  • Possible duplicate of [Cannot use \`document.execCommand('copy');\` from developer console](http://stackoverflow.com/questions/33321095/cannot-use-document-execcommandcopy-from-developer-console) – XCS Feb 02 '17 at 10:40

1 Answers1

2

You can only trigger the copy command on user action (key press, click on input, etc...).

Se more info here: https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en

Imagine the security risks if you opened a site and it automatically over-written your clipboard without you doing anything.

So, you should add a button to "copy the URL to clipboard" and use document.execCommand inside the click handler of that button.

LE: I just found a similar question to yours and marked this as a duplicate.

XCS
  • 27,244
  • 26
  • 101
  • 151
  • Ok i see your point, i'll try to investigate starting from that point because acutally in the real implementation that function has been called inside of en eventListener so on a user action, in this case a tap (because mobile). I'll accept the answer for now, i'll probably add more details about the solution. – Stefano Saitta Feb 02 '17 at 10:42
  • Also, see this, it might help: http://stackoverflow.com/questions/12525087/why-doesnt-the-document-execcommand-work-when-i-click-on-a-div – XCS Feb 02 '17 at 10:44
  • 1
    I found out what the issues is, the problem is actually caused by `display:none` property, the element have to be visible to be copied. I'll change a bit my question, if you want to can add this on the answer and i'll accept it. – Stefano Saitta Feb 02 '17 at 11:47