Send sync message from IpcMain to IpcRenderer – Electron

There is no such functionality of ipcMain *. However, you can achieve almost the same result asynchronously with the following steps:

  • Place your code which you would run only after the synchronous call in an ipcMain callback.
  • Reply to ipc message in renderer process with the result using event.sender.send

A dummy example of calculating sum using this approach looks like the following:

main.js

const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')

app.once('ready', () => {
  let win = new BrowserWindow()
  // have to run "sync", that is only after result is ready
  const doJobWithResult = (res) => {
    console.log(res)
  }
  win.webContents.once('dom-ready', () => {
    win.webContents
    .send('sum-request', 23, 98, 3, 61)
    ipcMain.once('sum-reply', (event, sum) => {
      doJobWithResult(sum)
    })
  })
  win.loadURL(path.resolve(__dirname, 'test.html'))
})

renderer.js (referred from test.html)

const {ipcRenderer} = require('electron')

window.onload = () => {
  const add = (a, b) => {
    return a + b
  }
  ipcRenderer.on('sum-request', (event, ...args) => {
    event.sender.send('sum-reply', [...args].reduce(add, 0))
  })
}

* I guess the main reason for this is that synchronous calls from the main process to the renderer process would cause the main nodejs process to wait, which is also responsible for running the renderer processes.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)