9

Not sure why I cannot retrieve info about current tab using getCurrent() when I navigate to, say, amazon.com or google.com and hit the browser icon for a browser action. Any hints on what I am missing?

MANIFEST:

{
  "name": "testGetCurrentTab",
  "version":  "1.0",
  "description":  "",
  "manifest_version": 2,

  "icons": {
    "48": "icons/icon-48.png"
  },

  "permissions": [
      "tabs",
      "<all_urls>"
  ],

  "browser_action": {
      "default_icon": "icon/icon-32.png"
  },

  "background": {
      "scripts": ["background.js"]
  }      
}

BACKGROUND:

function displayInfo() {

  function onGot(tabInfo) {
    console.log('Inside onGot() ...');
    console.log(tabInfo);
  }

  function onError(error) {
    console.log(`Error: ${error}`);
  }

  var gettingCurrent = browser.tabs.getCurrent();
  gettingCurrent.then(onGot, onError);
}

browser.browserAction.onClicked.addListener(displayInfo);

Here is the output:

Inside onGot() ...  background.js:4:7

undefined  background.js:5:7

Firefox Dev Edition 54 (64bit)

https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/getCurrent

Cam U
  • 340
  • 3
  • 10

2 Answers2

19

You can get the currently active tab in the background.js file as well when doing

browser.tabs.query({active: true, windowId: browser.windows.WINDOW_ID_CURRENT})
  .then(tabs => browser.tabs.get(tabs[0].id))
  .then(tab => {
    console.info(tab);
  });
evandrix
  • 6,041
  • 4
  • 27
  • 38
kesselborn
  • 533
  • 5
  • 7
17

From MDN tabs.getCurrent():

Get a tabs.Tab containing information about the tab that this script is running in.

You can call this function in contexts where there is a browser tab, such as an options page. If you call it from a background script or a popup, it will return undefined.

The browserAction.onClicked event returns the active tab, you do not need another API call.

browser.browserAction.onClicked.addListener(function(tab) {
 console.log(tab)
})

See the tab parameter for browserAction.onClicked listener.

Community
  • 1
  • 1
Daniel Herr
  • 19,083
  • 6
  • 44
  • 61
  • Thanks for reminding me of that. I actually had been trying to use getCurrent with a content script, but still getting undefined. I switched to background script for posting the question here, and in the process forgot that it won't work in a background script. It seems the contexts in which it can be used are very limited. – Cam U May 01 '17 at 08:03
  • so What's the solution ? i didnt found example demo code of tabs.getCurrent in internet so far... – questionasker Jun 27 '17 at 23:45
  • 3
    "This event will not fire if the browser action has a popup." – T3rm1 Jun 06 '18 at 12:24