In my App I have two windows: mainWindow and actionWindow. On my mainWindow I use the ipcRenderer.on listener to receive as message from the main process when the actionWindow is closed. The message however doesn't come through.
The mainWindow is used to control actions that take place on the actionWindow (e.g. navigate to an URL, remotely close the window, ...). I want to give the user the power to move and close the actionWindow manually as well, which is why its title bar is visible and usable.
I expose ipcRenderer.invoke for two-way communication and ipcRenderer.on to the mainWindow's renderer via contextBridge in a preload file.
This is what the code looks like (based on vite-electron-builder template)
main process
const mainWindow = new BrowserWindow({
show: false, // Use 'ready-to-show' event to show window
webPreferences: {
nativeWindowOpen: true,
webviewTag: false,
preload: join(__dirname, "../../preload/dist/index.cjs"),
},
});
const actionWindow = new BrowserWindow({
// some props
})
actionWindow.on("close", () => {
console.log("window closed")
mainWindow.webContents.send("closed", { message: "window closed" });
});
preload
contextBridge.exposeInMainWorld("ipcRenderer", {
invoke: ipcRenderer.invoke,
on: ipcRenderer.on,
});
renderer (mainWindow)
window.ipcRenderer.on("closed", () => {
console.log("message received")
// do something
});
I know for a fact that
- mainWindow has access to the exposed listeners, since
invokeworks and the actions it fires on the main process are executed on the actionWindow as supposed + the response also comes back to the renderer. - the
closelistener on the actionWindow works since I can see the logwindow closedin my console message receiveddoesn't appear in my dev tools console
To me this means that either
mainWindow.webContents.senddoesn't work -> the message is never sentwindow.ipcRenderer.ondoesn't work -> the message never reaches its destination
So either my code is buggy or Electron has recently put some restrictions on one of these methods which I'm not aware of.
Any ideas? If there is a smarter way to do this than IPC I'm also open to that.