dnakov / little-rat

🐀 Small chrome extension to monitor (and optionally block) other extensions' network calls
MIT License
2.08k stars 64 forks source link

Make sure variables are initialized when service worker restarts before onRuleMatchedDebug listener code is executed. #2

Closed keithx2 closed 1 year ago

keithx2 commented 1 year ago

Here's an example:

let initializer; let initialized = false;

chrome.declarativeNetRequest.onRuleMatchedDebug.addListener(async (e) => {

if (!initialized) { await initializer; }
// ...

});

(async function initialize() {

let gLocal = chrome.storage.local.get('muted', ({ muted: m }) => {
    muted = m || {};
});
let gManagement = chrome.management.getAll((extInfo) => {
    for(let { name, id, icons } of extInfo) {
        extensions[id] = { name, id, icon: icons?.[0]?.url, numRequests: 0, reqUrls: {}};
    }
});

let i = async () => {
    await gLocal;
    await gManagement;
    initialized = true;
}
initializer = i();

})();

dnakov commented 1 year ago

I haven't been able to reproduce this. If you have more info, lmk. Gonna keep it open for a few days.

keithx2 commented 1 year ago

Perhaps you always have the developer console open for the extension? That prevents a service worker from terminating.

Service workers have a 30 second lifecycle. Received events or extension api calls reset the timer back to 30 seconds. If the timer expires, the service worker is terminated. Make sure there is no network activity, wait at least 30 seconds, and the extension will go 'inactive'. It will restart when an event it is listening to is fired. When it restarts, all the code in service-worker.js is run again.

There is no guarantee that the code in chrome.management.getAll will run before the listener for onRuleMatchedDebug when the extension restarts because of network activity. That is why the onRuleMatchedDebug listener needs to wait until the extension is fully initialized, before it continues. I've seen this error happen in this case:

Error in event handler: TypeError: Cannot read properties of undefined (reading 'numRequests') at chrome-extension://ojeaaldfoimnikjkigkhebdbpfjdoaco/service-worker.js:35:27

I can reproduce the error with the uBlock Origin extension. I let the service worker go inactive and open the 'uBlock Dashboard'. Then after selecting 'Filter lists', 'Purge all caches', and 'Update now', the error will appear when the extension restarts. If the service worker restarts on non extension network activity, then there would be no error.

There may be other cases in your code where you need the variables fully initialized first. I only looked at where the error occurred.

Note, new extensions can also be installed when the service worker is running. And you'll get an error in that same spot. This also needs to be considered. Maybe listen to management.onInstalled.

dnakov commented 1 year ago

Thank you for the detailed debugging! I'm working on some fixes.