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

How to create a nodejs archetype from maven

eclipse node.js maven maven-plugin maven-eclipse-plugin

The current default nature of the project is 'org.eclipse.jdt.core.javanature' (Java nature) But I want change the default nature of the project to org.nodeclipse.ui.NodeNature' (nodejs).

JAVA Ignore commented out xml tags

java xml dom xml-parsing

While i'm parsing an XML document, i get commented out code as a node (which is a bad idea to begin with), i wan't to know when we have a commented out node/bulk and not to parse it.