同步 IPC 通訊

建立 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
  })
})

ipcMain.on('syncChannelToMain', (event, arg) => {
  console.log(arg + ' from renderer')
  event.returnValue = 'world'
})

和渲染器處理 index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Hello World IPC</title>
  </head>
  <body>
    <button onclick="console.log(require('electron').ipcRenderer.sendSync('syncChannelToMain', 'world') + ' from main')">click me</button>
  </body>
</html>