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

问题描述 投票:0回答:1

[当我在插件的后台脚本中执行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位)。

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

javascript firefox-addon
1个回答
1
投票

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

FYI,有关于Promise和异步功能的更多详细信息:

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

© www.soinside.com 2019 - 2024. All rights reserved.