javascript - firefox中document.execCommand('copy')无效
怪我咯
怪我咯 2017-04-11 12:44:24
0
3
1253

前端菜鸟在查一个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中有开关能打开之类的么?

谢谢。

怪我咯
怪我咯

走同样的路,发现不同的人生

répondre à tous(3)
阿神

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

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

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

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

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

PHPzhong
<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模拟点击也不可以。

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!