Closing application and notifying renderer process

…衆ロ難τιáo~ 提交于 2019-12-04 09:48:41

So far, the simplest solution that worked for me consists in doing the following:

  1. On the main process, the BrowserWindow listens on the close event, and when it happens, it sends a message via webContents to the renderer process. It also prevents the application from being immediately closed by calling event.preventDefault();
  2. The renderer process is always listening on IPC messages from the main process, then when it receives the close event notification, it saves its data, then sends the main process an IPC message (e.g. closed);
  3. The main process has previously set a hook to listen to the renderer IPC messages (ipcMain.on), so when the closed message arrives, it finally closes the program (e.g. via app.quit()).

Note that, if I understood it correctly, calling app.quit() sends another close event to the BrowserWindow, so it will loop unless you prevent it somehow. I used a dirty hack (quit the second time the close event is called, without calling event.preventDefault()), but a better solution must exist.

You can just use the normal unload or beforeunload events in the renderer process:

window.addEventListener('unload', function(event) {
  // store data etc.
})

On the Main process:

    const ipc = require('electron').ipcMain;
    let status = 0;

    mainWindow.on('close', function (e) {
    if (status == 0) {
      if (mainWindow) {
        e.preventDefault();
        mainWindow.webContents.send('app-close');
      }
    }
  })

ipc.on('closed', _ => {
  status = 1;
  mainWindow = null;
  if (process.platform !== 'darwin') {
    app.quit();
  }
})

On the renderer process:

const electron = require('electron');
const ipc = electron.ipcRenderer;

ipc.on('app-close', _ => {

        //do something here...

        ipc.send('closed');
    });
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!