Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the Chrome extension icon

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...

like image 206
Richard Avatar asked Jun 04 '13 15:06

Richard


1 Answers

Content scripts don't have access to most extension APIs. Instead, you'll need to use message passing to have the content script alert notify the background page of what works needs to be done.

Your content script should send a message using chrome.runtime.sendMessage, and the background page should listen using chrome.runtime.onMessage.addListener:

Content script:

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

Background page:

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
        });
    });
like image 125
apsillers Avatar answered Sep 20 '22 01:09

apsillers