无法从开发者控制台使用 `document.execCommand('copy');`。

24

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

您可以自己尝试一下,在控制台中运行它,它永远不会成功。

有什么想法吗?

输入图片说明

4个回答

43
document.execCommand('copy') 必须由用户触发。它不仅限于控制台,而是任何不在由用户触发的事件内部的位置都是如此。请看下面的例子,点击事件将返回true,但没有事件的调用不会返回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() 触发的复制命令将仅影响真正剪贴板的内容。如何配置实现以允许对剪贴板进行写入访问超出了此规范所涵盖的范围。


8
作为替代方案,请使用内置于Chrome Dev工具中的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);

复制当前选择? - Praveen Kumar Purushothaman
1
@PraveenKumar - 使用 getSelection().toString() 获取当前选定内容。我已编辑了我的答案。 - gilly3

2

我认为,copy命令需要在浏览器上有焦点,当您转到控制台并执行该命令时,当前窗口将失去焦点。但也可能有其他原因,如果我使用setTimeout()命令,它可以正常工作。


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'
    })
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接