gpt4 book ai didi

javascript - Document.execCommand() 仅适用于开发人员工具

转载 作者:行者123 更新时间:2023-12-03 01:26:19 30 4
gpt4 key购买 nike

我正在尝试将网页的所有链接复制到剪贴板。我试图将所有 anchor 标记加入到一个字符串中,将该字符串放入输入字段中,然后通过 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>

最佳答案

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

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

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);

关于javascript - Document.execCommand() 仅适用于开发人员工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51528733/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com