In the main window of my program, I have a button that, if clicked, creates a new, additional window. When this new window finishes loading, I want to send a message to ipcRenderer
; however, I have not been able so far to make ipcRenderer
able to receive the message, even though the window is created successfully.
Here's a snippet of the code in main.js
:
const { ipcMain } = require('electron');
ipcMain.handle('open-window', () => {
const newWindow = createWindow();
newWindow.on('did-finish-load', () => {
newWindow.webContents.send('opened-window');
});
});
Note that createWindow
is a function that creates and returns a browser window.
And here's a snippet of the code in preload.js
:
const { ipcRenderer } = require('electron');
window.addEventListener('DOMContentLoaded', () => {
document.getElementById('openWindow').addEventListener('click', () => {
ipcRenderer.invoke('open-window');
});
});
ipcRenderer.on('opened-window', () => {
console.log('received message!')
})
As you can see, I would expect to receive in the console the string received message!
after the new window finishes loading; however, this is not happening. What am I doing wrong?
CodePudding user response:
You are sending "opened-window"
to the new window you created, not the original one in which the button was pressed.
newWindow.webContents.send('opened-window')
instead of newWindow
, you need to refer to the window with the button and the opened-window
handler