不能使用`document.execCommand(' copy');`来自开发者控制台

时间:2015-10-24 17:21:49

标签: javascript google-chrome domdocument execcommand

每次从Chrome开发者控制台调用document.execCommand('copy');都会返回false

自己尝试一下。打开控制台并运行它,它永远不会成功。

知道为什么?

enter image description here

4 个答案:

答案 0 :(得分:38)

document.execCommand('copy')必须由用户触发。它不仅来自控制台,而且不在用户触发的事件中。如下所示,click事件将返回true,但是没有事件的调用不会和调度事件中的调用也一样。

console.log('no event', document.execCommand('bold'));

document.getElementById('test').addEventListener('click', function(){
    console.log('user click', document.execCommand('copy'));
});

document.getElementById('test').addEventListener('fakeclick', function(){
    console.log('fake click', document.execCommand('copy'));
});


var event = new Event('fakeclick')

document.getElementById('test').dispatchEvent(event) ;
<div id="test">click</ha>

见这里:https://w3c.github.io/editing/execCommand.html#dfn-the-copy-command

  

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

答案 1 :(得分:6)

作为替代方案,请使用Chrome开发工具内置的copy()命令。您无法使用document.execCommand("copy"),因为这需要用户操作才能触发它。

copy()命令允许您复制任何字符串(或对象作为JSON)。要模仿document.execCommand("copy"),您可以使用getSelection().toString()获取当前选择:

copy(getSelection().toString())

screen shot

如果您需要专门测试document.execCommand("copy")(例如,调试使用它的脚本),并且由于某些原因使用调试器并不理想,您可以将代码包装在单击处理程序中,然后单击您的页面:

document.body.addEventListener("click", function() {
    console.log("copy", document.execCommand("copy"));
}, false);

答案 2 :(得分:2)

我相信,copy命令需要关注浏览器,当你转到Console并执行命令时,当前窗口失去焦点。但可能是其他原因,因为如果我放弃setTimeout(),它会起作用。

答案 3 :(得分:0)

此方法适用于最新版本的safari

const copyUrl = (url, cb) => {
  try {
    var input = document.getElementById('copyInput')
    input.value = url
    input.focus()
    input.select()
    if (document.execCommand('copy', false, null)) {
      Message('复制成功')
    } else {
      Message({
        message: '当前浏览器不支持复制操作,请使用Ctrl+c手动复制',
        type: 'warning'
      })
    }
  } catch (e) {
    Message({
      message: `复制出错:${e}`,
      type: 'error'
    })
  }
}