Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot receive message sent from main process to renderer process in Electron

Tags:

electron

I'm sending a message from the main to the renderer process.

In the main process, I'm doing this:

const ipcMain = require('electron').ipcMain;

ipcMain.on('asynchronous-message', function(event, arg) {
   console.log('m i here');
   event.sender.send('asynchronous-reply', 'pong');
});

In the renderer script, I'm doing this:

const ipcRenderer = require('electron').ipcRenderer;

ipcRenderer.on('asynchronous-reply', function(event, arg) {
    console.log('In renderer again');
});

However, it seems like the message is not received in the renderer process. What am I missing?

like image 458
bikash Avatar asked Mar 21 '16 10:03

bikash


2 Answers

Thanks. I finally got around to understanding the concept. The whole idea that I was missing was to initiate the messaging chain from the renderer process. Actually I had two renderer processes: html 1, html 2. The idea was to populate html 2 based on contents in html 1.

Below is what worked for me

Main.js

ipcMain.on('Request-from-SOR-Page', function(event, arg) {
    var nomenclature = arg;

    ipcMain.on('Request-frm-AOR-Page', function(event, arg) {
        event.sender.send('Response-To-AOR-Page', nomenclature);
    });
});

Script for html 1

const ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.send('Request-from-SOR-Page', aor.nomenclature);

Script for html 2

var ipcRenderer = require("electron").ipcRenderer;

ipcRenderer.send('Request-frm-AOR-Page');
ipcRenderer.on('Response-To-AOR-Page', function(event, data) {
    console.log(data);
});

My conclusion is that in order to communicate between the main and the renderer process, the renderer needs to initiate the messaging or use webContents.send if there is a standalone message initiated from the main process.

Please correct if my assumption is true.

like image 97
bikash Avatar answered Oct 13 '22 05:10

bikash


You're never actually sending anything. You're just registering a listener in both the Main and Renderer processes.

  • To send a message from Renderer to Main, use ipcRenderer.send.
  • To send a message from Main to Renderer, use BrowserWindow#webContents.send.
like image 6
inukshuk Avatar answered Oct 13 '22 04:10

inukshuk