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?