主进程 (main.js)
const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("node:path");
// 导入fs模块
const fs = require("fs");
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile("index.html");
};
app.whenReady().then(() => {
createWindow();
});
// 主进程接收渲染进程发送的消息
ipcMain.on("message-from-renderer", (event, data) => {
let baseDir = "D:\\"; //保存的根路径
let FileLocation = "001.text"; //文件名
const url = path.join(baseDir, FileLocation);
// 调用fs.writeFile() 写入文件内容
fs.writeFile(url, data, function (err) {
if (err) {
return console.log("File write error" + err.message);
}
console.log("File write success");
// 收到消息后给子窗口child回复消息
event.sender.send("reply-msg-child", "我是父窗口,我接收到了子窗口的消息");
});
});
预加载脚本 (preload.js)
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("versions", {
node: process.versions.node,
chrome: process.versions.chrome,
electron: process.versions.electron,
});
contextBridge.exposeInMainWorld("api", {
send: (channel, data) => {
ipcRenderer.send(channel, data);
},
receive: (channel, func) => {
ipcRenderer.on(channel, (event, ...args) => func(...args));
},
});
渲染进程 (index.html 和 renderer.js)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'"
/>
<meta
http-equiv="X-Content-Security-Policy"
content="default-src 'self'; script-src 'self'"
/>
<title>Hello from Electron renderer!</title>
</head>
<body>
<p id="info"></p>
<button id="btn1">点击</button>
</body>
<script src="./renderer.js"></script>
</html>
const information = document.getElementById("info");
console.log(window);
information.innerText = `This app is using Chrome (v${versions.chrome}), Node.js (v${versions.node}), and Electron (v${versions.electron})`;
const btn1 = document.getElementById("btn1");
btn1.onclick = function () {
// 发送消息到主进程
window.api.send("message-from-renderer", "Hello from Renderer Process");
};
// 接收来自主进程的回应
window.api.receive("reply-msg-child", (args) => {
alert(args);
});