简体   繁体   中英

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?

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"});
  }
});

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});
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM