Examples

Here are a few common examples of how to use the webext-bridge package to communicate within your extension. There are way more possibilities, this should give a quick overview on how it all works together.

sendMessage() and onMessage()

Of the 6 available methods, the sendMessage() and the onMessage() methods are the most commonly used. Let's quickly go over these methods so the examples make a little more sense.

The sendMessage() method actually sends the message and will be the same no matter what context you are importing it. This method will accept 3 parameters:

  • messageId - ID of the message that we are sending. I usually set this to an uppercase enum or string value so it's easy to listen for and makes sense.
  • data - JSON data to send along with the message. Used for processing.
  • destination - The destination is where we are sending the message to, such as background, popup, content-script@{tabId}, etc.

Next, we have the onMessage() method which listens to an incoming message targeted. The two parameters accepted by this method are:

  • messageId - ID of the message are listening to. This matches the messageId from the sendMessage() method.
  • callback - The callback function used to handle the method.

There are other methods that are exposed as well, but they are all built off of these two methods. All methods are documented in the API.

In this example, we send a message from the popup to the background script.

One thing to note. In all examples, we decouple the {data} in the onMessage() handler. You don't have to do that. For the most part, it's all you really need access too. However, the callback method accepts a JSON object that contains a little more information and is constructed like this:

Parameter received by the `onMessage()` callback

{
    "sender": {
        "context": "popup", // could be any other context
        "tabId": null,
        "frameId": null
    },
    "id": "MESSAGE_ID",
    "data": {},
    "timestamp": 1701876927787
}

This can be extremely helpful when figuring out where the message came from. I've used the sender.context to determine where the message came from in order to determine the response in some extensions.

Popup

import { sendMessage } from "webext-bridge/popup";

const sendToBackground = async () => {
    await sendMessage("RECORD_NAME", {
        first_name: 'John',
        last_name: 'Doe'
    }, "background");
}

Background

import { onMessage } from "webext-bridge/background";

onMessage( "RECORD_NAME", recordName );
async function recordName( {data} ){
    // Do whatever processing you need here. 
    return {
        // Some response here
    }; 
}

This example sends a message from the background to a content script. One SUPER important piece to point out, is when messaging a content script, you need to add the tabId where the script is located to the end of the destination.

If you aren't using the webextension-polyfill package, I'd highly recommend it. Otherwise you will have to write an individual extension for each browser you want to support. In this example, we are using the polyfill and referencing the browser through browser. (the alternative would be chrome.).

Popup

import { sendMessage } from "webext-bridge/popup";

function sendToContentScript{
    let tabs = await browser.tabs.query({
        active: true,
        currentWindow: true
    });

    const response = await sendMessage("RECORD_NAME", { 
        first_name: 'John',
        last_name: 'Doe'
    }, "content-script@"+tabs[0].id);
}

Note, we are querying the active tab in the current window to grab the tabId. Feel free to use whatever method you need to get the tabId

Content

import { onMessage } from "webext-bridge/content-script";

onMessage( "RECORD_NAME", recordName );
async function recordName( {data} ){
    // Do whatever processing you need here. 

    return {
        // Some response here
    }; 
}

Content Script -> Background Script

This example sends a message from the content script to the background script.

Content

import { sendMessage } from "webext-bridge/content-script";

const sendToBackground = async () => {
    const response = await sendMessage('RECORD_NAME', {
        first_name: 'John',
        last_name: 'Doe'
    }, 'background'); 

    // Handle response
}

Background

import { onMessage } from "webext-bridge/background";

onMessage( "RECORD_NAME", recordName );
async function recordName( {data} ){
    // Do whatever processing you need here. 

    return {
        // Some response here
    }; 
}

Hope these examples help! Definitely check out the API to see all available methods and how to use them within your extension.