Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the previous URL of a tab?

When writing a Chrome extension, given a tab, how can I get the URL of the previously-visited page in that tab? i.e. the url that will appear in the omnibar after I hit "back"?

like image 752
Oak Avatar asked Jan 11 '23 01:01

Oak


1 Answers

Since I could not find any API approach, I just applied vux777's suggestion above: every time a page loads I store a mapping from its id to its URL. Then when I want to find the previous page of a tab, I can search for it there.

So, storage:

chrome.webNavigation.onCommitted.addListener(function (data) {
  if (data.frameId !== 0) {
      // Don't trigger on iframes
      return;
  }

  var tabIdToUrl = {};
  tabIdToUrl[data.tabId.toString()] = data.url;
  chrome.storage.local.set(tabIdToUrl);
});

And retrieval:

chrome.storage.local.get(tabId, function (item) {
  var url = item[tabId];
  ...
});
like image 99
Oak Avatar answered Jan 21 '23 13:01

Oak