# WebExt Typed Messages

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

## Sending messages from content scripts to background scripts

Background script:

```ts
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:

```ts
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:

```ts
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:

```ts
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
```
