vla*_*mon 7 javascript google-chrome google-chrome-extension
我对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
}
Run Code Online (Sandbox Code Playgroud)
onInstalled
侦听器在以下情况下捕获事件:
首次安装扩展程序时,将扩展程序更新到新版本以及将Chrome更新到新版本时。
由于这都是异步的,因此它将在后台发生,并且根据文档,在任何这些情况下都会立即触发。复习异步编程以对此有所了解。
根据您的问题,您似乎需要帮助以正确的顺序执行代码。该答案为您的案例提供了一个有用的框架(使用reason
属性)。
chrome.runtime.onInstalled.addListener(function(details){
if(details.reason == "install"){
//call a function to handle a first install
}else if(details.reason == "update"){
//call a function to handle an update
}
});
Run Code Online (Sandbox Code Playgroud)
我也需要弄清楚这一点。虽然我没有找到任何权威的东西,但我确实console.time()
在我的背景脚本中抛出了一些语句。
代码是这样的:
console.time('onInstall event');
console.time('first function');
chrome.runtime.onInstalled.addListener(details => {
console.timeEnd('onInstall event');
});
// 7 module imports
someSyncFunction() // console.timeEnd('first function') is called in the first line in this function
Run Code Online (Sandbox Code Playgroud)
然后我只是加载/重新加载了扩展(在开发模式下解压缩)几次。 onInstall
在前 50 毫秒内似乎非常可靠地触发,而第一个功能发生在前 50 毫秒内。结果如下:
(First function, onInstall event)
(.282ms, 47.2ms)
(.331ms, 45.3ms)
(.327ms, 49.1ms)
(.294ms, 45.9ms)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5872 次 |
最近记录: |