示例工程 01-what-is-electron
01-what-is-electron/demo-02-process-info/main.ts
import { app, BrowserWindow } from "electron";
const smoke =
process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
function table(rows: Array<[string, string]>): string {
return rows
.map(
([key, value]) =>
`<tr><td>${key}</td><td><code>${value}</code></td></tr>`,
)
.join("");
}
app.whenReady().then(async () => {
const window = new BrowserWindow({
width: 760,
height: 520,
show: false,
webPreferences: {
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
},
});
window.once("ready-to-show", () => {
window.show();
});
await window.loadURL("about:blank");
const rendererPid = window.webContents.getOSProcessId();
const rows: Array<[string, string]> = [
["Electron", process.versions.electron ?? "unknown"],
["Node", process.versions.node],
["Chromium", process.versions.chrome],
["主进程 PID", String(process.pid)],
["渲染进程 PID", String(rendererPid)],
];
const html = `<!doctype html>
<html lang="zh-CN">
<body style="font-family: system-ui, sans-serif; padding: 28px; line-height: 1.7">
<h1>进程与版本</h1>
<p>主进程只有一个;每个窗口有独立的渲染进程。</p>
<table style="border-collapse: collapse; min-width: 420px">
<thead><tr><th style="text-align:left;padding:8px;border-bottom:1px solid #e2e8f0">项</th><th style="text-align:left;padding:8px;border-bottom:1px solid #e2e8f0">值</th></tr></thead>
<tbody>${table(rows)}</tbody>
</table>
<p style="color:#64748b">在活动监视器里按 PID 搜索,可看到同一个渲染进程。</p>
</body>
</html>`;
await window.loadURL(
`data:text/html;charset=utf-8,${encodeURIComponent(html)}`,
);
if (smoke) {
console.log(
JSON.stringify({
evt: "smoke",
ok: rendererPid > 0,
electron: process.versions.electron,
node: process.versions.node,
chrome: process.versions.chrome,
mainPid: process.pid,
rendererPid,
}),
);
app.quit();
}
});
app.on("window-all-closed", () => {
app.quit();
});