Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท IPC and Preload Scripts

Two-Way IPC with ipcRenderer.invoke and ipcMain.handle

Build request and response IPC in Electron with ipcRenderer.invoke and ipcMain.handle: arguments, return values, errors, dialogs, file reads and a runnable mock of the page-to-main flow.

Most renderer-to-main communication is a question: "give me the app version", "open a file dialog", "save this document". The page asks, the main process works, and an answer comes back. In Electron this is the job of ipcRenderer.invoke and ipcMain.handle. They behave like a function call across processes, and they return a Promise, so you use await on the page.

The three parts

1. The handler in the main process

JavaScript
// main/ipc-handlers.js
const { ipcMain, dialog, app } = require('electron')
const fs = require('node:fs/promises')

function registerIpcHandlers() {
  ipcMain.handle('app:getVersion', () => app.getVersion())

  ipcMain.handle('notes:read', async (event, fileName) => {
    const text = await fs.readFile(safeNotePath(fileName), 'utf8')
    return text
  })

  ipcMain.handle('dialog:openFile', async (event) => {
    const { canceled, filePaths } = await dialog.showOpenDialog({
      properties: ['openFile'],
      filters: [{ name: 'Text', extensions: ['txt', 'md'] }],
    })
    return canceled ? null : filePaths[0]
  })
}
module.exports = { registerIpcHandlers }

The handler receives an event object first, then the arguments the caller passed. It may return a value or a Promise; whatever it returns (copied) becomes the resolved value on the other side.

2. The bridge in the preload script

JavaScript
// preload/preload.js
const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('api', {
  getVersion: () => ipcRenderer.invoke('app:getVersion'),
  readNote: (fileName) => ipcRenderer.invoke('notes:read', fileName),
  openFile: () => ipcRenderer.invoke('dialog:openFile'),
})

3. The call in the page

JavaScript
const version = await window.api.getVersion()
const text = await window.api.readNote('todo.txt')
const picked = await window.api.openFile()   // string path, or null when canceled

Register handlers before a window can call them, usually right after app.whenReady() and before creating windows. Each channel can have only one handler: calling ipcMain.handle twice for the same channel throws.

The call flow

sequenceDiagram
  participant Page
  participant Preload
  participant Main
  Page->>Preload: window.api.readNote("todo.txt")
  Preload->>Main: invoke("notes:read", "todo.txt")
  Main->>Main: validate, read file
  Main-->>Preload: "buy milk" (or rejects)
  Preload-->>Page: Promise resolves

Figure: invoke is a Promise-returning remote call.

Errors: what survives the trip

If the handler throws (or returns a rejected Promise), the renderer's Promise rejects. Electron serializes the error: the message is kept, wrapped in text like Error invoking remote method 'notes:read': Error: ENOENT..., but custom properties on the error and its class are not preserved. If your page must react to different failures, return a structured result instead of throwing:

JavaScript
ipcMain.handle('notes:read', async (event, fileName) => {
  try {
    return { ok: true, text: await readNote(fileName) }
  } catch (error) {
    return { ok: false, code: error.code ?? 'UNKNOWN', message: 'Could not read the note.' }
  }
})
JavaScript
const result = await window.api.readNote('todo.txt')
if (!result.ok && result.code === 'ENOENT') showEmptyState()

Do not leak internal details to the page: file system paths and stack traces help an attacker and confuse users. Log the real error in the main process and send a safe message.

Running the flow end to end

This stand-in reproduces the three parts above with the same function names. It uses a fake in-memory "disk" and shows both a thrown error (with the wrapped message, as real Electron does) and the structured-result style.

Node.js Stand-in: invoke, handle and errors

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.

The rejected error has no code property: it did not survive the boundary. The structured result did.

Arguments and return values

  • Pass plain data only (strings, numbers, objects, arrays). Never pass class instances or functions.
  • Prefer one object argument for anything with more than two parameters: invoke('export:pdf', { path, landscape: true }). It is easier to validate and to extend later.
  • Return only what the page needs. Returning a 50 MB Buffer copies it; prefer streaming or writing to disk and returning a path.
  • Handlers may be async. A slow handler does not block the main process, but the page's Promise waits, so show a loading state.

Calling invoke from the page: a loading pattern

Because invoke is asynchronous, the UI needs three states: loading, success, failure. The runnable demo below uses a mock window.api (the same shape as the preload would provide) with a built-in delay and failure toggle, so you can practice the page side.

Page side: loading, success and error states

Which window asked? event.sender and event.senderFrame

The first parameter of a handler carries information about the caller. event.sender is the webContents that made the call. BrowserWindow.fromWebContents(event.sender) finds its window, which is useful when a dialog should attach to the window that requested it:

JavaScript
ipcMain.handle('dialog:save', async (event, suggestedName) => {
  const win = BrowserWindow.fromWebContents(event.sender)
  const { canceled, filePath } = await dialog.showSaveDialog(win, { defaultPath: suggestedName })
  return canceled ? null : filePath
})

event.senderFrame.url tells you which page (or iframe) sent the message, which you should check in security-sensitive handlers (validation lesson).

Removing handlers

ipcMain.removeHandler('channel') removes a handler (for tests or hot reload). Under normal use you register once at startup and never remove them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ipcRenderer.invoke return?

    invoke is asynchronous and returns a Promise for the value returned by ipcMain.handle's function.
  2. 2. What happens to custom properties like error.code when a handler throws?

    Errors are serialized so the page sees a message, not your error class or its properties; return structured results to carry codes.
  3. 3. What happens if you call ipcMain.handle twice for the same channel?

    Each channel may have only one invoke handler.
  4. 4. How can a handler find the BrowserWindow that sent the request?

    event.sender is the webContents of the caller, and fromWebContents maps it to its window.

Summary

  • ipcMain.handle(channel, fn) and ipcRenderer.invoke(channel, ...args) give you Promise-based requests.
  • Expose each call through the preload script as a named function.
  • Arguments and results are copied; thrown errors lose custom properties, so return structured results when the page must react.
  • Use event.sender and BrowserWindow.fromWebContents to attach dialogs to the right window.
  • Register handlers once, before windows can call them.

Next: Main-to-Renderer Messages and Events