The BrowserWindow
BrowserWindow is the Electron class that creates an app window. Each window is an operating system frame with a page inside it, running in its own renderer process. Windows are created only in the main process.
Size and title
Window options are passed to the constructor as an object. Open main.js:
// main.js
const { app, BrowserWindow } = require('electron');
function createWindow() {
const win = new BrowserWindow({
width: 900,
height: 600,
minWidth: 400,
minHeight: 300,
title: 'Notes',
});
win.loadFile('index.html');
}
app.whenReady().then(createWindow);The window opens at 900 by 600, and the mouse cannot make it smaller than 400 by 300. The title is visible until the page loads; then the title tag from the HTML replaces it.
Main options
| Option | What it sets |
|---|---|
width, height | Initial size |
minWidth, minHeight | Minimum size |
x, y | Position; without them the window is centred |
resizable | Whether the size can change, true by default |
show | Whether to show the window at once, true by default |
backgroundColor | Background before the page loads, e.g. '#ffffff' |
icon | The window icon on Windows and Linux |
webPreferences | Page settings: the preload script and security |
The full list is in the Electron documentation, BrowserWindow section.
Showing without a flash
While the page loads, the window can be empty. To hide this, the window is created hidden and shown on the ready-to-show event:
// main.js
const win = new BrowserWindow({ width: 900, height: 600, show: false });
win.loadFile('index.html');
win.once('ready-to-show', () => {
win.show();
});The window appears with the page already rendered.
Controlling the window
The window object has methods and events:
// main.js
win.setTitle('Notes — 3 items');
win.maximize();
win.on('closed', () => {
console.log('Window closed');
});setTitle changes the title and maximize maximizes the window. There are also minimize, focus, close and setSize. The closed event fires after the window is closed — the message appears in the terminal.
The preload script
webPreferences holds the path to the preload script:
// main.js
const path = require('node:path');
const win = new BrowserWindow({
width: 900,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
});__dirname is the folder containing main.js. The script itself is covered in "The preload script and contextBridge".
Common mistake
The preload path must be absolute. preload: 'preload.js' does not work: the script is not loaded and the page does not get its functions. Always build the path with path.join(__dirname, 'preload.js'). loadFile does not need this: it resolves the path from the app root.