Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Get previous url from chrome.tabs.onUpdated


The chrome.tabs API provides us a way to listen to the change in the url for each tab. https://developer.chrome.com/extensions/tabs#event-onUpdated

I can add a listener like this:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
    // changeInfo.url gives the updated url if it's changed
    // tab.url gives the current url for the tab
});

What I'd like to do is to detect if the domain changes and perform some actions if it does.

For example if the url changes from https://google.com/abc to https://google.com do something.

Does anyone know the best way to do this?


Solution

  • Looks like there is no good way to get the previous url from the chrome.tabs API. What I'm currently doing is to have a hashmap that keeps track of the previous url for each tabId like this:

    var tabIdToPreviousUrl = {};
    
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
        if (changeInfo.url && changeInfo.url.match(/<regex>/g)) {
            var previousUrl = "";
            if (tabId in tab) {
                previousUrl = tabIdToPreviousUrl[tabId];
            }
            // If the domain is different perform action.
            if (previousUrl !== changeInfo.url) {
                // do something
            }
            // Add the current url as previous url
            tabIdToPreviousUrl[tabId] = changeInfo.url;
        }
    });