我正在尝试编写一个可以从剪贴板读取并可以写入剪贴板的chrome扩展程序,但它似乎失败了(尽管类似Firefox的实现也可以使用)
我先请求许可。对于clipboard-read
查询,我得到一个prompt
状态(尽管没有出现chrome提示),但读取失败。对于clipboard-write
查询,我得到一个granted
状态(没有出现任何chrome提示),但是再次写入失败。我不知道我在做什么错。
我仍在开发它,所以我将它作为解压缩扩展名以chrome的形式本地加载。
这是相关代码(background.js):
var g_sWord = "";
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
id: "MyContextMnu",
title: "MyText",
contexts: ["selection"],
});
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
g_sWord = info.selectionText;
switch (info.menuItemId) {
case "MyContextMnu":
navigator.permissions.query({name: "clipboard-read"}).then(result => {
alert("read: " + result.state);
if (result.state == "granted" || result.state == "prompt") {
navigator.clipboard.readText().then(
clipText => {
alert("Read from clipboard successfully: " + clipText);
}).catch(err => {
alert("Failed to read from clipboard: " + err);
});
}
});
navigator.permissions.query({name: "clipboard-write"}).then(result => {
alert("write: " + result.state);
if (result.state == "granted" || result.state == "prompt") {
navigator.clipboard.writeText("Howdy, partner!").then(function() {
alert("Write to clipboard successfully!");
}, function() {
alert("Failed to write to clipboard");
});
}
});
break;
}
});
和manifest.json的相关部分:
"permissions": [
"<all_urls>",
"tabs",
"activeTab",
"contextMenus",
"clipboardRead",
"clipboardWrite"
],
"background": {
"scripts": ["background.js"]
}
预先感谢您的任何想法。