macosvue.jselectronfile-managementelectron-vue

How to natively show the Save Changes Dialog when closing an Electron app?


I'm creating an Electron app. I save the user's progress in a file. I want the app to show the usual'Save changes before closing'' message when the user has not saved and tries to close the app.

I could show a custom dialogue. However, I would want to do it the native way.

(Example: On macOS, when you edit a file, the red button changes, letting know the user that the app has unsaved content)

Example of what I want to accomplish

I know this has to be done probably inside the Electron's listener for a closing app:

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

... preventing quit() from being called. And instead handling the unsaved file state and dialog.

PD: I already handle the logic to determine whether the user has saved their progress. I just want to know how to set the 'Unsaved' state for my electron app and correctly handle it.

(The example is Visual Studio Code, which is also an Electron App)


Solution

  • I usually use a global variable to indicate changes had occured and for example in the case of closing the app: Code in the main:

    mainWindow.on('close', function (event) {
    if (global.savetoask== 'Yes') {
       event.preventDefault();
        //send a ipc message to request a confirm dialog
    .............
              } else {
                app.exit();
              }
            });