17

I'm new to Google Chrome extensions and I've created one for our website that checks the content of the page you're on and bases on that gets the ID of the server (we have a webfarm with 4 VM's). Now using the server ID, I wan't to change the extension icon to show the number there. I've tried using :

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

But I'm getting this error: 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.

I've tried googling the error and have been searching through the documentation, but can't find what is causing this...

4

2 回答 2

30

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

您的内容脚本应该使用 发送消息chrome.runtime.sendMessage,并且后台页面应该使用 监听chrome.runtime.onMessage.addListener

内容脚本

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

背景页面

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
        });
    });
于 2013-06-04T17:48:01.180 回答
3
Unchecked runtime.lastError: Icon invalid.

以防万一任何人在更改 browserAction 图标时遇到上述错误,我需要澄清:并非所有尺寸的图像都支持,但 48x48 是有效的。

于 2020-01-07T11:00:12.197 回答