Messaging
Recommendation
We recommend using tRPC for communication. It is type-safe and supports streaming.
- Add dependencies:
bash
$ pnpm add @webx-kit/messaging @trpc/server@next @trpc/client@next zod
bash
$ npm install @webx-kit/messaging @trpc/server@next @trpc/client@next zod
bash
$ yarn add @webx-kit/messaging @trpc/server@next @trpc/client@next zod
- Server(background):
ts
import { createTrpcServer } from '@webx-kit/messaging/server';
import { appRouter } from './router';
createTrpcServer({
router: appRouter,
});
ts
import { t } from '@webx-kit/messaging/server';
import { z } from 'zod';
export const appRouter = t.router({
hello: t.procedure.input(z.object({ name: z.string() })).query(async ({ ctx, input }) => {
console.log(ctx.sender);
return `Hello, ${input.name}`;
}),
});
export type AppRouter = typeof appRouter;
- Client(popup/options/content-scripts...):
ts
import { createTrpcClient } from '@webx-kit/messaging/client';
import type { AppRouter } from '@/background/router';
const { client } = createTrpcClient<AppRouter>({});
// invoke
client.hello.query({ name: 'WebX Kit' }).then((value) => alert(value));
Other choices
We don't bundle sale specific libraries, you can choose your favorites.
- webext-bridge - Messaging in Web Extensions made easy. Batteries included.
- Web Ext Core Messaging - A simpler, type-safe API for sending and recieving messages.