Search code examples
javascriptgoogle-chrome-extensionservice-workerchrome-extension-manifest-v3

Is it necessary to removeListeners in background service workers for chrome extensions on suspend?


I'm adding listeners, e.g. chrome.tabs.onRemoved.addListener, in my chrome extension background service worker. I'm reading here: https://developer.chrome.com/docs/extensions/mv3/service_workers/#unloading that

Service workers unload on their own after a few seconds of inactivity

Does this mean I do not have to call removeListener logic to remove my listeners when the worker is suspended? i.e. chrome.tabs.onRemoved.removeListener on browser.runtime.onSuspend


Solution

  • No.

    When you register a listener Chrome remembers internally that your extension's background script wants to run when this event occurs in the future so Chrome will wake your background script. If you remove the listener, Chrome won't wake your background script for this event.

    P.S. The misguiding article on service workers can be replaced by the following sentence: the MV3 background script is essentially identical to an MV2 background script with "persistent": false except for the lack of stuff specific to normal tabs/windows such as DOM, XMLHttpRequest, etc.