Noah Watkins
Noah Watkins

Reputation: 5540

Chrome tabs.onActivated updating only current tab

I have a basic chrome extension that fires when the user switches to a new active tab. In the background page the URL is examined and the extension icon changes based on the URL.

chrome.tabs.onActivated.addListener(function(tabInfo) {
  chrome.tabs.get(tabInfo.tabId, function(tab) {
    update_tab(...)
  });
});

This works fine, but the problem I am facing is that by the time the function fires and the decision is made to update the icon, the user can switch tabs again, but the icon is changed based on the previous tab.

How can I handle this more reliability?

Upvotes: 2

Views: 1446

Answers (2)

Xan
Xan

Reputation: 77523

You can have per-tab browser action icons, so you don't need to track tab switching.

If you use chrome.browserAction.setIcon to update your icon, it takes an optional tabId parameter. Same applies to setTitle.

If you do this, you need not worry about tab activations; onUpdated will inform you of URL changes.

Upvotes: 1

Gideon Pyzer
Gideon Pyzer

Reputation: 24018

You could try adding the onUpdated listener too:

chrome.tabs.onUpdated.addListener(function(tabInfo) {
  chrome.tabs.get(tabInfo.tabId, function(tab) {
    update_tab(...)
  });
});

Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set. https://developer.chrome.com/extensions/tabs

Upvotes: 1

Related Questions