4
votes

I am developing desktop application using Electron, Scenario is I have 2 BrowserWindow, From FirstBrwoserWindow, I am going to SecondBrowserWindow after button click. i have instantiated SecondBrowserWindow on FirstBrwoserWindow's button click to avoid Object has been destroyed Exception.
As per Electron, if we want to send data between processes we have to use IPC. So actual problem starts here, I am creating SecondBrowserWindow object in FirstBrwoserWindow's renderer file, and for IPC i need to get SecondBrowserWindow object in main process.

How do i get SecondBrowserWindow Object in main.js and use IPC.on there????

2

2 Answers

3
votes

The way I've solved this is to pass the data with ipcRenderer from the first window to the main process and then pass it with ipcMain to the second window using BrowserWindow.webContents.send().

It looks kinda like this.

Window 1

...
// Emit an ipc message with your data
ipcRenderer('your-message', { foo: 'bar' });
...

Main process

...
let window1 = new BrowserWindow(...);
let window2 = new BrowserWindow(...);
...
// when ipc message received pass it on to second window object with webContents
ipcMain.on('your-message', (event, payload) => {
  window2.webContents.send('your-relayed-message', payload);
});
...

Window 2

...
// when ipc messaged received in second window do what you want with the data
ipcRenderer.on('your-relayed-message', (event, payload) => {
  console.log(payload);
});
...
0
votes

You can do it in more ways but what I recommend you to:

1) when you receive the input to open the 2nd BrowserWindow in the renderer, send a message to main.js

2) from main.js open the 2nd BrowserWindow so you can control it and send message to it in a cleaner way.

In this way, you can close the previous BrowserWindow without errors in communication and you have a more scalable and readable logic for N BrowserWindows.