Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Preload Scripts & Se | Electron.js Desktop App Development l | BraveProgrammer
  1. Courses
  2. /
  3. Electron.js Desktop App Development

Lesson 4 of 28

·javascript

Preload Scripts & Secure Context Bridge

12 mins

Course progress14%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • `contextBridge.exposeInMainWorld` creates a **whitelisted** API that the page can use.
  • Keep `nodeIntegration` **false** and `contextIsolation` **true** for security.
  • All IPC calls become **Promise‑based** (`invoke`) or simple event listeners (`on`).
  • Preload scripts are the only place where Node APIs can be mixed with the renderer.

Preload Scripts & Secure Context Bridge

A preload script runs before the renderer loads any web code, in a privileged yet isolated world.

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

// expose a minimal, typed API
contextBridge.exposeInMainWorld('electronAPI', {
  // async request → returns a Promise
  getVersion: () => ipcRenderer.invoke('app:getVersion'),

  // fire‑and‑forget
  logMessage: (msg) => ipcRenderer.send('log', msg),

  // subscribe to events from main
  onUpdateAvailable: (callback) => ipcRenderer.on('update:available', (e, info) => callback(info))
});

In main.js you must enable the preload path:

new BrowserWindow({
  webPreferences: {
    preload: path.join(__dirname, '../preload/bridge.js'),
    contextIsolation: true,
    nodeIntegration: false
  }
});

Now the renderer can safely call:

document.getElementById('ver').innerText = await window.electronAPI.getVersion();
window.electronAPI.logMessage('App launched');

Never expose the full ipcRenderer object; only expose specific, typed functions.

Make it stickPractice what you've learned1 quiz · 5 practical tests · Optional activities from Electron.js Desktop App DevelopmentBrowse activities
Previous lessonFile System Access – Reading & WritingContinue to lesson 5Security Best PracticesBack to Electron.js Desktop App Development curriculum