首頁  >  問答  >  主體

javascript - 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中有开关能打开之类的么?

谢谢。

怪我咯怪我咯2750 天前1260

全部回覆(3)我來回復

  • 阿神

    阿神2017-04-11 12:46:24

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

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

    回覆
    0
  • 怪我咯

    怪我咯2017-04-11 12:46:24

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

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

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

    回覆
    0
  • PHPz

    PHPz2017-04-11 12:46:24

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

    回覆
    0
  • 取消回覆