Quick Example
Let's quickly send a message from our popup, to our background script.
Popup
In your popup, add the following code:
Popup
import { sendMessage, onMessage } from "webext-bridge/popup";
const response = await sendMessage("ACTION", {
data: data
}, "background");
Background Service Worker
Now, head over to your background service worker script and add the following code:
Background Service Worker (background.js)
import { onMessage, sendMessage } from "webext-bridge/background"
onMessage( "ACTION", runAction );
async function runAction( {data} ){
// process data
// return data
return {
};
}
That's it! You are ready to send messages.
Advantages
There's a lot of advantages to using the webext-bridge
package. webext-bridge
handles everything for you as efficiently as possible. No more chrome.runtime.sendMessage
or chrome.runtime.onConnect
or chrome.runtime.connect
First, you can specifically target where your message is being sent or handled. Notice in the popup script, we import from webext-bridge/popup
and in the background service worker, we import from webext-bridge/background
. Super handy to control how your messages are being processed and where. No funky scoping or messages being processed in the wrong place.
Second, the code is much cleaner and easy to read since you can easily bind an action to a function. No more massive switch/case statements that you'd have using the built in messaging systems:
Compare to built in messaging
browser.runtime.onMessage.addListener( ( request, sender, sendResponse ) => {
switch( request.action ){
case "ACTION":
runAction( request.data ).then( sendResponse );
return true;
break;
}
} );
Also, this is a cross platform solution. This code will work on Firefox, Chrome, Safari, and Edge!
While this is a very simple example, it shows the power and flexibility of the webext-bridge
package. We will be diving in a lot more and showing a ton of examples.
Learn how to use "webext-bridge" with our book
We put together a comprehensive guide to help people build multi-platform browser extensions. The book covers everything from getting started to advanced topics like messaging, storage, and debugging. It's a great resource for anyone looking to build a browser extension. The book specifically covers how to use webext-bridge
to simplify messaging in your extension.