我对 chrome 扩展安装/更新事件有疑问。如果我在后台脚本的顶级代码中添加 onInstalled 事件侦听器,我的事件侦听器是否会在某个时间范围内捕获该事件?
我问这个,因为我的演示表明,如果我有一些逻辑在我挂钩 onInstalled 侦听器之前执行,它看起来永远不会执行,就像该事件同时发生一样。
有人可以在后台脚本中的其他逻辑的上下文中向我详细解释此事件的工作原理,或者指出一些文档,因为我找不到任何有用的东西。
谢谢!
更新@Noam Hacker:由于公司政策,我不能在这里发布任何真实代码,但我有一些伪代码可以说明我的问题:
/**
* setup in which I miss onInstalled event
*/
function firstLogicThatRunsOnBackgroundLoad() {
// perform some logic
// perform some asynchronous operations via generators and promises
// which can take a while
chrome.runtime.onInstalled.addListener(function (details) {
if (details.reason == "install") {
// this logic never gets executed
} else if(details.reason == "update") {
// perform some logic
}
});
}
/**
* setup in which I catch onInstalled event
*/
function firstLogicThatRunsOnBackgroundLoad() {
chrome.runtime.onInstalled.addListener(function (details) {
if (details.reason == "install") {
// this logic executes
} else if(details.reason == "update") {
// perform some logic
}
});
// perform some logic
// perform some asynchronous operations via generators and promises
// which can take a while
}
原文由 vladamon 发布,翻译遵循 CC BY-SA 4.0 许可协议
onInstalled
侦听器在这些情况下捕获事件:由于这都是异步的,它将在后台发生,并且根据文档,在任何这些情况下都会立即触发。复习异步编程以对此有所了解。
文档链接
根据您的问题,您似乎需要帮助以正确的顺序执行代码。 此答案 为您的案例提供了一个有用的框架(使用
reason
属性)。