Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท IPC and Preload Scripts

IPC in Electron: Channels and Messages Explained

Understand inter-process communication in Electron: why renderers and the main process need IPC, the four messaging patterns, channels, serialization, and a runnable model of how it works.

The main process can touch files and the operating system. The renderer can draw the user interface. Almost every real feature needs both: the user clicks a button in the page, and something must happen on disk or in the OS. Because the two live in separate processes, they cannot share variables or call each other's functions. They have to send messages. That mechanism is IPC, inter-process communication.

This lesson gives you the mental model before you write any real code: what IPC is made of, which patterns exist, what can travel through it, and where messages must never be trusted.

The pieces

Electron provides two modules for the job:

  • ipcMain (main process only): registers listeners and handlers for channels.
  • ipcRenderer (renderer side, normally used inside a preload script): sends messages to the main process and listens for replies.

A channel is just a string name that both sides agree on, such as 'dialog:openFile' or 'settings:get'. There is no schema or type check in Electron itself; you are responsible for naming and validating. A common convention is domain:action in lowercase (file:read, window:minimize).

sequenceDiagram
  participant R as Renderer (page)
  participant P as Preload script
  participant M as Main process
  R->>P: window.api.readNotes()
  P->>M: ipcRenderer.invoke('notes:read')
  M-->>P: resolves with the data
  P-->>R: returns the data

Figure: the page never touches ipcRenderer directly; the preload script owns that call.

The four patterns

Pattern Direction API Use for
Renderer to main, one way Renderer sends, no reply ipcRenderer.send and ipcMain.on Fire-and-forget: log an event, set the window title
Renderer to main, two way Renderer asks, main answers ipcRenderer.invoke and ipcMain.handle Almost everything: read a file, show a dialog
Main to renderer Main pushes webContents.send and ipcRenderer.on Menu clicks, progress, updates
Renderer to renderer Via main, or MessagePorts ipcRenderer.postMessage, MessageChannel Windows sharing data

Prefer invoke/handle over the older sendSync or reply-based patterns. invoke returns a Promise, errors become rejected promises, and nothing blocks. ipcRenderer.sendSync blocks the renderer until the main process answers, which can freeze the UI if the main process is busy; avoid it.

The following lessons cover each pattern with code; here is the smallest complete example (read-only, runs in real Electron):

JavaScript
// main
const { ipcMain } = require('electron')
ipcMain.handle('app:getVersion', () => '1.0.0')

// preload
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('api', {
  getVersion: () => ipcRenderer.invoke('app:getVersion'),
})

// renderer (the page)
const version = await window.api.getVersion()

What can travel through IPC

Messages are copied with the structured clone algorithm, the same one used by postMessage. You can send numbers, strings, booleans, null, undefined, arrays, plain objects, Date, Map, Set, ArrayBuffer, typed arrays, and Error objects (with limits). You cannot send functions, DOM nodes, class instances with methods (the prototype is lost), or Symbols. Sending something unclonable throws an error such as "An object could not be cloned."

Because the message is a copy, changing it on the other side does not affect the sender. There are no shared references.

A model of IPC you can run

To feel the rules, this stand-in builds a tiny IPC bus on top of Node's structuredClone. It has invoke/handle and send/on. Observe that functions fail to cross the boundary and that unknown channels reject.

Node.js Stand-in: a tiny IPC bus

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real Electron behaves the same way for function arguments (it throws an error that the object could not be cloned) and for unregistered invoke channels (the promise rejects with "No handler registered").

Copies, not references

This second stand-in highlights the most common surprise: mutating a received object never changes the original, and class instances lose their methods.

Node.js Stand-in: IPC copies data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If you need behavior on the receiving side, send plain data and rebuild the object there.

Security view: treat every message as untrusted input

A message arrives at ipcMain from a renderer, and a renderer displays web content. If any content in that page is compromised, an attacker can call your channels with any arguments they like. So the main-process handlers must check three things:

  1. Who sent it (event.senderFrame, whether it belongs to your own page and not an embedded iframe or remote site).
  2. What it contains (type, size, allowed values, no path traversal).
  3. Whether the action is permitted for this window (authorization).

Never create a catch-all channel like ipcMain.handle('run', (e, cmd) => exec(cmd)). Expose narrow, specific operations instead. IPC validation and patterns turns these rules into code.

Naming and organizing channels

  • Use a prefix per feature: settings:get, settings:set, file:open, file:save.
  • Keep a single channels.js constants module imported by both main and preload to avoid typos.
  • Register all handlers in one place (registerIpcHandlers()), so you can see the whole attack surface at once.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do Electron apps need IPC?

    Separate processes can only cooperate by sending messages, which is what IPC provides.
  2. 2. Which pair is the recommended two-way request and response pattern?

    invoke returns a Promise and handle supplies the answer; it avoids blocking the renderer.
  3. 3. What happens when you pass a function as an IPC argument?

    IPC uses structured clone, which cannot copy functions.
  4. 4. After a message is received, you change a nested array in it. What happens to the sender's original?

    Structured clone copies the data, so there are no shared references.
  5. 5. How should main-process handlers treat incoming IPC arguments?

    A compromised page can send any arguments, so handlers must check sender, shape and permissions.

Summary

  • IPC lets the page and the main process cooperate across process boundaries through named channels.
  • Prefer invoke/handle; use webContents.send for main-to-renderer pushes; avoid sendSync.
  • Messages are structured-cloned copies: no functions, no DOM nodes, no class methods.
  • Treat every message as untrusted input, and expose narrow operations only.

Next: Preload Scripts and contextBridge