跳至主要内容

[掘竅] Chrome Extension Tips 小細節

Structure​

  • 在 background 中 import 的程式碼就會算是 background 的,可以持續在背景執行。在 contentScript 或其 iframe 頁面內 import 的程式碼,則都算前端的,重新整理就會消失。最簡單的區分方式,是看 console.log 中訊息出現的位置來判斷,如果是在瀏覽器 console 中出現的,都算前端,重新整理就會資料都會重來;在 background 頁面中出現的訊息,才算是 background 的,網頁重新整理也不會重來。
  • 在 contentScript 中透過 iframe 載入的 chrome extension 頁面,該 iframe 中的內容雖然會算是 extension 的,但仍然算是前端的部分,一旦重新整理資料就會不見。
  • 因此,透過 iframe 中的頁面雖然可以為 chrome extension 取得 user media 的權限,但在該頁面執行 getUserMedia 取得的 stream 會在頁面重新整理時就不見,若想保持該 stream,則需要在 background 呼叫該方法。

Message Passing​

"Either side can listen for messages sent from the other end, and respond on the same channel." @ Message Passing @ Chrome Developer

  • Message 本來的用途是在不同 thread 間進行溝通(例如,Content Script 和 Background,Extension 和 Extension 之間的等)。因此,收件者無法收到在同一個 thread 中發送者發送的訊息,例如,在 background onMessage 的話,無法收到一樣在 background 中 sendMessage 的內容。(參考:Chrome messaging: chrome.runtime.sendMessage not working on the newest release 49)