推荐答案
Electron 的 app 模块提供了许多常用事件,以下是一些常见的事件:
ready:当 Electron 完成初始化时触发。window-all-closed:当所有窗口都关闭时触发。before-quit:在应用程序开始关闭窗口之前触发。will-quit:当所有窗口都已关闭并且应用程序即将退出时触发。quit:当应用程序退出时触发。open-file:当用户想要在应用中打开一个文件时触发(macOS)。open-url:当用户想要在应用中打开一个 URL 时触发。activate:当应用程序被激活时触发(macOS)。browser-window-created:当一个新的BrowserWindow被创建时触发。web-contents-created:当一个新的webContents被创建时触发。
本题详细解读
ready 事件
ready 事件是 Electron 应用程序启动时最重要的一个事件。它表示 Electron 已经完成了初始化,可以开始创建窗口和执行其他操作。通常,你会在 ready 事件中创建主窗口并加载应用的首页。
const { app, BrowserWindow } = require('electron');
app.on('ready', () => {
const mainWindow = new BrowserWindow({ width: 800, height: 600 });
mainWindow.loadFile('index.html');
});window-all-closed 事件
window-all-closed 事件在所有窗口都关闭时触发。通常,你会在该事件中决定是否退出应用程序。在 macOS 上,通常不会直接退出应用程序,而是保持应用程序在后台运行。
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});before-quit 和 will-quit 事件
before-quit 事件在应用程序开始关闭窗口之前触发,而 will-quit 事件在所有窗口都已关闭并且应用程序即将退出时触发。这两个事件可以用于执行一些清理操作或保存应用状态。
app.on('before-quit', () => {
console.log('Application is about to quit');
});
app.on('will-quit', () => {
console.log('Application is quitting');
});quit 事件
quit 事件在应用程序退出时触发。你可以在这个事件中执行一些最后的清理操作。
app.on('quit', () => {
console.log('Application has quit');
});open-file 和 open-url 事件
open-file 事件在用户想要在应用中打开一个文件时触发(macOS),而 open-url 事件在用户想要在应用中打开一个 URL 时触发。这些事件通常用于处理文件或 URL 的打开操作。
// www.javascriptcn.com code example
app.on('open-file', (event, path) => {
event.preventDefault();
console.log('File to open:', path);
});
app.on('open-url', (event, url) => {
event.preventDefault();
console.log('URL to open:', url);
});activate 事件
activate 事件在应用程序被激活时触发(macOS)。通常,你会在该事件中重新创建主窗口(如果窗口不存在)。
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});browser-window-created 和 web-contents-created 事件
browser-window-created 事件在新的 BrowserWindow 被创建时触发,而 web-contents-created 事件在新的 webContents 被创建时触发。这些事件可以用于对新窗口或新页面进行一些初始化操作。
app.on('browser-window-created', (event, window) => {
console.log('New BrowserWindow created:', window);
});
app.on('web-contents-created', (event, webContents) => {
console.log('New webContents created:', webContents);
});