Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Electron: Close w X vs right click dock and quit

In my Electron app, I would like to do something that is done very often in other OSX apps. That is... I would like to NOT close the app of the red X is clicked in the top right. But, if they right click the app icon in the dock, and say Quit, then I would like to quit the app. How do I do this?

I have tried using the onbeforeunload event from the rendererProcess, as well as the browserWindow.on("close", fn) event to try and prevent this. The problem is that they both file the onbeforeunload event. And I can't tell the different between the red X being clicked and the dock icon being right clicked and told to quit. Any help would be nice. Has anyone else done this in Electron for OSX?

like image 217
frosty Avatar asked Jan 26 '16 06:01

frosty


Video Answer


2 Answers

try this

if (process.platform === 'darwin') {
  var forceQuit = false;
  app.on('before-quit', function() {
    forceQuit = true;
  });
  mainWindow.on('close', function(event) {
    if (!forceQuit) {
      event.preventDefault();

      /*
       * your process here
       */
    }
  });
}
like image 153
Jeng Wittawat Avatar answered Oct 02 '22 07:10

Jeng Wittawat


This is the only answer that worked for me:

const electron = require('electron');
const app = electron.app;

let willQuitApp = false;
let window;

app.on('ready', () => {
  window = new electron.BrowserWindow();

  window.on('close', (e) => {
    if (willQuitApp) {
      /* the user tried to quit the app */
      window = null;
    } else {
      /* the user only tried to close the window */
      e.preventDefault();
      window.hide();
    }
  });

  window.loadURL('foobar'); /* load your page */
});

/* 'activate' is emitted when the user clicks the Dock icon (OS X) */
app.on('activate', () => window.show());

/* 'before-quit' is emitted when Electron receives 
 * the signal to exit and wants to start closing windows */
app.on('before-quit', () => willQuitApp = true);

via https://discuss.atom.io/t/how-to-catch-the-event-of-clicking-the-app-windows-close-button-in-electron-app/21425/8

like image 29
Snowman Avatar answered Oct 02 '22 08:10

Snowman