示例工程 05-preload-and-contextbridge
05-preload-and-contextbridge/demo-02-bridge-values/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>values</h1>");
const result = (await win.webContents.executeJavaScript(`(async () => {
const echoed = await window.api.echo({ a: [1, 2] });
let failure = "";
try {
await window.api.fail();
} catch (error) {
failure = error.message;
}
return { echoed, failure };
})()`)) as { echoed: { a: number[] }; failure: string };
console.log(
JSON.stringify({
evt: "smoke",
ok: result.echoed.a[1] === 2 && result.failure === "BOOM",
echoed: result.echoed,
failure: result.failure,
}),
);
app.quit();
});