Elias
Elias

Reputation: 4122

Electron | onbeforeunload prevents reloading

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");

Upvotes: 3

Views: 3352

Answers (2)

pergy
pergy

Reputation: 5531

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
  })
})

Upvotes: 1

Elias
Elias

Reputation: 4122

Soo after some more trial and error I found out that this works:

window.onbeforeunload = e => {
    console.log(e);
    if(settingsWindow) {
        settingsWindow.focus();
        e.returnValue = false;
    }
    - else e.returnValue = true;
    + else window.destroy();
};

Glad I finally found a solution :)

Upvotes: 0

Related Questions