I have an Electron application that needs to save some data when it's closed by the user (e.g. just after the user clicked on the "Close" button).
The data is available at the renderer process, so it should be notified before the application dies.
The Electron API for Browser Window mentions a close
method, but it seems this is done by the main process, not the renderer one (if I'm not mistaken).
I tried using WebContents.send
from the main process to notify the renderer process, but it seems that, because the message is asynchronous, the application is closed before the renderer process has the time to actually perform the operations.
You can just use the normal unload
or beforeunload
events in the renderer process:
window.addEventListener('unload', function(event) {
// store data etc.
})
So far, the simplest solution that worked for me consists in doing the following:
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()
;close
event notification, it saves its data, then sends the main process an IPC message (e.g. closed
);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.
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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With