Building desktop applications with Electron - Inter-process communication (IPC)

Janez Čadež
2 min readJun 8, 2017

--

This tutorial assumes you know how to install and set up electron-quick-start project. You can find the tutorial here.

The ipc (inter-process communication) module allows you to send and receive synchronous and asynchronous messages between the main and renderer processes.

To use ipc from renderer to the main process, you can use the ipcRenderer module, and the other way around (so from main to renderer process), you can use the ipcMain module.

We will take a look at how to send asynchronous message from the renderer to the main. Then, we will reply back to the renderer process. First, let’s navigate to our renderer.js file.

We begin by requiring ‘electron’ package, use destructuring to get the ipcRenderer module from the package and defining it as a constant. Then, we use the ipcRenderer.send method, where we specify the channel name to send through (in our case, this will be ‘asynchronous-message’ channel and listing arguments as next parameter.

// renderer.jsconst {ipcRenderer} = require(‘electron’)ipcRenderer.send(‘asynchronous-message’, ‘hello’)

Now, we will listen for the message in the main process, so let’s open up the main.js file. Here, we similary define new ipcMain constant and assign it to the electron.ipcMain . Now, we call ipcMain.on method and specify the channel we are listening to (in our case, this will be ‘asynchronous-message’ channel. The second parameter will be a anonymous function with two parameters, event and args. Now, we just display the message from arguments by logging it in the console.

// main.jsconst ipcMain = electron.ipcMainipcMain.on(‘asynchronous-message’, (event, args) => {
console.log(args)
})

To send the async message back, we can make use of passed in event and call event.sender.send method and pass the channel of ‘asynchronous-reply’ and the message of ‘world’. This will send an asynchronous message back to the renderer process.

// main.jsevent.sender.send(‘asynchronous-reply’, ‘world’)

Now, the last thing we need to do is to listen to our reply message in the renderer.js file. Here, we make use of the ipcRenderer.on method, the channel of ‘asynchronous-reply’, and we specifiy an anonymous function. Inside the function, we console.log the reply.

// renderer.jsipcRenderer.on(‘asynchronous-reply’, (event, arg) => {
console.log(arg) // prints “pong”
})

To see the response, open up the DevTools inside the BrowserWindow (CtrlCmd + Shift + I).

--

--

Janez Čadež

JavaScript Engineer @poviolabs, Udemy instructor, open source contributor. https://devhealth.io