Some ideas to improve the IPC communication between main and renderer process


Basically I would like to write the IPC like this:

renderer process

const {ipcRenderer} = require('electron');

ipcRenderer.send ('app:hello', (err, msg) => {
  console.log('main process replied: ' + msg); 
  // output: "main process repied: hi"

main process

const {ipcMain} = require('electron');

ipcMain.on('app:hello', event => {

To achieve this, I create this module which will enhance the original ipc api of Electron.

The idea behind it is:

First I store a session table that its key is a sessionID. When user start an IPC with callback function in one process (main or renderer), it will store the callback in the session table in that process, and encode the ipc like ipc:main2renderer and send it to the target process with the sessionID and your-msg.

In the target process, it will handle this special message, and wrap the event object by giving it the reply function, it will then call ipcMain/ipcRenderer.emit('your-msg', ...) to invoke the real message. When user handle the IPC message, and wants to reply back to the sender, it just call event.reply(...). Then the reply will be processed in another IPC message such as ipc:main2renderer-reply with the sessionID. This message eventually come back to sender process and will invoke the callback via the sessionID.

I hope this can help people with IPC programming, and I’m looking forward to see your feedback.