[Electron] IPC Mechanism

Kobe Ko
2 min readNov 6, 2016

--

source code @ github

Electron uses Chromium multi-process mechanism. That means the application is created by main process and the web page is rendered by renderer process. Each process is independent and cannot communicate with each other directly.

How can we let renderer process communicate with main process, for example use button in web page to close the application. We can use IPC (inter-process communication) mechanism to do this.

The ipc of electron allows subscribing to messages on a channel and sending messages to subscribers of a channel. Following illustrates the concept.

Here are the official docs of ipcMain and ipcRenderer

All related source codes are under ipc folder. The program will demonstrate the ipc mechanism that let user close the application by clicking the button.

  • The data structure of ipc folder
ipc
|- app
| |- index.html
| |- index.js
|
|- main.js
|- package.json
  • index.html

We create a button and run index.js in renderer process.

  • index.js

First, we get an instance of ipcRenderer in renderer process and we can use this instance to communicate with main process. Something need to be noticed is that we can only get instance of ipcRenderer in renderer process. If the code is changed to following

let ipcRenderer = require('electron').ipcMain

The ipcRenderer will be undefined. This is because electron only allow getting instance of ipcMain in main process.

  • main.js

Getting the instance of ipcMain at the beginning and subscribe to close-main-window channel at the end. The application will be closed when ipcMain receives messages from close-main-window channel.

  • Run the program
> npm install
> ./node_modules/.bin/electron .

--

--

Kobe Ko

Founder & CEO of topreco. Android & iOS Developer.