Electron Main Process, Renderer Process, and Preload Scripts

Understand the roles of the main process, renderer process, and preload scripts as a foundation for Vue integration and safe IPC.

🎯 Introduction

An Electron app does not run all its code in the same environment. Window management and system operations run in the main process, page code runs in the renderer process, and a preload script can provide a safe communication entry point between them.

This article answers one question: which process should run each piece of code? The detailed window lifecycle is covered separately after the next article.

By the end of this article, you will be able to:

  • Distinguish the roles of the main process, renderer process, and preload scripts.
  • Understand how one main process manages multiple windows.
  • Observe that different windows have independent page state.
  • Establish clear process boundaries for Vue integration in the next article and IPC later.

🧱 Electron's process model

When an Electron app starts, it runs the file specified by main in package.json. This code runs in the main process. Each app has one main process, which manages the entire application.

The main process creates windows with BrowserWindow. After a window loads HTML, page code runs in a renderer process. During development, think of each window as a separate browser page: each has its own DOM and JavaScript variables, and page state is not shared automatically.

A preload script runs before page scripts. It exposes a small set of specific desktop capabilities to the renderer. This article introduces where it fits; the IPC chapter explains how to use it.

EnvironmentMain responsibilityCommon contents
Main processManage the app, windows, and system capabilitiesapp, BrowserWindow
Renderer processDisplay pages and handle interface interactionsHTML, CSS, DOM, page scripts
Preload scriptSafely expose limited desktop capabilities to the pagecontextBridge, restricted IPC APIs
Do not enable nodeIntegration just to let pages use Node.js APIs directly. Keep Electron's default isolation settings and expose necessary capabilities through a preload script.

🛠 Create two independent page environments

Here, one main process creates two windows. Both load the same HTML and JavaScript, but each keeps its own counter state.

First, create the main process entry point:

main.js
const { app, BrowserWindow } = require('electron');
const path = require('node:path');

const windows = new Set();

function createWindow(name) {
    const win = new BrowserWindow({
        width: 460,
        height: 360,
        title: name,
    });

    windows.add(win);
    win.loadFile(path.join(__dirname, 'index.html'), {
        query: { name },
    });

    win.on('closed', () => {
        windows.delete(win);
    });

    return win;
}

function createApplicationWindows() {
    const firstWindow = createWindow('Window A');
    const secondWindow = createWindow('Window B');
    const [x, y] = firstWindow.getPosition();

    secondWindow.setPosition(x + 60, y + 60);
}

app.whenReady().then(() => {
    createApplicationWindows();

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createApplicationWindows();
        }
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

windows stores window objects that still exist. Remove a window from the set when it closes to avoid retaining invalid references.

Both windows load the same page and get their names from query parameters:

index.html
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta
            http-equiv="Content-Security-Policy"
            content="default-src 'self'; script-src 'self'"
        />
        <title>Process model example</title>
    </head>
    <body>
        <h1 id="window-name"></h1>
        <p>Current count: <span id="count">0</span></p>
        <button id="add">Add one</button>

        <script src="./renderer.js"></script>
    </body>
</html>

Write the page interaction code in the renderer process:

renderer.js
const params = new URLSearchParams(window.location.search);
const windowName = params.get('name');
const nameElement = document.querySelector('#window-name');
const countElement = document.querySelector('#count');
const addButton = document.querySelector('#add');

let count = 0;

nameElement.textContent = windowName;
document.title = windowName;

addButton.addEventListener('click', () => {
    count += 1;
    countElement.textContent = count;
});

Run the project:

npm start

“Window A” and “Window B” open. Click “Add one” repeatedly in Window A: Window B's count stays unchanged because the windows have independent DOMs and count variables.

No IPC is needed here: the windows only modify their own page state and do not exchange data. When windows need to share information, use the main process and IPC to pass it between them.


Window creation, reactivation, and quitting belong to the application lifecycle and will be covered together in a subsequent article. For now, remember this prerequisite: create BrowserWindow only after app.whenReady() resolves.


💡 Where should code go?

Start by considering what the code operates on:

  • Create windows, quit the app, and open system dialogs in the main process.
  • Update text, listen for button clicks, and change page styles in the renderer process.
  • When a page needs desktop capabilities, expose a purpose-specific API through a preload script.

For example, this code belongs in the main process because BrowserWindow creates desktop windows:

const win = new BrowserWindow({
    width: 600,
    height: 400,
});

This code belongs in the renderer process because it operates on the page DOM:

document.querySelector('#title').textContent = 'Hello, Electron';

The renderer cannot call main process functions directly. Use a preload script and IPC to establish an explicit communication channel for cross-process work.


🧾 Summary

  • An Electron app has one main process to manage the app, windows, and system capabilities.
  • Pages loaded by BrowserWindow run in independent page environments.
  • Different windows do not automatically share DOMs or JavaScript variables.
  • Window creation must wait for app.whenReady(); the detailed lifecycle is covered later.
  • Preload scripts connect the renderer to desktop capabilities; communication details are covered later.

❓ Questions and answers

Q1: Can an Electron app create multiple windows?

Yes. The main process can create multiple BrowserWindow instances and load different pages or the same page in each.

Q2: Are JavaScript variables automatically shared between two windows?

No. Each window has an independent page environment. Pass shared data through the main process and IPC.

Q3: Does every window always have its own operating system process?

Not necessarily. Chromium handles the underlying process allocation. Rely on page isolation between windows rather than a specific number of operating system processes.

Q4: Why doesn't closing one window quit the app?

Other windows are still open. window-all-closed fires only after every window closes.

Q5: Is the preload script part of the renderer process?

It runs with its designated window, but in a context isolated from the page and with more privileges than ordinary page code. It should expose only the capabilities the page needs.


🧪 Practice

Exercise 1: Complete the code to create another window named “Window C”:

function createApplicationWindows() {
    createWindow('Window A');
    createWindow('Window B');

    // Write your code here
}

Exercise 2: Complete the activation handler to recreate windows when none exist:

app.on('activate', () => {
    // Write your code here
});

After completing the exercises, change the count in each of the three windows and observe whether the values affect one another.


🎉 You now understand Electron's process responsibilities! Next, we will integrate Vue pages, then use preload scripts and IPC to request main process capabilities.