Search code examples
javascriptwebpackgoogle-chrome-extensionscopechrome-extension-manifest-v3

Listener inside IIFE/function (not in global scope) in ManifestV3 service worker?


Manifest v3 service workers require listeners are defined in the global scope of a file, webpack compiles to inside an anonymous function. These two things seems basically incompatible. Does anyone have a solution better than ditching webpack?


Solution

  • Manifest v3 service workers require listeners are defined in the global scope of a file

    There's no such requirement, it's an incorrect/inaccurate claim in the documentation: "top level of your script" is a misrepresentation of the technical terms used to describe the JS engine internals.

    The actual requirement is to register the listeners in the main (synchronous) phase of the first task of the JS event loop, which may certainly happen inside a function:

    (() => {
      (() => {
        chrome.runtime.onMessage.addListener(msg => { /* ..... */ });
      })();
    })();