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????
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????
Share Improve this question asked Dec 15, 2017 at 13:05 user7808817user7808817 1072 silver badges12 bronze badges 1- look this solution stackoverflow./questions/47416799/… – vineet Commented Aug 30, 2019 at 13:15
2 Answers
Reset to default 4The 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);
});
...
You can do it in more ways but what I remend 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 munication and you have a more scalable and readable logic for N BrowserWindows.