tabs.getCurrent() result is undefined?

2019-02-15 17:46发布

问题:

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

回答1:

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.



回答2:

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);
  });