Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท IPC and Preload Scripts

Preload Scripts and contextBridge in Electron

Learn how Electron preload scripts connect pages to the main process safely: contextIsolation, contextBridge.exposeInMainWorld, a minimal API surface and common mistakes, with runnable models.

A preload script is a JavaScript file that runs inside the renderer process before the page's own scripts. It is the only place where page-side code can use a restricted slice of Electron and Node.js. Its job is to build a small, safe API and hand it to the page, so the page never touches ipcRenderer or Node.js directly.

If IPC is the road between the page and the main process, the preload script is the toll booth: it decides exactly which vehicles can pass.

Registering a preload script

You pass the absolute path in webPreferences.preload:

JavaScript
const win = new BrowserWindow({
  webPreferences: {
    preload: path.join(__dirname, '../preload/preload.js'),
  },
})

The preload script runs for each page load in that window. It has access to a reduced set of Electron renderer modules (contextBridge, ipcRenderer, webFrame, webUtils and a few others) and, because it runs in a sandbox, a limited polyfill of Node.js (such as require for a small allow-list of modules, process basics, Buffer). It cannot use fs or child_process in the sandboxed default. Move that work to the main process and call it through IPC.

Context isolation: two worlds in one page

With contextIsolation: true (the default), the preload script and the page run in separate JavaScript worlds. They share the same DOM, but not the same global objects. A variable or prototype modification made by the page cannot reach your preload code, and the page cannot see ipcRenderer unless you hand it something.

flowchart LR
  subgraph Renderer["Renderer process"]
    direction LR
    A["Isolated world<br/>preload script<br/>(ipcRenderer, contextBridge)"]
    B["Main world<br/>your page's JavaScript<br/>(window, document)"]
    A -->|"contextBridge.exposeInMainWorld"| B
  end
  A -->|IPC| M["Main process"]

Figure: the bridge is the only thing that crosses from the isolated world to the page.

exposeInMainWorld

contextBridge.exposeInMainWorld(name, api) adds a global named name to the page's window, containing the functions and values you list:

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

contextBridge.exposeInMainWorld('notesApi', {
  list: () => ipcRenderer.invoke('notes:list'),
  save: (note) => ipcRenderer.invoke('notes:save', note),
  onExternalChange: (callback) => {
    const listener = (_event, data) => callback(data)
    ipcRenderer.on('notes:changed', listener)
    return () => ipcRenderer.removeListener('notes:changed', listener)   // unsubscribe function
  },
  platform: process.platform,
})
JavaScript
// renderer (page)
const notes = await window.notesApi.list()
await window.notesApi.save({ title: 'Hello', body: '...' })
const stop = window.notesApi.onExternalChange((data) => console.log(data))

Rules the bridge enforces:

  • Functions are proxied: the page receives a wrapper that calls your function in the isolated world. Arguments and return values are copied (structured clone style), so the page cannot reach your internals.
  • Primitive values and plain objects pass; class instances, DOM nodes and prototypes do not keep their identity.
  • The exposed object is read-only from the page's side; replacing window.notesApi.list in the page does not change what the bridge calls.

Exposing the minimum

The single most important habit: never expose ipcRenderer or a generic send(channel, ...) function. That would let the page (or any script injected into it) message any channel, including ones you add later.

JavaScript
// BAD: the page can call any channel with any data
contextBridge.exposeInMainWorld('electron', {
  invoke: (channel, ...args) => ipcRenderer.invoke(channel, ...args),
})

// GOOD: one function per capability, channel names stay private
contextBridge.exposeInMainWorld('api', {
  readNotes: () => ipcRenderer.invoke('notes:read'),
})

A model of the bridge

The real bridge copies values between JavaScript worlds. This stand-in imitates the idea: the "isolated" side holds a secret and the privileged function, and the page receives only a frozen object of wrappers, with arguments copied on the way in.

Node.js Stand-in: a context bridge

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.

Frozen exposed objects mean a script on the page cannot swap your wrappers for its own.

Subscribing safely

When the main process pushes messages, the renderer subscribes. Pass a callback, wrap it so the event object is not forwarded, and return an unsubscribe function. If you forwarded event, the page would get access to event.sender, a handle into the privileged side.

Node.js Stand-in: subscribe without leaking the event

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.

Forgetting to unsubscribe leaks listeners every time a component re-mounts; returning the remover from the API solves it.

TypeScript and types

Declare the shape of the exposed API once so the renderer gets autocomplete:

TypeScript
// renderer/global.d.ts
export interface NotesApi {
  list(): Promise<Note[]>
  save(note: Note): Promise<void>
  onExternalChange(cb: (note: Note) => void): () => void
}
declare global {
  interface Window { notesApi: NotesApi }
}

Common mistakes

  • Relative preload path so the script never loads and window.api is undefined. Use path.join(__dirname, ...).
  • contextIsolation: false to "make it work". Then window.api = ... works but is unsafe; use contextBridge instead.
  • Exposing class instances or objects with methods on prototypes; plain objects and functions are safest.
  • Exposing a generic channel function (shown above).
  • Heavy work in preload. It blocks page loading, so keep it tiny.
  • Using require('fs') in preload with the sandbox on. It is not available; ask the main process.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a preload script do?

    It runs before page scripts, with limited Electron access, and exposes selected functions via contextBridge.
  2. 2. What is the effect of contextIsolation: true?

    Separate worlds stop page code from tampering with your preload code or reaching ipcRenderer.
  3. 3. Which exposure is safest?

    One function per capability keeps channel names private and limits what the page can ask for.
  4. 4. Why should the listener you pass to ipcRenderer.on not forward the event object?

    Forward only plain data; the event object belongs to the privileged side.

Summary

  • A preload script runs before the page and uses contextBridge.exposeInMainWorld to expose a small API.
  • Keep contextIsolation on; the page and the preload live in different JavaScript worlds.
  • Expose one function per capability, never ipcRenderer or a generic channel sender.
  • Return unsubscribe functions and do not forward event objects.
  • The preload path must be absolute and the script must stay small.

Next: Two-Way IPC with invoke and handle