更改Chrome扩展程序图标

Ric*_*ard 13 google-chrome google-chrome-extension google-chrome-devtools

我是谷歌Chrome扩展程序的新手,我为我们的网站创建了一个检查您所在页面内容的网站,并根据该内容获取服务器的ID(我们有一个包含4个虚拟机的webfarm).现在使用服务器ID,我不想更改扩展图标以显示那里的数字.我尝试过使用:

chrome.browserAction.setIcon({
    path : folder + icons[2],
    tabId: tab.id
});
Run Code Online (Sandbox Code Playgroud)

但是我收到了这个错误: chrome.browserAction is not available: You do not have permission to access this API. Ensure that the required permission or manifest property is included in your manifest.json.

我已经尝试使用谷歌搜索错误并一直在搜索文档,但无法找到导致此问题的原因...

aps*_*ers 21

内容脚本无权访问大多数扩展API.相反,您需要使用消息传递让内容脚本警报通知后台页面需要完成哪些工作.

您的内容脚本应使用发送消息chrome.runtime.sendMessage,后台页面应使用chrome.runtime.onMessage.addListener以下方式监听:

内容脚本:

if(shouldChangeIcon) {
    // send message to background script
    chrome.runtime.sendMessage({ "newIconPath" : folder + icons[2] });
}
Run Code Online (Sandbox Code Playgroud)

背景页面:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        // read `newIconPath` from request and read `tab.id` from sender
        chrome.browserAction.setIcon({
            path: request.newIconPath,
            tabId: sender.tab.id
        });
    });
Run Code Online (Sandbox Code Playgroud)