Learn Electron · 3/12

Window Management and UI Basics

8 min read

When building a desktop application with Electron, you are essentially managing two very different worlds: the Node.js backend environment (the Main process) and the Chromium web frontend (the Renderer process).

Imagine you are managing an office building. The Main process is the building manager sitting in the basement. The manager has the authority to build new office rooms, demolish them, or change their locks. The individual office rooms are the UI windows where the actual workers (HTML, CSS, JavaScript) do their jobs. If the building manager forgets to build an office, the workers have nowhere to sit. If the manager builds an office but forgets to give it a secure door, anyone can wander in.

In this guide, we will learn how to ask the building manager to construct, configure, and manage these offices efficiently, without causing memory leaks or security disasters.


1. Creating and Configuring the BrowserWindow

The Problem

Node.js applications run in a terminal. They do not have a Graphical User Interface (GUI). If you want your users to interact with buttons, forms, and visuals rather than typing commands into a black box, you need a way to display web content on the user's desktop screen.

The Solution: BrowserWindow

The BrowserWindow is an Electron module used to create and control browser windows. It is the fundamental building block of an Electron app's UI. When you instantiate a BrowserWindow, Electron spawns a new Chromium renderer process to display your web page.

Industry Standards and Under the Hood

In the industry, creating a window is not just about giving it a width and height. It is heavily about security. Because Electron apps have access to the user's file system via Node.js, displaying untrusted web content can be highly dangerous.

To solve this, we use webPreferences to enforce a strict boundary:

  • nodeIntegration: false: Prevents the frontend HTML/JS from directly using Node.js features like require('fs').
  • contextIsolation: true: Ensures that the frontend JavaScript and the internal Electron JavaScript run in separate environments, preventing malicious scripts from overriding core behaviors.

If you set nodeIntegration: true and load a remote website, you are essentially handing over the keys to your computer, your bank account, and your browser history to a stranger. Don't do it.

Practical Example

Here is how you safely construct a window in your main.js file:

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

let mainWindow; // Keep a global reference to avoid garbage collection

app.whenReady().then(() => {
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    minWidth: 800, // Prevent users from shrinking the app to a microscopic pixel
    minHeight: 600,
    backgroundColor: '#1e1e1e', // Prevents a blinding white flash before your dark-mode UI loads
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'), // The secure bridge between Main and Renderer
      contextIsolation: true, 
      nodeIntegration: false 
    }
  });

  // Load the actual UI
  mainWindow.loadFile('index.html');

  // Open Developer Tools for debugging (usually removed in production)
  // mainWindow.webContents.openDevTools();
});

What happens here?

  1. We wait for app.whenReady() because Electron needs a few milliseconds to initialize its underlying C++ and Chromium engines. You cannot create a window before this event.
  2. We define minimum dimensions. Users will absolutely try to resize your app into a tiny sliver just to see what happens. minWidth stops them.
  3. We set a backgroundColor. Chromium naturally defaults to a white background. If your app is dark-themed, users will get flashbanged for half a second while the CSS loads. This property saves their eyes.

2. Frameless Windows and Custom Title Bars

The Problem

By default, the operating system (Windows, macOS, Linux) wraps your BrowserWindow in a native "frame". This frame includes the standard close, minimize, and maximize buttons, along with a title bar. This native frame often clashes horribly with your application's custom branding (think of Discord, Spotify, or VS Code—they do not use the ugly default Windows 95-style borders).

The Solution: frame: false or titleBarStyle

You can instruct Electron to strip away the OS window frame. Once removed, you have a completely blank canvas. However, this introduces a new problem: users can no longer drag the window around the screen, nor can they close it! You must rebuild this functionality using CSS and IPC (Inter-Process Communication).

Practical Example

First, tell the Main process to drop the frame:

javascript
// main.js
const win = new BrowserWindow({
  width: 800,
  height: 600,
  frame: false, // Removes the standard OS frame completely
  // On macOS, you often use titleBarStyle instead to keep the native traffic light buttons:
  // titleBarStyle: 'hidden' 
});

Now, your window looks beautiful but is permanently stuck in the middle of the screen. We need to define a "drag region" using a special Electron CSS property.

css
/* style.css */
body {
  margin: 0;
  padding: 0;
}

.custom-titlebar {
  height: 32px;
  background-color: #2c2c2c;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  /* THIS IS THE MAGIC SAUCE 🪄 */
  -webkit-app-region: drag; 
}

/* ⚠️ CRITICAL INDUSTRY FIX ⚠️ */
.custom-titlebar button {
  /* If you don't do this, users cannot click the buttons inside the drag region! */
  -webkit-app-region: no-drag; 
}
html
<!-- index.html -->
<div class="custom-titlebar">
  <span>My Awesome App</span>
  <div class="window-controls">
    <button id="minimize-btn">_</button>
    <button id="close-btn">X</button>
  </div>
</div>

Under the hood: When you apply -webkit-app-region: drag, Electron intercepts mouse events in that specific DOM area and forwards them to the OS window manager, telling it "the user is dragging the application." You must explicitly use no-drag on interactive elements inside that bar, or the OS will treat your button clicks as dragging attempts.


3. Handling Multiple Windows and Child Windows

The Problem

Sometimes one window is not enough. You might need a pop-up for application settings, a secondary window for a detached video player, or a confirmation dialog. If you just spawn a completely independent window, it might get lost behind the main window, or worse, the user might close the main app while the settings pop-up remains floating on the screen like an orphaned ghost.

