当我在插件的后台脚本中执行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位)。
这是一个错误,还是我做错了什么?
答案 0 :(得分:3)
browser.tabs.query()
(以及browser
名称空间下的大多数API)返回一个诺言。您需要使用await
或Promise.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兼容。