示例工程 08-ipc-invoke-handle
08-ipc-invoke-handle/app/.tsc/main/index.js
import { app, BrowserWindow, ipcMain, MessageChannelMain } from "electron";
import fsSync from "node:fs";
import path from "node:path";
import { CH, isFiniteNumber, isPingText, } from "../shared/ipc";
app.setName("IPC Lab");
const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
let logFile = "";
let portAcks = 0;
let portTimer = null;
const events = [];
function writeLog(level, evt, msg) {
const line = JSON.stringify({
at: Date.now(),
level,
evt,
...(msg ? { msg } : {}),
});
process.stdout.write(`${line}\n`);
if (!logFile)
return;
try {
fsSync.appendFileSync(logFile, `${line}\n`);
}
catch {
// 日志失败不能拖垮 IPC 演示。
}
}
function pushEvent(dir, channel, text) {
events.push({ at: Date.now(), dir, channel, text });
if (events.length > 40)
events.shift();
}
function resolvePreload() {
const candidates = [
path.join(__dirname, "preload.cjs"),
path.join(__dirname, "../preload/index.cjs"),
path.join(__dirname, "preload.js"),
];
return (candidates.find((candidate) => fsSync.existsSync(candidate)) ??
candidates[0] ??
"");
}
function createWindow() {
const win = new BrowserWindow({
width: 1000,
height: 720,
show: false,
title: "IPC 实验室",
backgroundColor: "#ffffff",
webPreferences: {
preload: resolvePreload(),
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
webSecurity: true,
allowRunningInsecureContent: false,
experimentalFeatures: false,
webviewTag: false,
spellcheck: false,
backgroundThrottling: true,
},
});
win.once("ready-to-show", () => {
if (!win.isDestroyed())
win.show();
});
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
void win.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
}
else {
void win.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
}
return win;
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function waitFor(check, timeoutMs) {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
if (await check())
return true;
await delay(50);
}
return false;
}
async function evalRenderer(win, code) {
let lastError = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return (await win.webContents.executeJavaScript(code));
}
catch (error) {
lastError = error;
await delay(200);
}
}
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
async function waitForRenderer(win) {
await waitFor(async () => {
if (win.isDestroyed())
return false;
try {
return await win.webContents.executeJavaScript("typeof window.__smoke === 'function'");
}
catch {
return false;
}
}, 8000);
}
async function runSmoke() {
try {
const win = createWindow();
await waitForRenderer(win);
const result = await evalRenderer(win, "window.__smoke()");
writeLog("info", "smoke-result", JSON.stringify(result));
process.stdout.write(`${JSON.stringify({
evt: "smoke",
ok: result.invoke === 144 &&
result.error.name === "Error" &&
result.pongs >= 1 &&
result.portMessages >= 5 &&
result.portAcks >= 5,
invoke: result.invoke,
error: result.error,
pongs: result.pongs,
portMessages: result.portMessages,
portAcks: result.portAcks,
stackLines: result.stackLines,
})}\n`);
app.quit();
}
catch (error) {
process.stdout.write(`${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`);
app.exit(1);
}
}
async function setTab(win, tab) {
await win.webContents.executeJavaScript(`window.__setTab && window.__setTab(${JSON.stringify(tab)})`);
}
async function capture(win, dir, file) {
const image = await win.webContents.capturePage();
if (image.isEmpty())
throw new Error(`empty capture: ${file}`);
const png = image.toPNG();
fsSync.writeFileSync(path.join(dir, file), png);
fsSync.writeFileSync(path.join(dir, "raw", file), png);
writeLog("debug", "shot", file);
}
async function runShots() {
try {
const dir = path.resolve(process.cwd(), "../../../docs/assets/images/08-ipc-invoke-handle");
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
const win = createWindow();
await waitForRenderer(win);
await evalRenderer(win, "window.__smoke()");
await delay(400);
await setTab(win, "invoke");
await delay(300);
await capture(win, dir, "08-01-invoke.png");
await setTab(win, "event");
await delay(300);
await capture(win, dir, "08-02-event.png");
await setTab(win, "port");
await delay(700);
await capture(win, dir, "08-03-port.png");
app.quit();
}
catch (error) {
writeLog("error", "shots-failed", String(error));
app.exit(1);
}
}
ipcMain.handle(CH.square, (_event, raw) => {
if (!isFiniteNumber(raw)) {
return {
ok: false,
error: { code: "BAD_INPUT", message: "value 必须是有限数字" },
};
}
if (raw < 0) {
return {
ok: false,
error: { code: "NEGATIVE", message: "value 不能为负数" },
};
}
if (raw > 1_000_000) {
return {
ok: false,
error: { code: "TOO_LARGE", message: "value 不能超过 1000000" },
};
}
pushEvent("in", CH.square, `value=${raw}`);
return { ok: true, value: raw * raw };
});
ipcMain.handle(CH.boom, () => {
// 故意抛异常:渲染进程会收到 reject,而不是 { ok:false } 返回值。
throw new Error("模拟主进程异常:余额不足");
});
ipcMain.on(CH.ping, (event, raw) => {
if (!isPingText(raw)) {
pushEvent("in", CH.ping, "invalid");
return;
}
pushEvent("in", CH.ping, raw);
const payload = {
at: Date.now(),
echo: raw,
replyAt: Date.now(),
};
event.sender.send(CH.pong, payload);
});
ipcMain.handle(CH.portStart, (event) => {
if (portTimer)
clearInterval(portTimer);
portAcks = 0;
const channel = new MessageChannelMain();
channel.port1.on("message", (messageEvent) => {
const ack = messageEvent.data?.ack;
if (typeof ack !== "number")
return;
portAcks += 1;
pushEvent("in", CH.portChannel, `ack ${ack}`);
});
channel.port1.start();
// 把 port2 交给渲染进程;preload 负责接收并转发消息。
event.sender.postMessage(CH.portChannel, { started: true }, [channel.port2]);
let seq = 1;
portTimer = setInterval(() => {
if (seq > 5) {
if (portTimer)
clearInterval(portTimer);
portTimer = null;
channel.port1.postMessage({ done: true, total: 5 });
pushEvent("out", CH.portChannel, "done");
writeLog("info", "port-done", `acks=${portAcks}`);
setTimeout(() => channel.port1.close(), 200);
return;
}
channel.port1.postMessage({ seq, value: seq * 10 });
pushEvent("out", CH.portChannel, `msg ${seq}`);
seq += 1;
}, 80);
return { ok: true };
});
app.whenReady().then(() => {
logFile = path.join(app.getPath("logs"), "ipc.log");
try {
fsSync.mkdirSync(path.dirname(logFile), { recursive: true });
}
catch {
// 日志目录不可写时退化为只写 stdout。
}
writeLog("info", "app-ready", app.getVersion());
if (isSmoke) {
void runSmoke();
}
else if (isShots) {
void runShots();
}
else {
createWindow();
}
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0)
createWindow();
});
});
app.on("before-quit", () => {
if (portTimer)
clearInterval(portTimer);
portTimer = null;
});
app.on("window-all-closed", () => {
if (!isSmoke && !isShots && process.platform !== "darwin")
app.quit();
});
//# sourceMappingURL=index.js.map