示例工程 05-preload-and-contextbridge
05-preload-and-contextbridge/demo-01-exposure-probe/main/index.ts
import { app, BrowserWindow } from "electron";
import path from "node:path";
app.whenReady().then(async () => {
const win = new BrowserWindow({
width: 720,
height: 480,
show: false,
webPreferences: {
preload: path.join(__dirname, "../preload/index.js"),
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
webSecurity: true,
allowRunningInsecureContent: false,
experimentalFeatures: false,
webviewTag: false,
spellcheck: false,
backgroundThrottling: true,
},
});
await win.loadURL("data:text/html,<h1>probe</h1>");
const probe = (await win.webContents.executeJavaScript(
`({
hasApi: typeof window.api === "object",
hasRequire: typeof require !== "undefined",
hasIpcRenderer: typeof window.ipcRenderer !== "undefined",
})`,
)) as { hasApi: boolean; hasRequire: boolean; hasIpcRenderer: boolean };
console.log(
JSON.stringify({
evt: "smoke",
ok: probe.hasApi && !probe.hasRequire && !probe.hasIpcRenderer,
...probe,
}),
);
app.quit();
});