最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get previous url from chrome.tabs.onUpdated - Stack Overflow

programmeradmin3浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论