Title: Get previous url from chrome.tabs.onUpdated
Tags: javascript;google-chrome;google-chrome-extension
Question: 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?

Here is the accepted answer: 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 &amp;&amp; changeInfo.url.match(/<regex&gt;/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;
Comment for this answer: What if a tab is closed? I guess you can use `chrome.tabs.onRemoved.addListener`.

Here is another answer: 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
Comment for this answer: `onBeforeNavigate` even only happens when the page reloads. It omits browser's back and forward and client and/or server redirect and `history.pushState()`. So this answer is not correct.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:11/18/15', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<javascript><google-chrome><google-chrome-extension>', 'Title': 'Get previous url from chrome.tabs.onUpdated', 'ViewCount': 2321, 'id': 33770825, 'user_AboutMe': '', 'user_AccountId': 1690387.0, 'user_DisplayName': 'jianweichuah', 'user_Reputation': 1397.0, 'user_Views': 280.0, 'user_id': 1552862.0}}