Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a listener that fires whenever the user changes tab

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 Answers

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.

like image 165
ComFreek Avatar answered Sep 04 '25 22:09

ComFreek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!