0.1.0 • Published 1 year ago

webext-typed-messages v0.1.0

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

WebExt Typed Messages

Tiny wrapper around the WebExtension messages API that provides type safety.

Sending messages from content scripts to background scripts

Background script:

import { addRuntimeMessageListener } from "webext-typed-messages";

declare module "webext-typed-messages" {
  interface RuntimeMessages {
    hello: (name: string) => string;
  }
}

addRuntimeMessageListener({
  hello(name) {
    // name is a string
    return `Hello, ${name}!`;
  },
});

Content script:

import { sendRuntimeMessage } from "webext-typed-messages";

const response = await sendRuntimeMessage("hello", "world");
console.log(response); // Hello, world!

Sending messages from background scripts to content scripts

Content script:

import { addTabMessageListener } from "webext-typed-messages";

declare module "webext-typed-messages" {
  interface TabMessages {
    add: (a: number, b: number) => Promise<number>;
  }
}

addTabMessageListener({
  async add(a, b) {
    // a and b are numbers
    return a + b;
  },
});

Background script:

import { sendTabMessage } from "webext-typed-messages";

const tab = await chrome.tabs.getCurrent();
const response = await sendTabMessage(tab.id, "add", 1, 2);
console.log(response); // 3
0.1.0

1 year ago