Kosmo Kosmo - 6 months ago 83
Javascript Question

In Electron version 1.X, how can I emit an event from one BrowserWindow and consume it in another BrowserWindow?

In Electron version 1.X, how can I emit an event from one BrowserWindow and consume it in another BrowserWindow?

I am using Electron version 1.2.1.

Answer

One way you could do this is using the ipcRenderer to communicate between BrowserWindow instances and the main process. For example, in the main process you could have something like the following: -

const electron          = require('electron');
const app               = electron.app;
const BrowserWindow     = electron.BrowserWindow;
let mainWindow, subWindow;

mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    fullscreen: true
});

mainWindow.loadURL('file://' + __dirname + '/../index.html');

subWindow = new BrowserWindow(); // etc

electron.ipcMain
    .on('myMainMessage', function (event, data) {
        // data can be passed from browser window
        subWindow.webContents.send('myPassedMessage', data);
    });

Then, inside the first mainWindow instance you could throw together a message using the ipcRenderer like so: -

var electron = require('electron');
var ipc = electron.ipcRenderer;

ipc.send('myMainMessage', {
    property: 'someValue'
});

And inside your other window instance you'd have some JavaScript to listen to the other trigger. Something like this: -

var electron = require('electron');
var ipc = electron.ipcRenderer;

ipc.on('myPassedMessage', function (event, data) {
    console.log(data); // will be from the mainWindow instance
});

Consult the docs on the ipcRenderer section for more information.

Comments