0

I need a page action popup icon to appear when a tab has a specific URL in the address bar.

I have this in my background page

chrome.tabs.query({url:"MYURL.COM"} , function(tab)
            {
                for(i=0;i<tab.length;i++)
                {
                    console.log(tab[i].id);
                    chrome.pageAction.show(tab[i].id);
                }

            });

The popup shows whenever I reload the extension but as soon as user refreshes, it goes away and doesn't come back.

Alex
  • 460
  • 1
  • 5
  • 16

3 Answers3

4

The reason is that the background.js page is only loaded once, so you need to add a listener to every time the page tab is updated to check whether the page action should be shown, something like this:

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    if (tab.url.indexOf("MYURL.COM") > -1) {
        chrome.pageAction.show(tabId);
    }
});

There is no reason to iterate over each tab as you have done.

Adam Ayres
  • 8,732
  • 1
  • 32
  • 25
3

As Adam has already said, the tabs.onUpdated event is the way to do it.

Anyway, it [seems like I'm not the only one who experienced that the tabs.onUpdated event doesn't always fire when it should - even when waiting for complete status.

So if you're having the same issue, you might want to try my modified version that has proven reliable for me 100%.

chrome.tabs.onUpdated.addListener(function(tabId, change) {
    if (change.status == "complete") {
        chrome.tabs.query({active: true}, function(tabs) {
            var tab = tabs[0];
            // Now do stuff with tab .. Eg:
            if (tab.url.indexOf("MYURL.COM") > -1) {
                chrome.pageAction.show(tab.id); } 
            else {
                chrome.pageAction.hide(tab.id); }
        });
    }   
});
Community
  • 1
  • 1
eyecatchUp
  • 10,032
  • 4
  • 55
  • 65
0

Use chrome.tabs.onUpdated to listen to new tabs and tab reloads of the domain you are interested in.

abraham
  • 46,583
  • 10
  • 100
  • 152