无法使用chrome.commands.onCommand listener

时间:2017-01-12 18:41:54

标签: javascript google-chrome-extension

正如标题所说,在我加载扩展程序后,后台加载(由警报消息显示),但onCommand无法正常工作。我将扩展程序加载到Chrome并且只运行了一次(这不是第一次加载扩展程序时,但是当我点击热键时)。

我正在使用金丝雀。

Background.js

alert('a');
chrome.commands.onCommand.addListener(function (command) {
    alert('clicked');
    if (command === "toggle-feature") {
        chrome.tabs.query({}, function (tabs) {
            alert('tabs');
            chrome.tabs.executeScript(tabs[1].id, {"file": "content_script.js"});
        });
    }

});

的manifest.json

{
    "manifest_version": 2,
    "name": "Extractor",
    "version": "1",
    "description": "Extract",
    "icons": {
        "16": "logo16.png",
        "48": "logo48.png",
        "128": "logo128.png"
    },
    "page_action": {
        "default_icon": {
            "16": "logo16.png",
            "48": "logo48.png",
            "128": "logo128.png"
        },
        "default_title": "Extractor"
    },
    "background": {
        "scripts": ["background.js"],
        "persistent": true
    },
    "permissions": [
        "tabs",
        "https://www.msn.com/*",
        "activeTab",
        "http://*/*",
        "https://*/*"    
    ],
    "commands": {
        "toggle-feature": {
            "suggested_key": {
                "default": "Ctrl+Shift+1",
                "windows": "Ctrl+Shift+2"
            },    
            "description": "Extract now"
        }
    }    
}

我试图删除并更改持久值,但没有运气。

我猜这可能是Chrome的一个更基本的问题。 我在开发者模式下禁用了缓存,并且还删除了然后安装了扩展程序。

1 个答案:

答案 0 :(得分:0)

可能尝试将 content_script.js 注入当前窗口的活动标签中。您当前从chrome.tabs.query()获取的列表将包括所有打开的窗口中打开的所有选项卡。您当前的代码将尝试将该脚本注入该列表中第二个列出的任何选项卡。

您应该将chrome.tabs.query()chrome.tabs.executeScript()更改为:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    //The active tab in the current window with be tabs[0].
    chrome.tabs.executeScript(tabs[0].id, {"file": "content_script.js"});
});

我只在Chrome的发布版本中测试了这个,而不是Canary。如果您仍然在Canary遇到问题,我建议您在Chrome的发布版本上进行测试,以便将任何特定于Canary的问题与您的扩展程序隔离开来。在Chrome的发布版本中使用它之后,请尝试使用Canary。