Concepts
A browser extension consists of a lot of moving parts. You essentially have small, microservices that need to communicate with one another in a variety of ways. As your extension grows in size, it gets all the more hairy when it comes to communication.
When designing Bugflow, we handle around 15-20 different messages from a popup, background, and content scripts heading in all different directions. With standard, built-in, browser extension messaging, you don't have direct control where the message is sent, and if you have multiple messages, it's hard to efficiently handle all of them. You end up with massive switch case statements and callback chains.
The goal of the webext-bridge
package is to make your internal extension messaging a breeze. You can scope where the message is sent, use type-safe protocols, and handle incoming messages the most efficient way possible.
Let's look at how the webext-bridge
package allows you to efficiently communicate within your extension.
Extension Communication Contexts
In your extension, you will have multiple contexts that can send and receive messages:
Each of these contexts allows you to send a message to, or receive an incoming message. The available contexts available within the package are:
content-script
popup
options
background
devtools
We will go through each of these contexts, explain how to use them, and what methods are available. In your code, you will just import the module by adding import { } from 'webext-bridge/{context}'
wherever you need it.
Background Script
The background script context is special within webext-bridge
. Even if your extension doesn't need a background page or wont be sending/receiving messages in background script.
webext-bridge
uses background/event context as staging area for messages, therefore it must loaded in background/event page for it to work.
(Attempting to send message from any context will fail silently if webext-bridge
isn't available in background page). See troubleshooting section for more.