仅在按钮单击时使用execCommand复制文本

时间:2016-11-07 20:04:17

标签: javascript html

我试图从textarea复制文本而不必点击按钮。我使用execCommand('copy')并且我可以让它复制文本,但只有在单击按钮而不是以编程方式时才会复制。

有办法做到这一点吗?



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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

不,必须由用户启动对剪贴板的更改。

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

  

从document.execCommand()触发的复制命令只会影响   如果从一个调度事件,真实剪贴板的内容   由用户信任和触发的事件,或者是   实现配置为允许此操作。实现方式如何   配置为允许对剪贴板的写访问权限在范围之外   本规范。