Search code examples
windowsgoogle-chromegoogle-chrome-extensioniconsbrowser-action

Setting browserAction icon in a concrete Chrome window


I want to set different browserAction icons in different windows. The only method I found for this is:

http://developer.chrome.com/extensions/browserAction.html#method-setIcon

But it doesn't take a context. It changes icon in every window. I know it is somehow possible, because adBlock do this. Do anyone know how?


Solution

  • Here is my solution, I hope it will be helpful:

    function setIcon(state, getIconNameCallback) {
    
        // we need to set the icon globally first, 
        // to avoid blinking to default icon
    
        chrome.windows.getLastFocused(null, function(window) {
            chrome.tabs.getSelected(null, function(tab) {
                chrome.browserAction.setIcon({
                    'path': getIconNameCallback(state, tab.url)
                });
            });
        });
    
        // then we must set the icon for each tab,
        // without that the extension wont behave
        // properly with multiple windows
    
        chrome.tabs.query({}, function(tabs) {
            for (var i = 0; i < tabs.length; i++) {
                chrome.browserAction.setIcon({
                    'path': getIconNameCallback(state, tabs[i].url), 
                    'tabId': tabs[i].id
                });
            }
        });
    
    }