如何使用 Javascript 复制纯文本值

How to copy plain text value from using Javascript

本文关键字:文本 复制 何使用 Javascript      更新时间:2023-09-26
function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}

我在Reddit上找到了这段代码,我认为它会起作用,因为创建一个元素然后选择它然后执行命令"copy"是合乎逻辑的。但我很惊讶它没有,我不知道为什么。

在 Chrome 开发人员控制台上运行此脚本时没有给出任何错误,这是我想要执行它的地方,这正是我不想听到与复制有关的任何 API 作为答案的原因。如果您可以告诉我如何在chrome开发工具上使用API,请随时告诉我。

如果有些事情我遗漏了,或者你有疑问。

没有用户交互,代码将无法工作,如果您尝试从控制台运行它,它将不起作用。

运行代码的唯一方法是将函数绑定到按钮或类似的东西。

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
  }
<button onclick='copytext("some text")'>copy some text!</button>

可以尝试从开发控制台以及按钮调用document.queryCommandSupported("copy")document.queryCommandEnabled("copy")来验证这一点。

谷歌开发者

请参阅底部的已知错误部分。