I'm trying to develop an app with a separate settings window (in electron). When the settings window is open and the main window is closed, I want to prevent the closing of the main window and focus the settings window.
Right now I do this as following:
window.onbeforeunload = e => {
console.log(e);
if(settingsWindow) {
settingsWindow.focus();
e.returnValue = false;
}
else e.returnValue = true;
};
This although prevents reloading the window, which I don't want. So I'm asking for a different preventing method or a way to detect if it is a reload or a close.
Greeting Elias =)
EDIT/Solution:
utilize ipcMain and ipcRenderer to handle everything with creating windows in the main process. There you can catch and prevent the close event.
MAIN.JS
const {ipcMain} = require("electron");
...
ipcMain.addListener("ASYNC_MSG", (event, arg) => {
switch(arg) {
case "OPEN_SETTINGS": createSettingsWindow(); break;
}
});
...
mainWindow.addListener("close", e => {
if(settingsWindow) {
e.preventDefault();
e.returnValue = false;
settingsWindow.focus();
}
else e.returnValue = true;
});
RENDERER.JS
const {ipcRenderer} = require("electron");
...
ipcRenderer.send("ASYNC_MSG", "OPEN_SETTINGS");
You can use 'close' event, which is called before onbeforeunload and doesn't collide with reloading
const { app, BrowserWindow } = require('electron')
app.once('ready', () => {
let main = new BrowserWindow({title: 'main'})
let settings = new BrowserWindow({title: 'settings'})
main.on('close', (event) => {
if (settings) {
event.preventDefault()
event.returnValue = false
settings.focus()
} else {
event.returnValue = true
}
})
settings.on('closed', () => {
settings = null
})
})
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