extension-js / extension.js

🧩 Plug-and-play, zero-config, cross-browser extension development tool.
https://extension.js.org
MIT License
3.58k stars 85 forks source link

service worker and self.addEventListener() #131

Open bugficks opened 1 month ago

bugficks commented 1 month ago

I am trying to reliably detect service worker restarts. chrome.runtime.onXXX does not work if you e. g. start/stop through chrome://serviceworker-internals/. So I've tried to add at top of my background.ts :

self.addEventListener('activate', (event) =>
{
    console.log('Service worker activated');
});

self.addEventListener('install', (event) =>
{
    console.log('Service worker installed');
});

Unfortunately this is results in: background.ts:2 Event handler of 'activate' event must be added on the initial evaluation of worker script. background.ts:7 Event handler of 'install' event must be added on the initial evaluation of worker script.

How can I achieve that ?

Is there any way to hook in webpack build config?

cezaraugusto commented 1 month ago

@bugficks are you able to run the script using webpack in isolation? In the ScriptsPlugin the background scripts are added in the entry configuration, I'm not sure it's possible to run earlier than that. Here's the code that implements it. We can definitely add a patch if needed.

It's not possible to hook in the internal webpack config without a hack yet, but happy to patch a fix to make it work if that's the case

bugficks commented 1 month ago

It seems to work using webpack in isolation. For testing I have used chrome-extension-webpack. I could add those few lines even at end of serviceWorker.ts and had no errors in console.

image

cezaraugusto commented 1 month ago

Possibly related to an upstream dep https://github.com/awesome-webextension/webpack-target-webextension, got to take a deeper look

bugficks commented 3 weeks ago

this seems to be an issue how webpack resolves/imports modules. In a webpack based project using my sources: If I comment everything except those 2 addEventListener() calls in my background.ts it works with a webpack based project, if I add imports from my other ts files to background.ts I will get this error.

cezaraugusto commented 2 weeks ago

Thanks, this needs a deeper look but currently focused on the next release. Not sure how to fix this one at the moment