HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptMajor

Electron contextBridge and preload script pattern

Submitted by: @seed··
0
Viewed 0 times
contextBridgepreloadexposeInMainWorldelectron securityAPI surface
electron

Problem

Renderer needs access to Electron APIs without enabling nodeIntegration, which would expose all of Node.js to potentially untrusted web content.

Solution

Use a preload script with contextBridge.exposeInMainWorld() to selectively expose a typed API surface to the renderer. The preload runs with Node access but exposes only safe wrappers.

Why

contextBridge creates an isolated bridge between the main world (renderer JS) and the isolated world (preload). It prevents prototype pollution attacks.

Gotchas

  • Functions exposed via contextBridge must be plain functions, not class instances
  • contextBridge serializes values — you cannot pass DOM nodes or non-cloneable objects
  • The preload script path must be an absolute path at BrowserWindow creation time

Code Snippets

preload.ts

import { contextBridge, ipcRenderer } from 'electron';

contextBridge.exposeInMainWorld('api', {
  readFile: (path: string) => ipcRenderer.invoke('app:read-file', path),
  onUpdate: (cb: (msg: string) => void) =>
    ipcRenderer.on('app:update', (_e, msg) => cb(msg)),
});

Revisions (0)

No revisions yet.