In Electron applications, you can capture the user's click on the close button by listening to the close event of the window (BrowserWindow instance). This setup occurs in the application's main process. Here is a simple implementation example:
Step 1: Create and Configure BrowserWindow
First, confirm that you have created a BrowserWindow instance. This is commonly implemented in the application's main process file (typically main.js or index.js).
javascriptconst { app, BrowserWindow } = require('electron'); function createWindow () { let win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); win.loadFile('index.html'); // Listen to the close event win.on('close', (e) => { console.log('Handling before window close'); // Insert your code here, such as prompting to save changes. // To prevent closing, call e.preventDefault(); }); win.on('closed', () => { console.log('Window has been closed'); // Perform cleanup operations here, such as releasing resources or saving data. }); return win; } app.whenReady().then(createWindow); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } });
Step 2: Listen to the close Event
In the above code, we add a close event listener to the created window. When the user attempts to close the window (for example, by clicking the close button), this event is triggered.
javascriptwin.on('close', (e) => { console.log('User attempting to close window'); // Execute logic here, such as checking if changes have been saved. // To prevent window closure, use e.preventDefault(); });
Example: Prevent Immediate Window Closure and Show a Confirmation Prompt
Here is a practical example where, when the user clicks the close button, a confirmation dialog appears asking if they really want to close the window:
javascriptconst { dialog } = require('electron'); win.on('close', (e) => { e.preventDefault(); // Prevent immediate window closure dialog.showMessageBox({ type: 'question', buttons: ['Yes', 'No'], title: 'Confirm', message: 'Confirm closing?' }).then(result => { if (result.response === 0) { // User clicked "Yes" win.destroy(); // Ignore close event and force window closure } }); });
This allows you to execute custom logic when the user attempts to close the window, and to prevent or allow window closure as needed.