admin管理员组

文章数量:1404924

The chrome.tabs API provides us a way to listen to the change in the url for each tab.

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 to do something.

Does anyone know the best way to do this?

The chrome.tabs API provides us a way to listen to the change in the url for each tab. https://developer.chrome./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./abc to https://google. do something.

Does anyone know the best way to do this?

Share Improve this question asked Nov 18, 2015 at 2:29 jianweichuahjianweichuah 1,4171 gold badge11 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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;
    }
});

Try this:

var previousUrl = "";

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
  //Your code here
});

chrome.webNavigation.onBeforeNavigate.addListener(function(object){ 
 chrome.tabs.get(object.tabId, function(tab){ previousUrl = tab.url;});
});

Note that you will need "webNavigation" listed in your manifest.json

本文标签: javascriptGet previous url from chrometabsonUpdatedStack Overflow