0Pricing
Electron Desktop App Development · 课时

管理应用生命周期事件

处理 `ready`、`window-all-closed`、`activate` 和 `quit` 等各种应用生命周期事件,确保应用行为正常

管理应用生命周期事件 是 CoddyKit 上的免费 Electron Desktop App Development 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Electron Desktop App Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Electron Desktop App Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

App's Journey: Lifecycle Events

Just like people, software applications have a lifecycle! They start, run, and eventually close. In Electron, these stages are managed through "lifecycle events".

  • These events let your app react to important moments, like when it's ready to show a window or when all its windows are closed.
  • Properly handling them ensures your app behaves predictably and professionally on different operating systems.

Meet the `app` Module

Electron provides a special module called app. This module is the heart of your application's lifecycle management.

  • You use the app module to control your application's events.
  • It allows you to listen for events like when the app is ready, when windows close, or when the app is about to quit.
  • It also provides methods to manage the app, such as quitting or restarting.

App is Ready! The `ready` Event

The ready event is the most fundamental lifecycle event. It fires when Electron has finished initializing and is ready to create browser windows and interact with the system.

You must wait for this event before performing most operations. Try running this simple example:

const { app } = require('electron');

app.on('ready', () => {
  console.log('Electron app is ready!');
  // In a real app, you'd create windows here.
});

// Minimal handler to allow the app to quit when needed
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

Launching Your First Window

The ready event is typically where you create your application's main window. This ensures the Electron environment is fully initialized before the UI appears.

We import BrowserWindow and create an instance, loading simple HTML content directly.

const { app, BrowserWindow } = require('electron');

let mainWindow;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 400,
    height: 300
  });

  // Load a simple HTML string directly for a self-contained example
  mainWindow.loadURL('data:text/html;charset=utf-8,<h1>Hello Electron!</h1><p>This is your window.</p>');

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

Closing All Windows? `window-all-closed`

The window-all-closed event fires when all of your application's windows have been closed. How you respond depends on the operating system.

  • On Windows and Linux, apps usually quit when all windows close.
  • On macOS, apps often stay active in the dock.

This code ensures the app quits on Windows/Linux but stays open on macOS.

const { app, BrowserWindow } = require('electron');

let mainWindow;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 400,
    height: 300
  });
  mainWindow.loadURL('data:text/html;charset=utf-8,<h1>Close Me!</h1>');
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  // On macOS, it's common for apps to remain active in the dock
  // until the user quits explicitly with Cmd + Q.
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

Reactivating Your macOS App

The activate event is specific to macOS. It fires when the application is activated, typically when the user clicks on the app's icon in the dock, but no windows are currently open.

This is where you'd re-create a window if mainWindow is null.

const { app, BrowserWindow } = require('electron');

let mainWindow;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 400,
    height: 300
  });
  mainWindow.loadURL('data:text/html;charset=utf-8,<h1>Activated!</h1><p>A new window was opened.</p>');
  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.on('ready', createWindow);
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On macOS, re-create a window when the dock icon is clicked
  // and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});

Last Chance: `will-quit`

The will-quit event fires just before the application begins to close its windows and quit. This is your last opportunity to perform synchronous cleanup operations.

  • For example, you might save unsaved data or close database connections.
  • This event is emitted before the quit event.
const { app, BrowserWindow } = require('electron');

let mainWindow;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 400,
    height: 300
  });
  mainWindow.loadURL('data:text/html;charset=utf-8,<h1>Will Quit Demo</h1>');
  mainWindow.on('closed', () => { mainWindow = null; });
}

app.on('ready', createWindow);
app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } });
app.on('activate', () => { if (mainWindow === null) { createWindow(); } });

app.on('will-quit', (event) => {
  console.log('Application is about to quit! Performing final cleanup...');
  // event.preventDefault(); // Uncomment to prevent quitting
  // Perform synchronous cleanup here, e.g., save data.
});

The Final Goodbye: `quit`

The quit event is emitted when the application successfully exits. By this point, all windows have been closed, and the main process is shutting down.

  • This event is primarily for logging or very simple, final notifications.
  • It's generally too late to perform significant cleanup or prevent the app from quitting.
const { app, BrowserWindow } = require('electron');

let mainWindow;

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 400,
    height: 300
  });
  mainWindow.loadURL('data:text/html;charset=utf-8,<h1>Quit Demo</h1>');
  mainWindow.on('closed', () => { mainWindow = null; });
}

app.on('ready', createWindow);
app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } });
app.on('activate', () => { if (mainWindow === null) { createWindow(); } });
app.on('will-quit', () => { console.log('Will quit...'); });

app.on('quit', (event, exitCode) => {
  console.log(`Application has quit with code: ${exitCode}`);
  // This is the very last event.
});

Lifecycle Event Check

You've learned about several key Electron application lifecycle events. Now, let's test your understanding!

Lifecycle Events: Key Takeaways

Great job! You've learned how to manage your Electron application's lifecycle, ensuring it starts, runs, and quits gracefully on different operating systems.

  • The app module is central to event handling.
  • ready is crucial for initialization and window creation.
  • window-all-closed and activate handle window behavior across platforms.
  • will-quit and quit manage the final stages of app termination.

Mastering these events is fundamental for building robust Electron applications. Keep practicing!

常见问题解答

「管理应用生命周期事件」课时是免费的吗?

是的 — 「管理应用生命周期事件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Electron Desktop App Development 课程的其余内容,请升级到 CoddyKit PRO。 Electron Desktop App Development 课程共包含 4 节课。

「管理应用生命周期事件」这节课中我会学到什么?

处理 `ready`、`window-all-closed`、`activate` 和 `quit` 等各种应用生命周期事件,确保应用行为正常 你通过在浏览器中直接运行的动手代码来练习 Electron Desktop App Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Electron Desktop App Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Electron Desktop App Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「管理应用生命周期事件」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Electron Desktop App Development 课中编写并运行代码吗?

能。每节 Electron Desktop App Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 管理应用生命周期事件
  2. 实现自动更新
  3. 崩溃报告
  4. 深层链接与协议处理器
← 返回 Electron Desktop App Development