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-closed means no application windows remain
  • quitting ends the main process
  • activate means 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:

  1. Launch the app and create one window.
  2. Close that window.
  3. On macOS, select the Dock icon and confirm a new window appears.
  4. On Windows or Linux, confirm the application exits.
  5. 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

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →