electron Main and renderer process. Asynchronous IPC communication

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Main process source code index.js:

const {app, BrowserWindow, ipcMain} = require('electron')
let win = null

app.on('ready', () => {
  win = new BrowserWindow()
  win.loadURL(`file://${__dirname}/index.html`)
  win.webContents.openDevTools()
  win.on('closed', () => {
    win = null
  })
  win.webContents.on('did-finish-load', () => {
    win.webContents.send('asyncChannelToRenderer', 'hello')
  })
})

ipcMain.on('asyncChannelToMain', (event, arg) => {
  console.log(arg + ' from renderer')
  if (arg === 'hello') {
    event.sender.send('asyncChannelToRenderer', 'world')
  }
})

Renderer process in index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Hello World IPC</title>
    <script>
      require('electron').ipcRenderer.on('asyncChannelToRenderer', (event, arg) => {
        console.log(arg + ' from main')
        if (arg === 'hello') {
          event.sender.send('asyncChannelToMain', 'world')
        }
      })
    </script>
  </head>
  <body>
    <button onclick="require('electron').ipcRenderer.send('asyncChannelToMain', 'hello')">click me</button>
  </body>
</html>


Got any electron Question?