Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Electron ipcMain module


May 25, 2021 Electron


Table of contents


ipcMain module is an example of eventEmitter. W hen it is used in the main process, it controls asynchronous or synchronized messages sent by the rendering process (web page). Messages sent from the rendering process trigger events.

Send a message

You can also send messages from the main process to the rendering process to see more webContents.send .

  • Send a message with the event channel .
  • In response to the sync message, you event.returnValue .
  • In response to asynchronous messages, event.sender.send(...) .

An example of sending and processing messages between the main and rendering processes:

// In main process.
const ipcMain = require('electron').ipcMain;
ipcMain.on('asynchronous-message', function(event, arg) {
  console.log(arg);  // prints "ping"
  event.sender.send('asynchronous-reply', 'pong');
});

ipcMain.on('synchronous-message', function(event, arg) {
  console.log(arg);  // prints "ping"
  event.returnValue = 'pong';
});
// In renderer process (web page).
const ipcRenderer = require('electron').ipcRenderer;
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"

ipcRenderer.on('asynchronous-reply', function(event, arg) {
  console.log(arg); // prints "pong"
});
ipcRenderer.send('asynchronous-message', 'ping');

Listen for messages

ipcMain has the following methods for listening for events:

ipcMain.on(channel, listener)

  • channel String
  • listener Function

Listen to channel and when a new message arrives, listener(event, args...) Call listener .

ipcMain.once(channel, listener)

  • channel String
  • listener Function

Add a one-time listener function to the event. This listener only called upon channel the message reaches the channel and then deleted.

ipcMain.removeListener(channel, listener)

  • channel String
  • listener Function

Remove a channel listener from the listener for a specific channel.

ipcMain.removeAllListeners([channel])

  • channel String (optional)

Delete all listeners, or all listeners channel the channel.

The event object

The event object passed to event has the following methods: callback

event.returnValue

Set this to the value returned in a synchronization message.

event.sender

Back to webContents can call event.sender.send to reply to the asynchronous message, more information webContents.send .