Anonymous
Anonymous

Reputation: 4630

Google chrome extension - toggle icon for all tabs simultaneously?

I was able to toggle my extension icon for a single active tab before:

chrome.browserAction.onClicked.addListener(function(tab) {
  toggle = !toggle;
  if(toggle){
    active_tab=tab.id;
    chrome.browserAction.setIcon({path: "on.png", tabId:tab.id});
  }
  else{
    chrome.browserAction.setIcon({path: "off.png", tabId:active_tab});
  }
});

But how do I change that icon for all tabs at once... including the new tabs?

Is there an easy way of doing this?

Upvotes: 3

Views: 583

Answers (2)

Makyen
Makyen

Reputation: 33366

You do this by not supplying a tabId property on the Object you pass to browserAction.setIcon(). The documentation for tabId states that it is optional and that if specified it:

Limits the change to when a particular tab is selected. Automatically resets when the tab is closed.

If you don't supply tabId, then what you specify for path or imageData applies to all tabs. This is the standard way that the methods of browserAction, which change the properties of the button, work.

Thus, in your case it would be:

chrome.browserAction.onClicked.addListener(function(tab) {
  toggle = !toggle;
  if(toggle){
    active_tab=tab.id;
    chrome.browserAction.setIcon({path: "on.png"});
  }
  else{
    chrome.browserAction.setIcon({path: "off.png"});
  }
});

Upvotes: 3

Anonymous
Anonymous

Reputation: 4630

Solved by adding another listener that activates on switching tabs.

chrome.browserAction.onClicked.addListener(function(tab) {
    toggle = !toggle;
    if(toggle){
        chrome.browserAction.setIcon({path: "on.png", tabId:tab.id});
    }
    else{
        chrome.browserAction.setIcon({path: "off.png", tabId:tab.id});
    }
});

chrome.tabs.onActivated.addListener(function (tab) {
    if(toggle){
        chrome.browserAction.setIcon({path: "on.png", tabId:tab.id});
    }
    else{
        chrome.browserAction.setIcon({path: "off.png", tabId:tab.id});
    }
});

Upvotes: 0

Related Questions