示例工程 05-preload-and-contextbridge
05-preload-and-contextbridge/app/main/index.ts
import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import { CH, type BridgeConfig, type BridgeProbe } from "../shared/ipc";
const isSmoke =
process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
let mainWindow: BrowserWindow | null = null;
let started = false;
function log(record: Record<string, unknown>): void {
process.stdout.write(`${JSON.stringify(record)}\n`);
}
function resolvePreload(): string {
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 collectConfig(): BridgeConfig {
return {
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
preload: resolvePreload(),
};
}
function createWindow(): void {
mainWindow = new BrowserWindow({
width: 1000,
height: 720,
show: false,
backgroundColor: "#ffffff",
webPreferences: {
preload: resolvePreload(),
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
webSecurity: true,
allowRunningInsecureContent: false,
experimentalFeatures: false,
webviewTag: false,
spellcheck: false,
backgroundThrottling: true,
},
});
mainWindow.once("ready-to-show", () => {
mainWindow?.show();
});
mainWindow.webContents.on("did-finish-load", () => {
if (started) return;
started = true;
const pid = mainWindow?.webContents.getOSProcessId() ?? -1;
log({ evt: "window-created", id: mainWindow?.id, pid });
if (isSmoke) {
void runSmoke();
} else if (isShots) {
void runShots();
}
});
mainWindow.on("closed", () => {
if (!isSmoke) log({ evt: "window-closed" });
mainWindow = null;
});
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
void mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
} else {
void mainWindow.loadFile(
path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
);
}
}
async function runSmoke(): Promise<void> {
try {
await new Promise((resolve) => setTimeout(resolve, 300));
const probe = (await mainWindow?.webContents.executeJavaScript(`(() => {
const api = window.api;
return {
hasApi: typeof api === "object" && api !== null,
hasPing: typeof api?.ping === "function",
hasRequire: typeof window.require !== "undefined",
hasIpcRenderer: typeof window.ipcRenderer !== "undefined",
};
})()`)) as BridgeProbe;
const config = collectConfig();
log({
evt: "smoke",
ok:
probe.hasApi &&
probe.hasPing &&
!probe.hasRequire &&
!probe.hasIpcRenderer,
...probe,
contextIsolation: config.contextIsolation,
sandbox: config.sandbox,
});
app.quit();
} catch (error) {
log({ evt: "error", message: String(error) });
app.exit(1);
}
}
async function runShots(): Promise<void> {
try {
const dir = path.resolve(
process.cwd(),
"../../../docs/assets/images/05-preload-and-contextbridge",
);
await fs.mkdir(path.join(dir, "raw"), { recursive: true });
await mainWindow?.webContents.executeJavaScript(
`new Promise((resolve) => {
const started = Date.now();
const tick = () => {
if (typeof window.__setTab === "function") resolve(true);
else if (Date.now() - started > 3000) resolve(false);
else setTimeout(tick, 20);
};
tick();
})`,
);
const shots = [
{ tab: "exposure", file: "05-01-exposure.png" },
{ tab: "isolation", file: "05-02-isolation.png" },
{ tab: "serialization", file: "05-03-serialization.png" },
];
for (const shot of shots) {
await mainWindow?.webContents.executeJavaScript(
`window.__setTab(${JSON.stringify(shot.tab)})`,
);
await new Promise((resolve) => setTimeout(resolve, 120));
const image = await mainWindow?.webContents.capturePage();
if (!image) throw new Error("capturePage returned null");
const png = image.toPNG();
await fs.writeFile(path.join(dir, shot.file), png);
await fs.writeFile(path.join(dir, "raw", shot.file), png);
log({ evt: "shot", file: shot.file, bytes: png.byteLength });
}
app.quit();
} catch (error) {
log({ evt: "error", message: String(error) });
app.exit(1);
}
}
ipcMain.handle(CH.config, () => collectConfig());
ipcMain.handle(CH.ping, (_event, message: unknown) => {
if (typeof message !== "string") {
throw new Error("BAD_MESSAGE");
}
return `pong: ${message}`;
});
app.whenReady().then(() => {
log({ evt: "app-ready", electron: process.versions.electron });
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});