If the user selects the save button, we must save the data and close the window using window.close() . But, with this approach, we get an infinite loop that asks to save unsaved work, because window.close() will again generate a close window event.
To solve this problem, we need to declare a new boolean type var forceQuit , which is initially set to false , then we set it to true after saving the data or if the user decided to just close without saving the data.
import { app, BrowserWindow, dialog } from 'electron'; let win = null; let forceQuit = false; app.on('ready', () => { win = new BrowserWindow({ // Your window options.. }); mainWindow.on('close', e => { if (!forceQuit) { const clickedButtonId = dialog.showMessageBox(mainWindow, { type: 'warning', buttons: ['Save', 'Cancel', 'Don't save'], cancelId: 1, title: 'Confirm', message: 'You have unsaved work!' }); if (clickedButtonId === 0) { e.preventDefault(); console.log('Saving...'); /** Here do your data saving logic */ forceQuit = true; win.close(); } else if (clickedButtonId === 1) { e.preventDefault(); } else if (clickedButtonId === 2) { forceQuit = true; win.close(); } } }); });
parse
source share