Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome extension get active tab id in browser action popup

I am writing an extension supposed to catch any kind of redirections through a backgroud page, keep track of them for each tab, and outline them in a browser action for each tab. Thus i want the action popup script to get the active tab's Id to display only datas related to this active tab in the action popup.

I already declared the permission "activeTab" in the manifest.

I tried chrome.tabs.getCurrent(function(tab){}) before noticing in the documentation that the browser actions are mentionned as instance of contexts where tab is undefined. https://developer.chrome.com/extensions/tabs#method-getCurrent

I considered messaging a content script to get the tab id, but i did not find a suitable method to connect a content script and an action popup.

How could i get the active tab's ID in a browser action popup if it is possible ?

like image 439
Link-akro Avatar asked Oct 03 '16 21:10

Link-akro


1 Answers

You need tabs.query:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  var currTab = tabs[0];
  if (currTab) { // Sanity check
    /* do stuff */
  }
});

"Rare cases" are mostly limited to a detached DevTools window being the current window (looks like this case is fixed); should not happen during normal operation.

like image 144
Xan Avatar answered Jan 01 '23 21:01

Xan