
Electronのプロセス間通信についてで、Electronの実行についての概要に触れ、プロセス間通信(IPC)を介して、レンダラープロセスからメインプロセスに値を送信してみました。
今回はメインプロセスからレンダラープロセスに値を送信してみます。
コードの編集の前にファイルの構成を挙げておきます。
. ├── index.html ├── main.js ├── node_modules ├── package.json ├── package-lock.json └── preload.js
main.jsがメインプロセスになり、index.htmlがレンダラープロセスになり、preload.jsでIPCに関するコードを書いています。

今回はレンダラープロセスからメインプロセスに文字列を送信したら、メインプロセスで文字列を加工してレンダラープロセスに値を返し、受け取った値をアラートで表示するという処理を追加してみます。
始めにメインプロセスの方でレンダラープロセスに値を送信するコードを追加します。
main.js
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const createWindow = () => {
const win = new BrowserWindow({
width: 400,
height: 300,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
ipcMain.handle("receive", async (_e, _arg) => {
win.webContents.send('reply', "hello "+_arg)
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
})
BrowserWindow.webContents.send(key, value)
でレンダラープロセスに値を送信します。
続いて、IPCのpreload.jsを改修します。
preload.js
const { ipcRenderer, contextBridge } = require('electron');
contextBridge.exposeInMainWorld("api", {
send: (name) => ipcRenderer.invoke('receive', name),
getReply: (callback) => ipcRenderer.on('reply', (_e, _arg) => callback(_arg))
});
ipcRenderer.on(key, func)
でメインプロセスから値を取得するための機能を追加します。
最後にレンダラープロセスの方のコードを改修します。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="text" id="name">
<button id="send">送信</button>
</body>
<script>
document.querySelector("#send").addEventListener("click", () => {
let name = document.querySelector("#name").value;
window.api.send(name);
});
window.api.getReply( (_arg) => {
alert(_arg)
});
</script>
</html>
preload.jsで追加した関数の呼び出しのコードを書いて終了です。