jlalmes / trpc-chrome

tRPC adapter for Web Extensions 🧩
https://www.npmjs.com/package/trpc-chrome
MIT License
270 stars 21 forks source link

How to get a sender from tRPC procedure? #9

Closed sleaper closed 1 year ago

sleaper commented 1 year ago

Is there any way how to get the sender from tRPC procedure? I need it to get a tab.

Here is an example with onMessage listener:

browser.runtime.onMessage.addListener(
  (data, sender) => {
    let tab = sender.tab
    console.log(tab)
  }
);
sleaper commented 1 year ago

I'm just stupid. You can get sender from ctx like this:

createChromeHandler({
  router: appRouter,
  createContext: (ctx) => {
    return { sender: ctx.req.sender }
  }
})

Then you can get ctx in your procedure like this:

const appRouter = t.router({
  helloTab: t.procedure.input(z.object({ url: z.string().url() })).mutation(async ({ input, ctx }) => {
    //@ts-ignore
    const tab = ctx.sender.tab
    console.log(tab)
  }),
});