Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท IPC and Preload Scripts

Main-to-Renderer Messages: webContents.send and ipcRenderer.on

Push events from the Electron main process to a page with webContents.send and ipcRenderer.on: menu clicks, progress updates, broadcasts to all windows and safe unsubscribing, with runnable models.

invoke and handle cover requests that start in the page. But many things start in the main process: the user clicks a menu item, a file download progresses, the operating system goes to sleep, an auto-update becomes available, another window changed a setting. The page cannot ask "has anything happened yet?" in a loop; the main process needs to push a message.

That is the job of webContents.send(channel, ...args) on the main side and ipcRenderer.on(channel, listener) on the renderer side. This lesson shows the whole path, including the preload code that keeps it safe, and the two classic problems: forgetting to unsubscribe and sending to a window that is gone.

The basic flow

JavaScript
// main: send to ONE window's page
win.webContents.send('menu:new-file')
win.webContents.send('download:progress', { id: 7, percent: 42 })
JavaScript
// preload: expose a subscription function
const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('api', {
  onNewFile: (callback) => {
    const listener = () => callback()
    ipcRenderer.on('menu:new-file', listener)
    return () => ipcRenderer.removeListener('menu:new-file', listener)
  },
  onDownloadProgress: (callback) => {
    const listener = (_event, info) => callback(info)
    ipcRenderer.on('download:progress', listener)
    return () => ipcRenderer.removeListener('download:progress', listener)
  },
})
JavaScript
// renderer (page)
const stop = window.api.onDownloadProgress(({ id, percent }) => {
  progressBar.value = percent
})
// later, when the component is removed:
stop()

A message sent with webContents.send goes only to that window's main frame (and its preload). Each BrowserWindow has its own webContents, so you choose the recipient.

flowchart LR
  M["Main process<br/>menu click / timer / OS event"]
  M -->|"win1.webContents.send"| W1["Window 1 page"]
  M -->|"win2.webContents.send"| W2["Window 2 page"]
  M -.->|"loop over BrowserWindow.getAllWindows()"| W3["Broadcast to all"]

Figure: sends are addressed to a specific window; to broadcast, loop.

Example: menu click triggers a page action

A classic: the application menu has "File > New" and the page must open an empty document. The menu lives in the main process; the document UI lives in the page. The click handler sends a message:

JavaScript
const { Menu, BrowserWindow } = require('electron')

const template = [
  { label: 'File', submenu: [
    { label: 'New', accelerator: 'CmdOrCtrl+N',
      click: () => BrowserWindow.getFocusedWindow()?.webContents.send('menu:new-file') },
  ]},
]
Menu.setApplicationMenu(Menu.buildFromTemplate(template))

Note getFocusedWindow()?. : there may be no focused window (for example when the app is in the background on macOS), so guard against null.

A model of push messages and unsubscribing

This stand-in implements a window with webContents.send, a renderer-side on with an unsubscribe function, and a broadcast helper. Pay attention to the line that counts listeners: it demonstrates the leak that happens when you forget to unsubscribe.

Node.js Stand-in: send, subscribe, unsubscribe, broadcast

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.

Sending to a window that no longer exists

If a window has been closed and you still call win.webContents.send, Electron throws Object has been destroyed. Typical causes: a long-running task finishes after the user closed the window, or a stored reference was not cleared. Guard with win.isDestroyed() (and win.webContents.isDestroyed()), or listen for closed and cancel the work.

JavaScript
function notify(win, channel, payload) {
  if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return
  win.webContents.send(channel, payload)
}

Timing: wait for the page to be ready

If you send a message right after creating a window, the page may not have registered its listener yet, and the message is lost. Send initial data after the page asks for it (preferably with invoke), or wait for did-finish-load:

JavaScript
win.webContents.once('did-finish-load', () => {
  win.webContents.send('app:initial-state', state)
})

A more robust design: the page asks for its initial state with invoke('app:getState') when it starts, and the main process only pushes changes afterwards. That removes the race entirely.

Throttling noisy streams

Progress updates can arrive hundreds of times per second. Sending every one wastes IPC bandwidth and re-renders the page uselessly. Throttle on the main side to, say, 10 updates per second and always deliver the final value.

Node.js Stand-in: throttle progress messages

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.

Reply to the same window that asked: event.reply

For listeners registered with ipcMain.on you can answer with event.reply('channel', data), which is event.sender.send under the hood. Prefer invoke/handle for questions. Use push messages for genuine events that have no question.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call sends a message from the main process to one window's page?

    webContents.send addresses the page of a specific window; the page receives it through ipcRenderer.on in the preload script.
  2. 2. Why return an unsubscribe function from the preload subscription helper?

    Without removing listeners, every re-mount adds another one, causing duplicate handling and memory leaks.
  3. 3. What happens if you call webContents.send on a destroyed window?

    Guard with isDestroyed() or cancel work when the window closes.
  4. 4. What is a robust way to deliver a page's initial state?

    A page-initiated request avoids the race where the message arrives before the page has registered listeners.

Summary

  • webContents.send pushes events to one window; ipcRenderer.on receives them in the preload script.
  • Expose subscriptions as functions that strip the event object and return an unsubscribe function.
  • Broadcast by looping over windows; check isDestroyed() before sending.
  • Let the page ask for initial state; push only changes, and throttle noisy streams.

Next: IPC Validation, Security and Advanced Patterns