jsonnull / electron-trpc

Build type-safe Electron inter-process communication using tRPC
https://electron-trpc.dev/
MIT License
267 stars 26 forks source link

handleIPCMessage only sends replies to electron main frame #145

Closed JoeHartzell closed 1 year ago

JoeHartzell commented 1 year ago

Summary

I have a use case that involves using iframes and tRPC to communicate between each frame and the main thread. After spending some time debugging it seems that handleIPCMessage replies to the sender using event.sender.send which will always reply to the main frame.

References

Solution

I think the solution here is pretty simple. handleIPCMessage should be able to use event.reply to respond to incoming events as stated by the Electron docs. This would also involve updating the types on the event parameters to use ipcMainEvent instead of IpcMainInvokeEvent.

Example

Current implementation

import { IpcMainInvokeEvent } from 'electron'
export async function handleIPCMessage<TRouter extends AnyRouter>({
  router,
  createContext,
  internalId,
  message,
  event,
  subscriptions,
}: {
  router: TRouter;
  createContext?: (opts: CreateContextOptions) => Promise<inferRouterContext<TRouter>>;
  internalId: string;
  message: ETRPCRequest;
  event: IpcMainInvokeEvent; // OLD
  subscriptions: Map<string, Unsubscribable>;
}) { 
// ...
}

Suggested change

import { IpcMainEvent } from 'electron'
export async function handleIPCMessage<TRouter extends AnyRouter>({
  router,
  createContext,
  internalId,
  message,
  event,
  subscriptions,
}: {
  router: TRouter;
  createContext?: (opts: CreateContextOptions) => Promise<inferRouterContext<TRouter>>;
  internalId: string;
  message: ETRPCRequest;
  event: IpcMainEvent; // NEW
  subscriptions: Map<string, Unsubscribable>;
}) { 
// ...
}

Contributing

Would be more than happy to make a PR with the suggested changes above.

Versions

JoeHartzell commented 1 year ago

Just confirmed that the PR resolves the issue and my frames now successfully communicate! 🎉 It might be worth following up this issue by adding an example to the repo using iframes.

JoeHartzell commented 1 year ago

Just giving this a friendly bump @jsonnull . Would love to see this merged as I think it blocks multi-window support as well. Also more than happy to help on any other roadmap items. This is by far the best way to work with electron ipc communication.

jsonnull commented 1 year ago

Hey, thanks for the friendly bump and all the effort here. I'll get this merged in and get a release out. If you're interested in contributing more, let's chat sometime!

jsonnull commented 1 year ago

This fix is released in electron-trpc@0.5.1. Thanks again!