我正在制作一个chrome扩展程序,用户可以在其中按一个按钮,然后将文本复制到剪贴板。我已经编写了HTML和Javascript来做到这一点,并且当我在浏览器中打开HTML文件时,代码可以工作。问题是当我打开扩展名(运行相同的HTML文件)时,该按钮不会将任何文本复制到剪贴板。我确实在我的manifest.json文件中启用了“ clipboardWrite”权限,当我进入“详细信息”>“权限”时,chrome:// extensions也会说“修改您复制并粘贴的数据”。
要尝试解决此问题,我重新加载了扩展名,删除并重新添加了解压缩的文件夹,然后重新启动了计算机;没有一个能解决我的问题。我也已经在多种浏览器中对其进行了测试,但无法在所有浏览器中正常工作。
popup.html:
<!DOCTYPE html><html>
<body>
<script>
/*Function that copies text. This works fine in a browser but not in the extension*/
function clip(string) {
const ta = document.createElement('textarea'); //creates a constant of a textarea
ta.value = string; //adds 'string' parameter into the textarea
ta.setAttribute("id", "temptextarea");
document.body.appendChild(ta); //adds an instance of the textarea
ta.select(); //selects the text in the textarea (may be the issue for chrome extension)
document.execCommand('Copy'); //copies the selected text
document.body.removeChild(ta); //removes the instance of the textarea
}
</script>
<!--Button that copies text.-->
<button onclick="clip('This text gets copied')">Copy Text!</button>
</body>
</html>
manifest.json:
{
"manifest_version": 2,
"name": "My Extenstion Name",
"version": "1.0.0",
"permissions": [
"clipboardWrite"
],
"browser_action": {
"default_popup": "popup.html",
"default_title": "My Extension Name"
}
}
在浏览器选项卡中运行此代码段时,您将获得预期的结果:单击该按钮,它将“复制此文本”复制到剪贴板。无论出于什么原因,当您将这两个文件放入文件夹并上传到chrome:// extenstions时,文本都不会复制到剪贴板。这使我感到困惑,因为从逻辑上讲,它无法在扩展程序中工作的唯一原因是权限不足,但正如我之前所说,它确实具有写入剪贴板的权限。
谢谢!
答案 0 :(得分:0)
此代码不起作用的原因是,如果您使用onclick =“”,则chrome扩展程序会引发异常。在这种情况下,您需要使用事件监听器。