May 25, 2021 Electron
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.
You can also send messages from the main process to the rendering process to see more webContents.send .
channel
.
event.returnValue
.
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');
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
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
.