javascript 为什么 document.execCommand("copy") 在我的 chrome 扩展的内容脚本中不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15005059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why document.execCommand("copy") doesn't work in content script of my chrome extension?
提问by Hank X
I want to write some data in to clipborad from a chrome extension which I'm creating. In the manifest file i gave permissions to both clipboardRead and clipboardWrite.
我想将一些数据从我正在创建的 chrome 扩展程序写入剪贴板。在清单文件中,我授予了clipboardRead 和 clipboardWrite 的权限。
i use this function which i found here
我使用我在这里找到的这个功能
but it doesn't work. seems that "document.execCommand('copy');" can not work.
但它不起作用。似乎是“document.execCommand('copy');” 不能工作。
i write all of these codes in content script.
我在内容脚本中编写了所有这些代码。
thx manifest:
thx 清单:
{
"manifest_version":2,
"name":"easyCopy",
"description":"just a small toll",
"version":"1.0.0",
"permissions":[
"clipboardWrite", "http://*/*", "clipboardRead"
],
"content_scripts":[
{
"matches":["http://*/*"],
"js":["jquery-1.9.1.min.js", "main_feature.js"]
}
],
"background":{
"persistent":false,
"page":"background.html"
}
}
main_feature.js:
main_feature.js:
copyOrderId();
function copyOrderId() {
$(".order-num").click(function () {
var curOrderNum = $(this).text();
copyTextToClipboard(curOrderNum);
// chrome.extension.sendMessage({method:"copy", content:curOrderNum}, function (response) {
// clog(response);
// });
});
}
function copyTextToClipboard(text) {
var copyFrom = $('<textarea/>');
copyFrom.text(text);
$('body').append(copyFrom);
copyFrom.select();
document.execCommand('copy', true);
copyFrom.remove();
}
function clog(message) {
console.log(message);
}
the background.html is just a blank page with basic html body.
background.html 只是一个带有基本 html 正文的空白页面。
回答by Hank X
Thanks everyone, I ended up using this:
谢谢大家,我最终使用了这个:
document.execCommand
can not work in content script.
Instead, I send data to background page and then run the "copyTextToClipboard" function.
document.execCommand
不能在内容脚本中工作。相反,我将数据发送到后台页面,然后运行“copyTextToClipboard”功能。
Notice that you must put your JavaScript into single .js file instead of mixing it with background.html.
请注意,您必须将 JavaScript 放入单个 .js 文件中,而不是将其与 background.html 混合。
Additionally, the textarea must have an id
or class
property.
此外,textarea 必须具有id
orclass
属性。