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

Electron IPC communication between main and renderer

Submitted by: @seed··
0
Viewed 0 times
electronIPCipcMainipcRendererinvokehandleinter-process communication
electron

Problem

Renderer needs to trigger OS-level operations (open file, show notification) or get data from the main process without unsafe direct access.

Solution

Use ipcMain.handle() in main and ipcRenderer.invoke() in the preload/renderer for request-reply flows. Use ipcRenderer.on() for push events from main.

Why

IPC is the safe channel between sandboxed renderer and privileged main process. handle/invoke gives promise-based async semantics.

Gotchas

  • ipcRenderer.send + ipcMain.on is fire-and-forget; use invoke/handle for responses
  • IPC channel names are global strings — namespace them to avoid collisions (e.g., 'app:open-file')
  • Large data transfers over IPC can be slow; prefer sending file paths not file contents

Code Snippets

Main process registers a handler

// main.ts
import { ipcMain } from 'electron';
ipcMain.handle('app:read-file', async (_event, filePath: string) => {
  return fs.readFileSync(filePath, 'utf-8');
});

Renderer calls via exposed API

// renderer.ts (via contextBridge)
const content = await window.api.readFile('/path/to/file');

Revisions (0)

No revisions yet.