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
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
Share Improve this question asked May 1, 2014 at 22:36 Dom ShahbaziDom Shahbazi 7402 gold badges10 silver badges27 bronze badges 1- possible duplicate of chrome.tab.onactivated – rsanchez Commented May 1, 2014 at 23:17
2 Answers
Reset to default 7You have 2 choices here:
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 usechrome.tabs.get
method to grab thetabId
from theonActivated
'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* }); });
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" ], ... }
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).