Reputation: 744
I wanted to prevent my electron app from closing so I can trigger some code (like saving data) before the end of my application from the render process.
Since e.PreventDefault() didn't worked for me (from both render and main process) I had to found another way. I wanted to share it if someone had the same problem than me.
You can find my answer below :)
Upvotes: 1
Views: 546
Reputation: 744
So. From the render process. You can use window.onbeforeunload
to prevent the window from closing by returning any value (false, true or any string).
Here is just created a boolean called "CanCloseWindow" that will return something if false inside the window.onbeforeunload function to prevent my window from closing.
Electron remote.getCurrentWindow() will return the current BrowserWindow object. I can use that to get the .on('close') event.
If "CanCloseWindow" is false. I will launch a promise.allSettled with all the tasks I want to run before my application is closing. I can also launch synchrone tasks after if I wanted to.
Once finished. I can set the boolean "CanCloseWindow" to true, and ask the application to try to close it's windows again with app.quit()
All this code will be executed again, but since CanCloseWindow is true, my tasks won't run, and my application will close.
var CanCloseWindow = false;
window.onbeforeunload = function(e){
if(CanCloseWindow === false) {return false}
}
remote.getCurrentWindow().on('close', ()=>{
if(CanCloseWindow === false){
var editorconfig = EditorConfig.getInstance();
Promise.allSettled([
editorconfig.set('.BrowserWindow.x', CurrentWindow.getPosition()[0]),
editorconfig.set('.BrowserWindow.y', CurrentWindow.getPosition()[1]),
editorconfig.set('.BrowserWindow.width', CurrentWindow.getSize()[0]),
editorconfig.set('.BrowserWindow.height', CurrentWindow.getSize()[1]),
editorconfig.set('.BrowserWindow.fullscreen', CurrentWindow.isFullScreen())
])
.then((results)=>{
CanCloseWindow = true;
remote.app.quit();
})
}
})
Upvotes: 2