tabs.getCurrent() 结果未定义?

tabs.getCurrent() result is undefined?

不知道为什么当我导航到 amazon.com 或 google.com 并点击浏览器图标进行浏览器操作时,我无法使用 getCurrent() 检索有关当前选项卡的信息。关于我遗漏的任何提示?

清单:

{
  "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"]
  }      
}

背景:

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

这是输出:

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

undefined  background.js:5:7

Firefox 开发版 54(64 位)

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

来自 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.

browserAction.onClicked 事件 returns 活动选项卡,您不需要另一个 API 调用。

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

参见tab parameter for browserAction.onClicked listener

您也可以在 background.js 文件中获取当前活动的选项卡,同时执行

browser.tabs.query({active: true, windowId: browser.windows.WINDOW_ID_CURRENT})
  .then(tabs => browser.tabs.get(tabs[0].id))
  .then(tab => {
    console.info(tab);
  });