从/写入剪贴板的chrome扩展失败

时间:2018-11-07 23:32:14

标签: javascript google-chrome-extension

我正在尝试编写一个可以从剪贴板读取并可以写入剪贴板的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"]
}

预先感谢您的任何想法。

0 个答案:

没有答案