gpt4 book ai didi

javascript - 在 Chrome 扩展程序中复制到剪贴板

转载 作者:IT王子 更新时间:2023-10-29 03:03:09 26 4
gpt4 key购买 nike

我正在为 Google Chrome 制作扩展程序,但遇到了麻烦。

我需要在弹出窗口中单击时将只读文本区域的内容复制到剪贴板。有谁知道使用纯 Javascript 而没有 Flash 的最佳方法吗?如果有帮助的话,我还在扩展中加载了 jQuery。我当前的(非工作)代码是...

function copyHTMLCB() {
$('#lb_html').select();
$('#lb_html').focus();
textRange = document.lb_html_frm.lb_html.createTextRange();
textRange.execCommand("RemoveFormat");
textRange.execCommand("Copy");
alert("HTML has been copied to your clipboard."); }

最佳答案

所有功劳都归功于 joelpt,但如果其他人需要在没有 jQuery 的情况下使用纯 javascript(我做到了),这里是他的解决方案的改编版:

function copyTextToClipboard(text) {
//Create a textbox field where we can insert text to.
var copyFrom = document.createElement("textarea");

//Set the text content to be the text you wished to copy.
copyFrom.textContent = text;

//Append the textbox field into the body as a child.
//"execCommand()" only works when there exists selected text, and the text is inside
//document.body (meaning the text is part of a valid rendered HTML element).
document.body.appendChild(copyFrom);

//Select all the text!
copyFrom.select();

//Execute command
document.execCommand('copy');

//(Optional) De-select the text using blur().
copyFrom.blur();

//Remove the textbox field from the document.body, so no other JavaScript nor
//other elements can get access to this.
document.body.removeChild(copyFrom);
}

关于javascript - 在 Chrome 扩展程序中复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3436102/

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