0

I'm trying to copy text from a textarea without having to click on a button. I'm using execCommand('copy') and I can get it to copy the text but only when the button has been clicked and not programmatically.

Is there a way to do this?

var button = document.querySelector('button');
var area = document.querySelector('textarea');

button.addEventListener("click", function(){
  area.select();
  var msg = document.execCommand('copy') ? "successful" : "unsuccessful";
  console.log("Copy " + msg);
});

button.click(); // Does not copy successfully
<textarea>Text to Copy</textarea>
<button>Copy</button>
spencer.sm
  • 19,173
  • 10
  • 77
  • 88

1 Answers1

0

No, changes to the clipboard must be initiated by the user.

See: https://w3c.github.io/editing/execCommand.html#dfn-the-copy-command

Copy commands triggered from document.execCommand() will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this. How implementations can be configured to allow write access to the clipboard is outside the scope of this specification.

Dan Wilson
  • 3,937
  • 2
  • 17
  • 27