Windows and the renderer
Handle the window lifecycle
Follow macOS, Windows, and Linux conventions when the app starts, closes its windows, and becomes active again.
8 minute lesson
Electron APIs such as BrowserWindow are not ready when the module first loads. Create the first window after app.whenReady() resolves:
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
On Windows and Linux, closing every window normally quits the app. On macOS, an application usually remains active and creates a new window when its Dock icon is selected.
These are different lifecycle events:
- closing a window destroys that window
window-all-closedmeans no application windows remain- quitting ends the main process
activatemeans the operating system brought the app forward
Do not keep using a destroyed BrowserWindow reference. Before sending a menu event, check that the target exists and has not been destroyed.
Test the complete sequence on every supported platform:
- Launch the app and create one window.
- Close that window.
- On macOS, select the Dock icon and confirm a new window appears.
- On Windows or Linux, confirm the application exits.
- Quit from the menu and confirm no background process remains.
If the real app has unsaved changes, decide where close confirmation lives. Test both cancellation and confirmed quit; lifecycle code that loses data is not complete.
Lesson completed