示例工程 05-preload-and-contextbridge
05-preload-and-contextbridge/app/src/renderer.ts
import "./styles.css";
import type { BridgeConfig } from "../shared/ipc";
type TabId = "exposure" | "isolation" | "serialization";
declare global {
interface Window {
api: {
config(): Promise<BridgeConfig>;
ping(message: string): Promise<string>;
};
require?: unknown;
ipcRenderer?: unknown;
__setTab?: (tab: TabId) => void;
__snapshot?: () => unknown;
}
}
const state: {
tab: TabId;
config: BridgeConfig | null;
pingResult: string | null;
busy: boolean;
} = { tab: "exposure", config: null, pingResult: null, busy: false };
const tabs: Array<{ id: TabId; label: string }> = [
{ id: "exposure", label: "暴露面" },
{ id: "isolation", label: "隔离世界" },
{ id: "serialization", label: "传值边界" },
];
function escapeHtml(value: string): string {
return value
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """);
}
function available(value: boolean): string {
return value ? "可用" : "不可用";
}
function exposure(): string {
const hasApi = typeof window.api === "object" && window.api !== null;
const hasPing = typeof window.api?.ping === "function";
const hasRequire = typeof window.require !== "undefined";
const hasIpcRenderer = typeof window.ipcRenderer !== "undefined";
return `<div class="section">
<h2>页面能看到什么</h2>
<table class="table" data-testid="exposure-table">
<thead><tr><th>全局对象</th><th>状态</th><th>说明</th></tr></thead>
<tbody>
<tr><td><code>window.api</code></td><td data-testid="info-api">${available(hasApi)}</td><td>preload 暴露的白名单对象</td></tr>
<tr><td><code>window.api.ping</code></td><td>${available(hasPing)}</td><td>只暴露具体方法</td></tr>
<tr><td><code>window.require</code></td><td data-testid="info-require">${available(hasRequire)}</td><td>渲染进程拿不到 Node 模块系统</td></tr>
<tr><td><code>window.ipcRenderer</code></td><td data-testid="info-ipc">${available(hasIpcRenderer)}</td><td>不暴露 IPC 本体</td></tr>
</tbody>
</table>
<p class="hint">页面只能看到 <code>api</code>;<code>require</code> 与 <code>ipcRenderer</code> 都不在页面世界里。</p>
</div>`;
}
function isolation(config: BridgeConfig): string {
return `<div class="section">
<h2>隔离世界</h2>
<table class="table" data-testid="isolation-table">
<tbody>
<tr><td>contextIsolation</td><td><code>${config.contextIsolation}</code></td></tr>
<tr><td>sandbox</td><td><code>${config.sandbox}</code></td></tr>
<tr><td>nodeIntegration</td><td><code>${config.nodeIntegration}</code></td></tr>
<tr><td>preload</td><td><code>${escapeHtml(config.preload)}</code></td></tr>
</tbody>
</table>
<p class="hint">preload 在页面脚本之前、在一个隔离的 JavaScript 世界里执行;它与页面共享 DOM,但全局对象是分开的。</p>
<p class="hint">contextBridge 在两边做一次可序列化拷贝:函数被包装成可调用代理,对象被克隆,原型与引用关系不会过去。</p>
</div>`;
}
function serialization(result: string | null): string {
return `<div class="section">
<h2>传值边界</h2>
<p>点击按钮通过 <code>window.api.ping</code> 发一条字符串到主进程;主进程返回 <code>pong: ...</code>。</p>
<button class="tab active" data-testid="ping-button" id="ping-button">调用 ping</button>
<div class="section" data-testid="ping-result">
${
result
? `<p>结果:<code>${escapeHtml(result)}</code></p>`
: `<p class="hint">还没有调用。</p>`
}
</div>
<p class="hint">函数、普通对象、数组、字符串都能过桥;类实例的方法、DOM 节点、Promise 不行。跨进程传的是数据,不是对象图。</p>
</div>`;
}
function render(): void {
const root = document.querySelector<HTMLDivElement>("#app");
if (!root) return;
const body =
state.tab === "exposure"
? exposure()
: state.tab === "isolation"
? state.config
? isolation(state.config)
: `<p class="hint">正在读取配置…</p>`
: serialization(state.pingResult);
root.innerHTML = `
<header class="header">
<div>
<h1 data-testid="app-title">预加载脚本与 contextBridge</h1>
<p class="subtitle">页面只看得到白名单方法;preload 在隔离世界里跑</p>
</div>
<nav class="tabs">
${tabs
.map(
(tab) =>
`<button class="tab${state.tab === tab.id ? " active" : ""}" data-tab="${tab.id}" data-testid="tab-${tab.id}">${tab.label}</button>`,
)
.join("")}
</nav>
</header>
<main class="content">${body}</main>`;
for (const button of root.querySelectorAll<HTMLButtonElement>("[data-tab]")) {
button.addEventListener("click", () => {
const tab = button.dataset.tab;
if (
tab === "exposure" ||
tab === "isolation" ||
tab === "serialization"
) {
state.tab = tab;
render();
}
});
}
root.querySelector("#ping-button")?.addEventListener("click", async () => {
if (state.busy) return;
state.busy = true;
try {
state.pingResult = await window.api.ping("hello");
} finally {
state.busy = false;
render();
}
});
}
async function boot(): Promise<void> {
state.config = await window.api.config();
render();
window.__setTab = (tab) => {
state.tab = tab;
render();
};
window.__snapshot = () => ({
tab: state.tab,
hasApi: typeof window.api === "object",
hasRequire: typeof window.require !== "undefined",
});
}
void boot();