首页 > 解决方案 > Document.execCommand() 仅适用于开发人员工具

问题描述

我正在尝试将网页的所有链接复制到剪贴板。我正在尝试将所有锚标记加入一个字符串,将该字符串放入一个输入字段,然后复制它,document.execCommand("copy")但不知何故document.execCommand("copy")只能在浏览器开发人员工具中使用。我希望它在网页中加载的脚本中工作。请帮助我,在此先感谢。

var
body = document.querySelector("body"),
input = document.createElement("textarea"),
a = document.getElementsByTagName("a"),
list = [],
anchor = document.createElement("a");
for (let i = 0; i < a.length; i++){
    list.push(a[i]);
};
list = list.join("\r\n");
input.value = list;
input.setAttribute("readonly", "");
input.style = "position: absolute; left: -9999px;";
body.appendChild(input);
input.select();
document.execCommand('copy');
body.removeChild(input);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>test</title>
    </head>
<body>
    <a href="http://ali.com">sample link</a>
    <script src="script.js"></script>
</body>
</html>

标签: javascripthtmlanchordeveloper-toolsexeccommand

解决方案


需要注意的是,只有在用户调用操作execCommand('copy')的上下文中才能可靠地工作。换句话说,如果你想将数据复制到剪贴板,这应该作为用户点击按钮的副作用来完成。

例如,您可以按如下方式修改您的脚本 - 将调用带到execCommand()click 事件处理程序内部,以实现所需的复制到剪贴板行为:

var
body = document.querySelector("body"),
input = document.createElement("textarea"),
a = document.getElementsByTagName("a"),
anchor = document.createElement("a");

input.setAttribute("readonly", "");

// Added a copy button for the purpose of this demonstration
var copyButton = document.createElement("button")
copyButton.innerText = 'Copy'

// The event in which the copy to clip board will occour
copyButton.addEventListener('click', () => {

    // This code is in the context of a user 'click' action 
    var list = []
    for (let i = 0; i < a.length; i++){
        list.push(a[i]);
    };
    list = list.join("\r\n");

    body.appendChild(input);
    input.value = list;
    input.focus();
    input.select();

    // exec copy command is now being called in the context of 
    // a user invoked interaction (ie click), so it should work
    // as expected
    if(document.execCommand('copy')) {
        console.log('copy success')
    }
    else {
        console.log('copy failed')
    }
    body.removeChild(input);
})

body.appendChild(copyButton);

推荐阅读