javascript - 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 位)。
这是一个错误,还是我做错了什么?
解决方案
(以及命名空间下的browser.tabs.query()
大多数 API browser
)返回一个承诺。您需要使用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);
}
})();
请提醒您需要为每个Promise
对象执行此操作,例如,当您想将 API 的结果用作下一次 API 调用的参数时。
(async () => {
const tabs = await browser.tabs.query({"currentWindow": true, "active": true});
const tab = await browser.tabs.query(tabs[0].id);
})();
仅供参考,有关Promise
异步功能的更多详细信息:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
基于回调的样式仅在命名空间下可用chrome
- 它通常与 Google Chrome 的 API 兼容。
推荐阅读
- visual-studio-code - 如何在不出现这些错误的情况下更新 VS Code?
- json - django模型使用json或任何其他方法保存表如何保存在后端
- mesh - 确定非凸多面体的凹度
- javascript - 导入 Bootpag 分页插件
- javascript - 猫头鹰轮播淡入淡出效果无法使用 animate.css
- java - 在 ant 构建期间在具体类上出现抽象类错误
- reactjs - 将 id 属性插入到由 react-emotion 创建的样式化组件中
- javascript - JQUERY ASP.NET MVC - ReferenceError:索引未在 eval 中定义
- dialogflow-es - Google 助理再也找不到我的 Google Action
- c# - Automapper - IQueryable 扩展和内存中的条件映射