Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 592
John McCollum Avatar asked Apr 09 '12 09:04

John McCollum


Video Answer


2 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'
        });
    }
});
like image 128
Rob W Avatar answered Sep 22 '22 01:09

Rob W


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.

like image 30
JoeAndrieu Avatar answered Sep 22 '22 01:09

JoeAndrieu