首页 > 解决方案 > Firefox browser.tabs.query({}).then() 未定义

问题描述

当我这样做browser.tabs.query({"currentWindow": true, "active": true}).then(onCall, onError);let querying = browser.tabs.query({"currentWindow": true, "active": true}); querying.then(onCall, onError);在我的插件的后台脚本中时,Firefox 抱怨说

Unchecked lastError value: Error: browser.tabs.query(...) is undefined

当我用以下内容替换同一行时,它将按预期工作,尽管Firefox API 文档中没有提到这一点:

browser.tabs.query({"currentWindow": true, "active": true}, function(tabs){
        onCall(tabs); 
      });

我的 Firefox 版本在 Ubuntu 上是 75.0(64 位)。

这是一个错误,还是我做错了什么?

标签: javascriptfirefox-addon

解决方案


(以及命名空间下的browser.tabs.query()大多数 API browser)返回一个承诺。您需要使用awaitPromise.prototype.then()从承诺中提取“已解决”的值。例如:

browser.tabs.query({"currentWindow": true, "active": true})
  .then(onCall)
  .catch(onError);

或者:

(async () => {
  try {
    const tabs = await browser.tabs.query({"currentWindow": true, "active": true});
    onCall(tabs);
  }
  catch(error) {
    onError(error);
  }
})();

请提醒您需要为每个Promise对象执行此操作,例如,当您想将 API 的结果用作下一次 API 调用的参数时。

(async () => {
  const tabs = await browser.tabs.query({"currentWindow": true, "active": true});
  const tab = await browser.tabs.query(tabs[0].id);
})();

仅供参考,有关Promise异步功能的更多详细信息:

基于回调的样式仅在命名空间下可用chrome- 它通常与 Google Chrome 的 API 兼容。


推荐阅读