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>