crx-bridge icon indicating copy to clipboard operation
crx-bridge copied to clipboard

Separate modules for each runtime context

Open zikaari opened this issue 3 years ago • 1 comments

The idea sparked up as a direct result of issue https://github.com/NeekSandhu/crx-bridge/issues/7. This issue popped up Firefox support was added through webextension-polyfill. Basically, there's some code that can't be loaded into the window context.

The fix? - let's just not have that code run in the window context then!


Having separate modules for each runtime context not only fixes the issue mentioned above, but it actually has some sick benefits (explained later), first, this is what it would look like:

// any script injected by a content script
import Bridge from 'crx-bridge/window';

// within content scripts
import Bridge from 'crx-bridge/content';

// within devtools
import Bridge from 'crx-bridge/devtools';

// and finally, background pages
import Bridge from 'crx-bridge/background';

Now, on to the benefits:

  • Lightweight - the window context doesn't care about the webextension API's, and the background doesn't care about postMessage. While there's no concept of "loading time" in an extension, parsing time reduction is still welcome.
  • Strict, more precise "localized" typings - because each module has its own designated scope, instead of a general crx-bridge scope, types can be contained as well. For example, setNamespace inside any other context besides the window script is a noop, and allowWindowMessaging is only applicable in a content script.
  • More readable - The moment you see import Bridge from 'crx-bridge/background', you know that this file is meant to run in the background page. With just import Bridge from 'crx-bridge', not so much.
  • Strict errors during development - The moment import Bridge from 'crx-bridge/window' statement runs within a content script, an error is thrown to let you know that you're mixing up things. This strict behavior keeps the previous bullet point about readability reinforced at all times.

cc @smeijer @antfu @pakholeung37 @Marik-D

zikaari avatar Jul 29 '21 08:07 zikaari

Fixed in https://github.com/antfu/webext-bridge/pull/24

zikaari avatar Jun 29 '22 00:06 zikaari

Task Complete

zikaari avatar Apr 06 '23 20:04 zikaari