电子:关闭w X vs右键单击停靠并退出

fro*_*sty 6 javascript electron

在我的Electron应用程序中,我想做一些在其他OSX应用程序中经常执行的操作.那是......我想不要关闭红色X的应用程序点击右上角.但是,如果他们右键单击Dock中的应用程序图标,然后说退出,那么我想退出该应用程序.我该怎么做呢?

我已经尝试使用onbeforeunloadrendererProcess中的事件,以及browserWindow.on("close", fn)尝试阻止它的事件.问题是他们都提交了onbeforeunload事件.我无法分辨出被点击的红色X和右键单击的停靠栏图标之间的区别,并被告知要退出.你能帮忙的话,我会很高兴.还有其他人在Electron for OSX中做过这个吗?

小智 12

试试这个

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
       */
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案是正确和简洁的。感谢那。对正在发生的事情进行一些解释以帮助澄清:应用程序的 `before-quit` 事件触发 _before_ 浏览器窗口已关闭,因此如果您从关闭浏览器窗口以外的其他地方退出(停靠栏上下文菜单、应用程序菜单等)` before-quit` 将在 mainWindow 的 `close` 事件之前触发。如果通过单击主窗口上的 x 关闭,窗口的 `close` 事件将首先触发。http://electron.atom.io/docs/api/app/#event-before-quit (2认同)

Sno*_*man 6

这是唯一对我有用的答案:

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);
Run Code Online (Sandbox Code Playgroud)

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