Re: [w3c/ServiceWorker] New "setup" lifecycle for service worker (#1576)

No matter if service worker provides 'setup phase' or 'top level await', thank @wanderview for your simpler solution.

Here I post a more complete code snippet, which include updating the cache. Maybe other extension developers will refer to this solution.
```
// I use uppercase to identify global variables
var Cache;
function init() {
  return new Promise(function(resolve, reject) {
    chrome.storage.sync.get(null, function(data) {
      // setup cache, for example:
      Cache = data;
      resolve();
    });
  });
}
var InitPromise = init();

// listen browser events, for example:
chrome.tabs.onUpdated.addListener(async function(parameters) {
  await InitPromise;
  // now you can use cache to process the event
});

// if data changed, e.g. user changed settings, you should update cache.
// listen messages or listen storage change event. for example:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if(request.type == "update") {
    InitPromise = init();
  }
});
```


-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/1576#issuecomment-814700162

Received on Wednesday, 7 April 2021 08:07:14 UTC