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

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

谢谢。

怪我咯
怪我咯

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

모든 응답(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模拟点击也不可以。

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!