Preload Script
Renderers talk to the main process through a preload script, which exposes electron-trpc’s IPC channel to the page. createIPCHandler registers electron-trpc’s own preload script.
Sessions
Section titled “Sessions”The preload script is registered on Electron’s default session, so it runs in every page that uses it. If your windows use other sessions, pass those instead:
import { session } from 'electron';
createIPCHandler({ router, preload: { sessions: [session.fromPartition('persist:app')] },});Register the preload script before your windows load their pages, since a page only gets the preload scripts registered when it loads. Disposing the handler unregisters it.
Your own preload scripts, set with webPreferences.preload, run alongside electron-trpc’s.
Packaged apps
Section titled “Packaged apps”The preload script is a file in the electron-trpc package, so your packaged app has to include it. That doesn’t need any setup when:
- Your app includes electron-trpc in
node_modules, for example as adependencypackaged by electron-builder, whether or not your main process is bundled. - Your main process is bundled with webpack, as in electron-forge’s webpack template. webpack copies the preload script into its output.
If your build bundles electron-trpc into the main process without including its preload script, createIPCHandler throws an error saying it couldn’t find the preload script. This usually happens when electron-trpc is a devDependency, or when your packager only includes your bundled code.
Using your own preload script
Section titled “Using your own preload script”To expose electron-trpc from a preload script of your own, pass preload: false and call exposeElectronTRPC from it:
createIPCHandler({ router, preload: false });
const win = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js'), },});import { exposeElectronTRPC } from 'electron-trpc/preload';
exposeElectronTRPC();Electron sandboxes renderers by default, and a sandboxed preload script can only require Electron’s own modules. Bundle your preload script so that electron-trpc/preload is included in it, as electron-forge’s templates do and the manual preload example shows with Vite.