Communication between process in Electron.js

- Andrés Cruz

En español
Communication between process in Electron.js

There are many scenarios in which we need to communicate both processes, that when an event occurs in the main process and/or the rendering process, we can send said message at any time to perform a specific action; Being able to send messages via events between processes is particularly useful for performing operations that can only be executed on one side but that we need to communicate to the other side; For example:

  • If we want to open a new window by clicking on a button, where the button is obviously on the web page, it is logical that from the web page, we must send a message to the main process to open said window.
  • If from the main component we must pass data to the web page that will be taken as a reference to build the application interface; these data can be provided in any comment, either when the web page loads, when the user interacts with the application, etc.

In summary, like any other paradigm, for example the one based on the client and server used by web applications, it is essential to communicate the layers or processes that are involved, either directly or indirectly, and we are going to know in detail how to perform these processes.

At Electron, we have a single main process and one or more rendering processes or web pages; the communication between the two is done through a couple of modules:

  • ipcMain: This module is used to communicate from the main process to the rendering processes.
  • ipcRenderer: This module is used to communicate from the rendering processes to the main process.

Let's analyze each of them in practice.

Main Process to Render Process

In order to send a message to the web page from the main process, we have the following function:

<window>.webContents.send(<EVENT>,<VALUE>)

From the client we have to subscribe to an event; we need to import an ipcRenderer object from Electron and listen to the set channel.

const { ipcRenderer } = require('electron')

ipcRenderer.on(<EVENT>, (event, arg) => {
 // TO DO
});

Render process to main process

To be able to send a message from the rendering process or web page, we have it very simple, just pass the message from the web page:

const { ipcRenderer } = require('electron')
ipcRenderer.send('message', <DATA>)

From the main process, we have a callback event:

const {ipcMain} = require('electron')

ipcMain.on('message',(event, arg) => {
   // TO DO
})

Remember that the previous material is part of mi curso completo sobre Electron.js

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.