IPC=inter-process communication=进程间通信
仍然以Electron读取本地文件并显示中的原始代码作为基础。
preload.js(渲染进程向主进程发送hello):
const { ipcRenderer } = require('electron'); let sendMsgToMainProcess = (str) => { ipcRenderer.send("line1", str); // 默认就是异步 } document.querySelector('#btn2').addEventListener("click", event => { // 点击按钮发送信息 sendMsgToMainProcess('hello from renderer1'); })
main.js(主进程接收该消息并回复):
ipcMain.on("line1", (event, arg) => { console.log(arg); event.reply("line1-reply", "helle from main process"); })
preload.js(渲染进程监听并处理主进程返回的消息):
ipcRenderer.on("line1-reply", (event, args) => { console.log(args); // 打印主线程的回复 })
渲染进程中点击按钮创建一个新的窗口。如果在渲染进程中直接使用electron主进程模块的API将抛出类似于BrowserWindow is not a constructor的异常.
preload.js
document.querySelector('#btn3').addEventListener("click", event => { ipcRenderer.send("line2", "createWindow"); })
main.js
ipcMain.on("line2", (event, arg) => { if (arg == "createWindow") { const newWindow = new BrowserWindow({ width: 300, height: 300, }) newWindow.loadURL('https://baidu.com') } })