Electron - IPC - sending data between windows

mainWindow is not able to receive the event because it is not getting sent to it. The events.sender.send() code in main.js will send the data back to whoever sent the notes event, which in this case is the noteWindow. So the notes2 event is getting sent back to noteWindow instead of mainWindow.

To send the notes2 event to mainWindow, check out webContents.send(). This allows the main process to send data via events to a specific window. After some modifications to main.js it would look similar to this:

ipcMain.on('notes', function(event, data) {
    mainWindow.webContents.send('notes2', data);
});

There is no need to setup ipc hub on main.js. Here is how I would do it.

The key here is that if you want to have a direct ipc talk between renderer their need to know each other getCurrentWebContents().id.

Step 1: Create a main window global object

main.js

function createWindow() {
    mainWindow = new BrowserWindow(...);

    global.mainWindow = mainWindow;

    ...
}

Step 2: Send data to main window (and receive)

noteWindow.js

const ipc = require("electron").ipcRenderer;
ipc.sendTo(
          getGlobal("mainWindow").webContents.id,
          "ChannelForMainWindow",
          data,
          web_component.id // for main window to send back
        );

mainWindow.js

ipc.on("ChannelForMainWindow", (e, data, web_component_id) => {
    // do something
});

(Optional) Step 3: Send data back (and receive as well)

noteWindow.js

let's add listener for main window reply (if any)

const ipc = require("electron").ipcRenderer;

ipc.on("ChannelForNoteWindow", e => {
    ...
});

ipc.sendTo(
          getGlobal("mainWindow").webContents.id,
          "ChannelForMainWindow",
          data,
          web_component.id // for main window to send back
        );

mainWindow.js

ipc.on("ChannelForMainWindow", (e, data, web_component_id) => {
    // do something

    //send data back
    ipc.sendTo(web_component_id, "ChannelForNoteWindow");
});

Tags:

Ipc

Electron