2016-11-15 172 views
2

我有一個關於鉻擴展安裝/更新事件的問題。如果我在後臺腳本的頂級代碼中添加onInstalled事件偵聽器,是否有一個時間框架,其中我的事件偵聽器將捕獲該事件?鉻擴展onInstalled事件

我在問這個問題,因爲我的演示表明,如果我在掛接安裝的偵聽器之前執行了一些邏輯,它看起來像它永遠不會執行,就像事件同時發生一樣。

有人可以向我解釋這個事件是如何工作的,在後臺腳本中的其他邏輯的背景下,或者指向我的一些文檔,因爲我一直沒有找到有用的東西。

謝謝!

更新@Noam黑客:由於公司政策,我不能在這裏發表任何實際的代碼,但我有我的說明一些問題的僞代碼:

/** 
* 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 
} 
+0

你有沒有背景腳本的示例代碼? –

+0

如果將主邏輯放入偵聽器函數中,該怎麼辦? 'chrome.runtime.onInstalled.addListener(函數(詳細){ //執行您想要先執行的邏輯... //安裝/更新邏輯... } –

+0

@NoamHacker如果我把一些我想先在偵聽器函數內執行的邏輯,我的測試表明,如果在後臺有其他邏輯,則不能保證這個邏輯將被首先執行。 – slickman

回答

2

onInstalled聽衆趕在這些情況下的事件:

第一次安裝擴展程序,擴展程序更新爲新版本時,以及Chrome更新爲新版本時。

由於這是全部異步,它會在後臺進行,根據文檔,在任何這些情況下立即觸發。爲了清晰起見,請查看異步編程。

link to documentation

根據您的問題,好像你想幫助以正確的順序執行代碼。 This answer爲您的案例提供了一個有用的框架(使用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 
    } 
}); 
+1

我意識到這一點,即在安裝,更新擴展程序或將Chrome更新爲新版本時,會觸發onInstalled事件。我對流程更加好奇,並且可以捕捉到該事件的時間表,因爲我注意到,如果在鉤住安裝的偵聽器之前運行了一些邏輯,我的偵聽器就不會捕獲該事件。 – slickman

2

我也需要弄清楚。雖然我沒有發現任何權威,但我在我的後臺腳本中發現了幾條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 

然後我裝/再擴展(解壓縮,在開發模式)的幾十倍。 onInstall似乎非常可靠地在第一個50ms內觸發,而第一個功能在第一個ms內發生。結果如下:

(First function, onInstall event) 
(.282ms, 47.2ms) 
(.331ms, 45.3ms) 
(.327ms, 49.1ms) 
(.294ms, 45.9ms)