Search code examples
javascriptelectrondesktop-application

How to send a variable from the mainWindow to a childWindow in Electron JS?


I'm opening a child window, with it's own HTML and JavaScript.
I want to send a property from the MainWindow javascript, an ID. to the childWindow.

The child window is a "settings" window, when done you hit Apply. I then want it to return me some HTML
information (a search input value) and the ID I originally sent to it.

Them being both renderer processes, a mainWindow and a childWindow.
How do I accomplish this?


Solution

  • Two windows cannot communicate directly, but you can send Informatopn via your main.js using ipcRenderer

    FirstWindow:

    const {ipcRenderer} = require('electron');
    ipcRenderer.send('eventA', {SomeData});
    

    main.js:

    const {ipcMain} = require('electron');
    ipcMain.on('eventA', (event, arg) => {
        secondWindow.webContents.send('EventA', arg);
    });
    ipcMain.on('eventB', (event, arg) => {
        firstWindow.webContents.send('EventB', arg);
    });
    

    child WIndow:

    const {ipcRenderer} = require('electron');
    ipcRenderer.on('EventA', (event, message) => {
        ipcRenderer.send('EventB', {someotherData});
    });
    

    This Way {someData} reaches your child window, and can be sent back the same way.