0

I am trying to get the url of tab which is currently there and it should change as soon as I change my tab.My code is this:

var y;
    chrome.tabs.getSelected(null, function(tab) {
    alert("current:"+tab.url);
    y=tab.url;
});

The problem is it only gives the Url of the first page when I load the extension i.e chrome://extensions and doesn't change its value when I change the tabs .I know I am doing something wrong .I am new to this and probably not able to understand it properly.What to do?

  • I believe that is deprecated, see this for an answer -> http://stackoverflow.com/questions/6132018/how-can-i-get-the-current-tab-url-for-chrome-extension – adeneo Jul 20 '14 at 17:55
  • I know that's deprecated ,but even if i use current or query my question remains the same!! – user3668325 Jul 20 '14 at 18:00

1 Answers1

0

Your code is only run once; what do you expect?

You should register listeners to appropriate events to react to changes.

  • chrome.tabs.onActivated will tell you when tabs are switched.
  • chrome.tabs.onUpdated will, among other things, fire when the tab's URL changes.
  • You might also want to listen to chrome.windows.onFocusChanged

Example:

chrome.tabs.onActivated.addListener( function(activeInfo){
  chrome.tabs.get(activeInfo.tabId, function(tab){
    y = tab.url;
  });
});

All in all, give the docs another read.

Xan
  • 74,770
  • 16
  • 179
  • 206