The Solution: Child Windows and parent Property

Electron allows you to bind a new BrowserWindow to an existing one by passing the parent property. You can also make the child window a modal, meaning it disables the parent window until the child is closed.

Practical Example

Let's say the user clicks "Settings". We want to open a modal that forces them to finish their settings changes before returning to the main app.

javascript
// main.js
let mainWindow;
let settingsWindow; // Keep a reference!

function createSettingsWindow() {
  // Prevent opening multiple settings windows
  if (settingsWindow) {
    settingsWindow.focus();
    return;
  }

  settingsWindow = new BrowserWindow({
    width: 400,
    height: 500,
    parent: mainWindow, // Bind to the main window
    modal: true,        // Lock the main window until this is closed
    show: false,        // Don't show immediately (prevent flicker)
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  });

  settingsWindow.loadFile('settings.html');

  // Show gracefully only when React/HTML is fully parsed and ready
  settingsWindow.once('ready-to-show', () => {
    settingsWindow.show();
  });

  // VERY IMPORTANT: Memory Management
  settingsWindow.on('closed', () => {
    settingsWindow = null; // Free up memory!
  });
}

Memory Management Note:
Notice the settingsWindow = null; part. If you do not nullify the window reference when it is closed, JavaScript's Garbage Collector will not clean it up because the variable still holds a reference. Do this enough times, and your application will consume memory until the user's computer sounds like a jet engine taking off.


4. Integrating Modern Frameworks (React/Vue) Conceptually

The Problem

Writing vanilla HTML, CSS, and document.getElementById works fine for a simple tool, but enterprise desktop applications have complex state, routing, and reactivity. You want to use React, Vue, or Svelte.
However, Electron only understands raw HTML and JS. Furthermore, React uses a development server (like localhost:5173) with Hot Module Replacement (HMR) during development, but in production, you just have a folder of static files.

The Solution: The Two-Step Dance

To integrate a modern framework, you must completely decouple your mental model.

  1. The UI (React/Vue) is built with a standard bundler like Vite or Webpack.
  2. The Backend (Electron) simply points its BrowserWindow to wherever the UI lives.

During development, Electron points to a URL. In production, Electron points to a compiled file.

Practical Example: Development vs. Production

Think of the Electron Main process as a web browser. When you are writing React code, your Vite server runs locally. You just tell Electron to navigate to it.

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

// A simple way to check if we are in development or production
const isDev = !app.isPackaged; 

function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true
    }
  });

  if (isDev) {
    // DEVELOPMENT: Load the React/Vue dev server
    // This allows Hot Module Replacement (HMR) to work flawlessly
    win.loadURL('http://localhost:5173');
    win.webContents.openDevTools();
  } else {
    // PRODUCTION: Load the static index.html built by Vite/Webpack
    win.loadFile(path.join(__dirname, '../dist/index.html'));
  }
}

app.whenReady().then(createWindow);

Industry Standard Tooling:
While you can set up Vite and Electron manually, managing the simultaneous startup of the Vite server and the Electron process is tedious. In the industry, developers overwhelmingly use boilerplate bundlers designed specifically for this architecture.

The most prominent tool today is electron-vite. It provides a pre-configured structure out of the box where the main, preload, and renderer (React/Vue) folders are separated, and it handles the complex build pipeline for you.


Further Reading & References

Keep these bookmarks handy, as the Electron API surface is massive and constantly updating:

Challenge

Challenge

Your task is to implement the logic for creating and managing two Electron windows: a primary application window and a secondary, modal settings window. You must adhere to modern security and performance best practices.

Main Window Requirements (createMainWindow function):

  1. Instantiate a new BrowserWindow.
  2. Configure webPreferences for maximum security: nodeIntegration must be false and contextIsolation must be true.
  3. Set the initial dimensions to 800x600 pixels and the minimum dimensions to 600x400 pixels.
  4. The window must be frameless.
  5. The window should be created in a hidden state and only shown when the ready-to-show event is fired.
  6. It should load the URL 'https://www.freecodecamp.org'.
  7. Assign the created window object to the global mainWindow variable.

Settings Window Requirements (createSettingsWindow function):

  1. This function will receive the parent window object as an argument.
  2. Instantiate a new BrowserWindow that is a modal child of the parent window.
  3. Set its dimensions to 400x500 pixels and make it non-resizable.
  4. It should load the URL 'https://www.freecodecamp.org/news'.
  5. To prevent memory leaks, you must listen for the closed event and set the settingsWindow variable back to null inside the event handler.

Expected result

The completed code should correctly implement two functions.

createMainWindow function:

javascript
function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    minWidth: 600,
    minHeight: 400,
    frame: false,
    show: false, // Initially hide the window
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
    }
  });

  mainWindow.loadURL('https://www.freecodecamp.org');

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  // ... (ipcMain part remains for context)
}

createSettingsWindow function:

javascript
function createSettingsWindow(parentWindow) {
  settingsWindow = new BrowserWindow({
    width: 400,
    height: 500,
    parent: parentWindow,
    modal: true,
    resizable: false,
    show: true // Modal windows are typically shown immediately
  });

  settingsWindow.loadURL('https://www.freecodecamp.org/news');

  // Crucial for memory management
  settingsWindow.on('closed', () => {
    settingsWindow = null;
  });
}
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.