0

With manifest v3, we will need to store state data to the local storage with chrome.storage.local and load it when needed. But that API is asynchronous, so when it is called inside an event listener, sometimes the service worker is unloaded without waiting for the result from reading local storage. For example:

chrome.webNavigation.onCompleted.addListener(function (details) {
  chrome.storage.local.get('desired_key', (data) => {
    // sometimes sw is unloaded before the result (because of idling for 30s)
  })
});

With chrome.runtime.onMessage, I can use the sendResponse function to keep the service worker alive:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
  chrome.storage.local.get('desired_key', (data) => {
    // sendResponse keeps the sw alive
    sendResponse(1);
  })
});

I wonder how to keep the service worker alive until the asynchronous listener ends?

trihai3012
  • 11
  • 2
  • 2
    Does this answer your question? [Chrome Extension Message passing: response not sent](https://stackoverflow.com/questions/20077487/chrome-extension-message-passing-response-not-sent). See also [this answer](https://stackoverflow.com/a/59915897). – wOxxOm May 28 '22 at 05:04
  • Hi wOxxOm, thanks for your reply. But I don't have any problem with send/receive message, as I can keep it alive until the sendResponse is called. My question is about other asynchronous API and asynchronous event listener that don't have any 'sendResponse'-like function to keep it alive. Like chrome.webNavigation.onCompleted, the service worker may not wait for any asynchronous calls inside it before unloading. – trihai3012 May 28 '22 at 14:20
  • See [Persistent Service Worker in Chrome Extension](https://stackoverflow.com/a/66618269) – wOxxOm May 28 '22 at 18:57

0 Answers0