Type Safe Protocols

We are likely to use sendMessage and onMessage in different contexts, keeping the type consistent could be hard, and its easy to make mistakes. webext-bridge provide a smarter way to make the type for protocols much easier.

Create shim.d.ts file with the following content and make sure it's been included in tsconfig.json.

shim.d.ts

import { ProtocolWithReturn } from "webext-bridge";

declare module "webext-bridge" {
    export interface ProtocolMap {
        foo: { title: string };
        // to specify the return type of the message,
        // use the `ProtocolWithReturn` type wrapper
        bar: ProtocolWithReturn<CustomDataType, CustomReturnType>;
    }
}

Now within the different parts of your extension, you can use the following:

Content Script

import { onMessage } from 'webext-bridge/content-script'

onMessage('foo', ({ data }) => {
    // type of `data` will be `{ title: string }`
    console.log(data.title)
}

Background Worker

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

const returnData = await sendMessage("bar", {
  /* ... */
});
// type of `returnData` will be `CustomReturnType` as specified