Inter-process communication (IPC) in Electron Js

  • In Electron.js, inter-process communication (IPC) refers to the communication mechanism used to exchange data between the main process and renderer processes. Electron.js allows you to build desktop applications using web technologies like HTML, CSS, and JavaScript. It consists of two main components: the main process and the renderer processes.
  • The main process is responsible for managing the application's lifecycle, handling system events, and creating and managing the renderer processes. Each renderer process runs in its own isolated environment and represents a web page in the Electron application.
  • IPC enables communication between the main process and the renderer processes, allowing them to exchange data, trigger actions, and synchronize their behavior. It provides a way to send and receive messages asynchronously between processes.
Here's a brief example to illustrate how IPC works in Electron.js:
  • In the main process, you can use the `ipcMain` module to handle incoming messages from renderer processes and send responses back. For example:


    // In the main process
    const { ipcMain } = require('electron');

    ipcMain.on('message', (event, arg) => {
        console.log(arg); // Output: 'Hello from renderer'
        event.sender.send('reply', 'Hello from main');
    });

  • In the renderer process, you can use the `ipcRenderer` module to send messages to the main process and receive responses. For example:


    // In the renderer process
    const { ipcRenderer } = require('electron');

    ipcRenderer.send('message', 'Hello from renderer');

    ipcRenderer.on('reply', (event, arg) => {
        console.log(arg); // Output: 'Hello from main'
    });

  • In this example, the renderer process sends a message with the string 'Hello from renderer' to the main process using `ipcRenderer.send()`. The main process listens for the 'message' event using `ipcMain.on()` and logs the received message. It then sends a reply with the string 'Hello from main' back to the renderer process using `event.sender.send()`. The renderer process listens for the 'reply' event using `ipcRenderer.on()` and logs the received reply.
  • This simple example demonstrates the basic usage of IPC in Electron.js. It allows you to establish communication channels and exchange data between the main process and renderer processes, enabling them to work together seamlessly in an Electron application.

No comments:

Post a Comment