Firefox browser.tabs.query({})。then()未定义

时间:2020-04-19 17:36:19

标签: javascript firefox-addon

当我在插件的后台脚本中执行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 docs中未提及:

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

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

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

1 个答案:

答案 0 :(得分:3)

browser.tabs.query()(以及browser名称空间下的大多数API)返回一个诺言。您需要使用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);
  }
})();

请注意,例如,当您要将来自API的结果用作下一个API调用的参数时,需要对每个Promise对象执行此操作。

(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兼容。