3

I'm creating a Chrome Extension and trying to get a function to fire everytime the user changes tab. I've been looking at the listeners in the webRequest API, and the chrome.tabs but couldn't figure what to use, and what not to use.

The only information I need from the tab is its url.

1 Answers1

3

Take a look at chrome.tabs.onActivated:

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.
Google Documentation

chrome.tabs.onActivated.addListener(function(activeInfo) {
    chrome.tabs.get(activeInfo.tabId, function (tab) {
        mySuperCallback(tab.url);
    });
});

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, updatedTab) {
    chrome.tabs.query({'active': true}, function (activeTabs) {
        var activeTab = activeTabs[0];

        if (activeTab == updatedTab) {
            mySuperCallback(activeTab.url);
        }
    });
});

function mySuperCallback(newUrl) {
    // ...
}

It definitely works in background pages (as Locercus confirmed in a comment), but please consider using event pages (stable since Chrome 22) instead.

Community
  • 1
  • 1
ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • I took a look at it. But how would i go around getting the URL, when it has been set. I need to get the event to fire whenever you go to a new URL in your active tab, too. –  Aug 10 '13 at 14:26
  • @Locercus Use [chrome.tabs.onUpdated](https://developer.chrome.com/extensions/tabs.html#event-onUpdated) and check whether the changed tab is the active tab in the current window *and* whether the URL has been changed . – ComFreek Aug 10 '13 at 14:30
  • Could you give me an example in a context? Where'd I place the onActivated listener? I'm pretty sure it won't work in popup.js –  Aug 10 '13 at 14:32
  • @Locercus This should actually work in a background script and in your popup (though I'm not 100% sure. I haven't developed chrome exts for a while now). – ComFreek Aug 10 '13 at 14:45
  • So you're telling me that I can put this in either popup.html or background.html? –  Aug 10 '13 at 14:46
  • @Locercus Just try it ;) As I said, I'm not 100% sure and I cannot find documentation about that right now. – ComFreek Aug 10 '13 at 14:47
  • **Note to future readers**: It works if you put it in background.js and use the background feature in manifest.json. Take a look at this page. http://developer.chrome.com/extensions/background_pages.html –  Aug 10 '13 at 14:53
  • Great explanation and nice code. Thanks. When I run this, however, it never drops into the mySuperCallback routine. Any thoughts? – itchyspacesuit Feb 18 '17 at 17:06