Search code examples
javascriptgoogle-chrome-extensionchrome-extension-manifest-v3

question about listening to events in non persistent service worker in chrome extension mv3


In background.js of my extension(mv3), I am doing following things: 1. created an alarm with periodInMinutes:1, 2. register alarm listener, 3. register chrome.downloads.onCreate listener to monitor file downloads, 4. connect to Native Messaging port. When I start chrome and wait a while, my extension turns to inactive status which is expected because it is not persistent. When I download something, the extension is invoked and background.js is executed again. My question is are those event listeners registered in first run still valid when background.js is invoked and executed again?

Do I have to implement a mechanism to avoid registering them again or it is correct to do all the things again?


Solution

  • In Manifest V3, having events unconditionally registered at the top level of your script is the correct way of doing things. While Chrome remembers "the extension is interested in this event, so I should wake it up if it happens", it doesn't remember the implementation and so it needs to be provided each time. You don't need to worry about duplicate events. There's some more info here: https://developer.chrome.com/docs/extensions/mv3/service_workers/

    Also as a note, an extension with an active native messaging connection should be exempt from the service worker timeouts (https://developer.chrome.com/docs/extensions/whatsnew/#m100-native-msg-lifetime). The known issue mentioned there should be fixed now. If you're not seeing that, that may be worth troubleshooting separately.