Question

I have an extension which detects every time a webpage is changed using the chrome.tabs.onUpdated event listener. The code within this event listener performs certain tasks depending on the page URL. I also want to perform these tasks when switching from one tab to another, but this doesnt fire the chrome.tabs.onUpdated event listener, so instead im listening for the tab change using chrome.tabs.onActivated.

The problem is using chrome.tabs.onActivated does not give me the URL of the tab i have just switched to, which i need. Can anybody help me with this?

Thanks

Was it helpful?

Solution

You have 2 choices here:


  1. Using two events (Not as good):

    IN ADDITION to the chrome.tabs.onUpdated event that you're ALREADY using for your other functionality (you describe above), you could ALSO use chrome.tabs.get method to grab the tabId from the onActivated's event object, then pass to a function. But, IMHO option 2 is a better one for you in this case:

        chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
          //... whatever other stuff you were doing anyway
        });
    
        chrome.tabs.onActivated.addListener(function(evt){ 
          chrome.tabs.get(evt.tabId, function(tab){ 
            alert(tab.url);  //the URL you asked for in *THIS QUESTION*
          }); 
        });
    
  2. Use only the onUpdated event once (better):

    Do both your other stuff and what you're looking for in your question in the same event:

        chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
          //... whatever other stuff you were doing anyway
          chrome.tabs.getSelected(null, function(tab) {
            alert(tab.url);  //the URL you asked for in *THIS QUESTION*
          });
        });
    

.

Of course, don't forget:


your manifest.json file should have the "tabs permission":

  {
    "name": "My extension",
    ...
    "permissions": [
      "tabs"
    ],
    ...
  }

OTHER TIPS

You have the right idea in using chrome.tabs.onActivated. When you get the event for onActivated, you should also get the activeInfo object, which should include the tab id. With this, you can then do chrome.tabs.get(), passing in that tab id, and the tab object passed to the callback of chrome.tabs.get() should include the URL (though note you will need the "tabs" permission in your manifest to get the URL).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top