webext-typed-messages
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

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

Package Sidebar

Install

npm i webext-typed-messages

Weekly Downloads

2

Version

0.1.0

License

ISC

Unpacked Size

11.5 kB

Total Files

5

Last publish

Collaborators

  • nikixd