Reputation: 412
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.
Upvotes: 1
Views: 2354
Reputation: 1232
Communication example from a child_window to its parent_window using webContents:
Inside parent_window:
const BrowserWindow = require('electron').remote.BrowserWindow;
var child_window = new BrowserWindow({ ... });
child_window.webContents.on("event", function(arg1, arg2){
console.log(arg1, arg2); // this will print inside parent_window devtools console
});
Inside child_window:
require('electron').remote.getCurrentWebContents().emit("event", "hello", "world");
The main advantage using this solution instead of the IPC one is that those routines are linked to the local context of child_window's webContents. So those routines are deleted if the child_window is closed and its BrowserWindow object is deleted.
You can also use the same system to communicate from parent_window to child_window.
Upvotes: 1
Reputation: 1286
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.
Upvotes: 1