Omagerio
Omagerio

Reputation: 505

Prevent child window from closing when parent window is closed in Electron

I'm making an Electron app. This app has a way to open a new window (popup) to be dragged on a different monitor. This window has a way to open another one, and so on. I need the user to be able to close a window he does not want, but keep others open.

First, I tried window.open but the child window gets closed when the parent is closed. I thought it must be because the var gets garbage collected.

Second, I tried binding to the new-window event in the main process. This is what I did:

let windows = [];

function createNewWindow(){
  let win = new BrowserWindow(
    {
      width: 1600,
      height: 900,
      webPreferences: {
        nodeIntegration: true
      }
    }
  );

  win.webContents.on('new-window', (event, url) => {
    event.preventDefault()

    let win = createNewWindow();
    win.loadURL(url);
    event.newGuest = win;
  })

  windows.push(win);

  return win;
}

But the child gets closed when the parent is closed. I checked the windows var, but it is correctly retained in the main process, so this should not be a GC problem.

How can I open a chain of windows (with or without window.open) without them being closed when the main parent is closed?

EDIT

As I did not found a way to keep windows open, I decided to hide the windows instead of closing them. This is what I did:

  win.on("close", (event) => {
    if (win.hideInsteadOfClose == true) {
      event.preventDefault();
      win.hide();
    }
  });

Where hideInsteadOfClose is a property I give to new windows created. This is not the proper way of doing it, but it gets the work done. Please feel free to answer with the correct way.

Upvotes: 3

Views: 2109

Answers (1)

Omagerio
Omagerio

Reputation: 505

As I did not found a way to keep windows open, I decided to hide the windows instead of closing them. This is what I did:

  win.on("close", (event) => {
    if (win.hideInsteadOfClose == true) {
      event.preventDefault();
      win.hide();
    }
  });

Where hideInsteadOfClose is a property I give to new windows created. This is not the proper way of doing it, but it gets the work done.

Please feel free to answer with the correct way.

Upvotes: 1

Related Questions