1

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?

notexactly
  • 918
  • 1
  • 5
  • 21

1 Answers1

0

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

skara9
  • 4,042
  • 1
  • 6
  • 21
  • Hmm... I see what you are saying, but it is still not working. I tried printing something to terminal like this: `newWindow.on('did-finish-load', () => { console.log('print here') });`, but nothing is printed to the terminal. Interestingly, I see `print here` in the terminal if I use `ready-to-show` instead of `did-finish-load`, but I am not able to make `ipcRenderer` receive the message even with what you suggested. – notexactly Dec 26 '21 at 03:57
  • @6cloud9 can you show the code in `createWindow` where you load the window? – skara9 Dec 26 '21 at 04:11
  • Sure, I can, but it is a pretty simple function, actually. I just create a new instance of a `BrowserWindow`, where `nodeIntegration` is set to `false`, and `contextIsolation` is set to `true`, and that's pretty much it (besides setting the width, height of the window, etc.). – notexactly Dec 26 '21 at 04:34
  • I realized my mistake. Instead of using an `on` event, I just called `windowWithTheButton.webContents.send('opened-window');` directly. – notexactly Dec 26 '21 at 04:46