The app lifecycle
The lifecycle is the stages of an app's life: startup, work, closing windows, exit. The app object from the electron module reports each stage with an event. They must be handled properly because Windows, Linux and macOS behave differently.
Ready
Windows can be created only after Electron has initialized. The app.whenReady() promise is there for that:
// main.js
const { app, BrowserWindow } = require('electron');
function createWindow() {
const win = new BrowserWindow({ width: 900, height: 600 });
win.loadFile('index.html');
}
app.whenReady().then(() => {
createWindow();
});The promise resolves once after startup, and the window opens. It is the same as listening to the ready event, only more convenient.
All windows closed
On Windows and Linux an app usually exits when its last window is closed. On macOS it stays in the Dock until the user chooses Quit or presses Cmd+Q:
// main.js
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});process.platform is 'darwin' on macOS, 'win32' on Windows and 'linux' on Linux. On Windows closing the window ends the app, while on a Mac it keeps running without windows.
Reactivation
If an app on macOS has no windows and the user clicks its Dock icon, the activate event fires. The app should open a window again:
// main.js
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});BrowserWindow.getAllWindows() returns an array of open windows. The listener is added inside whenReady so that no window is created too early.
Quitting
| Event | When it fires |
|---|---|
ready | Electron is ready, windows can be created |
window-all-closed | The last window was closed |
activate | The Dock icon was clicked (macOS) |
before-quit | The app starts quitting |
will-quit | All windows are closed, exit is about to happen |
quit | The app is quitting |
before-quit is handy for a final save:
// main.js
app.on('before-quit', () => {
console.log('The app is closing');
});The message appears in the terminal when you quit the app.
Common mistake
If you create a window right at the top of main.js, without whenReady, Electron stops with Cannot create BrowserWindow before app is ready. Call everything that works with windows, menus and the tray after the app is ready: inside app.whenReady().then(...).