firefox中document.execCommand('copy')无效

前端菜鸟在查一个firefox复制失败但chrome复制正常的问题。定位到firefox执行document.execCommand('copy')返回false,而chrome返回true

这里提到

With the 'cut' or 'copy' command as argument, Document.execCommand()
now works, but only within the context of user-initiated or privileged
code

我使用的是firefox 47

看了代码感觉execCommand('copy')不是用户触发的(我不确定,不了解多少js....)
想问下privileged code是个什么东西……firefox中有开关能打开之类的么?

谢谢。

阅读 17.2k
3 个回答

这是一个安全考虑,因为exeCommand()可以操作系统剪切板,有可能被恶意利用。所以你不能用JS“直接”调用execCommand('copy'),而需要放到某一个有用户出发的事件响应函数内,如

<button id="mybtn"></button>
<script>
  $('#mybtn').click(function () {
    document.execCommand('copy');
  });
</script>

补充楼上,另一点需要注意的是

用户触发的事件和 document.execCommand('copy'); 之间不能被异步过程隔开

诸如 setTimeout 之类的都是不可以的

<input type='text' id='testInput' value="这是测试问题" onclick='copy(this)'>


<script>

//onclick时触发的copy函数
function copy(obj)
{
obj.select(); 
document.execCommand("Copy");
alert("已复制好");
}

//模拟点击
var obj = document.getElementById("testInput");
obj.click();

</script>

只有通过用户实际操作才能触发execCommand,即使JS模拟点击也不可以。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题