Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

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

OptionWhat it sets
width, heightInitial size
minWidth, minHeightMinimum size
x, yPosition; without them the window is centred
resizableWhether the size can change, true by default
showWhether to show the window at once, true by default
backgroundColorBackground before the page loads, e.g. '#ffffff'
iconThe window icon on Windows and Linux
webPreferencesPage 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.

Thanks for reading!

Donate to the site — we work hard for you.