Using chrome.browserAction.setPopup per tab

I'm writing a Chrome extension which dynamically changes the content of the popup window based on the current URL.

I'm doing something like this in background.js, which works fine:

if(domains.contains(request.url)){
    chrome.browserAction.setPopup({
        popup: "tracking.html"
    });
}else{
    chrome.browserAction.setPopup({
        popup: "nottracking.html"
    });
}

The problem is that if I switch tab, the content of the popup stays the same between tabs. What's the correct strategy to deal with this?

  • Hook into the tab change event somehow (if such a possibility exists)?
  • Limit the change of popup contents to the current tab? (I did notice that there's an optional tabId parameter for chrome.browserAction.setPopup, but the docs are a bit scant)
  • Something else?

All help very much appreciated!

Answers


Option 1, bind an event listener:

Use chrome.tabs.onUpdated to listen for URI changes, followed by chrome.browserAction.setPopup with a given tabId to set the popup for the given tab. For example:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (domains.contains(tab.url)) {
        chrome.browserAction.setPopup({
            tabId: tabId,
            popup: 'tracking.html'
        });
    } else {
        chrome.browserAction.setPopup({
            tabId: tabId,
            popup: 'nottracking.html'
        });
    }
});

Simply pass the TabId to the setPopup call. http://code.google.com/chrome/extensions/browserAction.html

I do this in my background page all the time:

chrome.browserAction.setPopup({"tabId":data.tabId,"popup":url});

Works like a charm.


The setpopup parameter's object now supports a tabId value. You'll need to get the numeric id of the current tab first. This does not require additional permissions.

chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
    var url = domains.contains(request.url) ? "tracking.html" : "nottracking.html";
    chrome.browserAction.setPopup({
       popup: url,
       tabId: tabs[0].id
    });
});

Need Your Help

Find next Friday at 5pm from one time zone to another

iphone nsdate nsdatecomponents nstimezone

I have an NSDate with a NZDT timezone and I need to find the next Friday at EST timezone. I have searched and have used NSDateComponents to generate dates but the timezone change is messing me up.

How can I let a table's body scroll but keep its head fixed in place?

javascript html css html-table

I am writing a page where I need an HTML table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matte...