Electron click close button pop-up box to confirm

The reason:

After the user clicks the close button, a pop-up box with confirm and cancel buttons pops up for the user to decide whether to close the client.

Solution:

Close event listening for the mainWindow in main.js. Prevent default behavior (must) before executing the corresponding handler on dialog’s callback function. In this case, the popup confirms minimization and confirms closure

const {app, BrowserWindow, globalShortcut, dialog, Menu, ipcMain} = require('electron')
const path = require('path')

let mainWindow

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800.height: 600.webPreferences: {
      nodeIntegration: true.preload: path.resolve(path.join(__dirname, './src/preload.js'))}}); mainWindow.loadFile('index.html');
  mainWindow.on('close'.(e) = > {
    dialog.showMessageBox({
      type: 'info'.title: 'Information'.defaultId: 0.message: 'Are you sure you want to close it? '.buttons: [Minimize.'Straight out']},(index) = >{
      if(index===0){
        e.preventDefault();		// Block default behavior, be sure to have it
        mainWindow.minimize();	// Call the minimize instance method
      } else {
        mainWindow = null;
        //app.quit(); // Do not use quit(); You can play it twice
        app.exit();		//exit() closes the client directly without executing quit();}})}); } app.on('ready', createWindow)
app.on('activate'.function () {
  if (mainWindow === null) createWindow()
});
Copy the code
other

If you need any other operations, add them to the buttons in the dialog. Then, in the callback function, determine the value of the index returned and perform the operations.