Electron Documentation1.7.5

Docs / API / ipcMain

ipcMain

Communicate asynchronously from the main process to renderer processes.

Process: Main

The ipcMain module is an instance of the EventEmitter class. When used in the main process, it handles asynchronous and synchronous messages sent from a renderer process (web page). Messages sent from a renderer will be emitted to this module.

Sending Messages

It is also possible to send messages from the main process to the renderer process, see webContents.send for more information.

An example of sending and handling messages between the render and main processes:

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

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

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

Methods

The ipcMain module has the following method to listen for events:

ipcMain.on(channel, listener)

Listens to channel, when a new message arrives listener would be called with listener(event, args...).

ipcMain.once(channel, listener)

Adds a one time listener function for the event. This listener is invoked only the next time a message is sent to channel, after which it is removed.

ipcMain.removeListener(channel, listener)

Removes the specified listener from the listener array for the specified channel.

ipcMain.removeAllListeners([channel])

Removes listeners of the specified channel.

Event object

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

event.returnValue

Set this to the value to be returned in a synchronous message.

event.sender

Returns the webContents that sent the message, you can call event.sender.send to reply to the asynchronous message, see webContents.send for more information.


See something that needs fixing? Propose a change on the source.
Need a different version of the docs? See the available versions or community translations.
Want to search all the documentation at once? See all of the docs on one page.