《Electron 45.2.3 内核解剖》第 12 章 渲染进程初始化:从 preload 到 contextIsolation
第 11 章把 WebContents 拆到了底,最后留下三根线没有收:启动数据从哪来、ipcRenderer 怎么在页面里出现、四个 world 什么时候创建。这一章把这三根线接上。
但真正的难点不在"接上"。真正的难点是:Electron 的渲染进程初始化有两条完全不同、彼此不知道对方存在的路径,而文档把它们当成同一件事讲。 一条路径里,渲染进程跑着一个完整的 Node.js 环境,preload 是被 Node 的模块加载器 require 进来的;另一条路径里,渲染进程里连 require 这个单词都没有,preload 是被 C++ 用 v8::ScriptCompiler::CompileFunction 编译成一个匿名函数、再手工塞进五个参数调起来的。前者的 process 是 Node 的 process;后者的 process 是一个在 C++ 里一个属性一个属性拼出来的、长得像 process 的对象。
这两条路径在编译期是同一个二进制,在运行期靠一个命令行开关分开。搞清楚它们什么时候分叉、分叉后哪些行为会不一样,是本章的主目标。
12.0 规模、两条轴与一条主线
先把这一章要处理的文件摆出来。它们全部在 shell/renderer/ 与 lib/renderer/:
| 区域 | 文件 | 行数 | 职责 |
|---|---|---|---|
| 客户端基类 | renderer_client_base.cc / .h | 757 / 158 | 共享回调与 world 判定 |
| 客户端 A | electron_renderer_client.cc | 334 | 有 Node.js 的渲染进程 |
| 客户端 B | electron_sandboxed_renderer_client.cc | 225 | 无 Node.js 的渲染进程 |
| 启动数据消费者 | electron_api_service_impl.cc | 511 | 缓存推送的 RendererStartupData |
| 每帧观察者 | electron_render_frame_observer.cc | 247 | world 创建与分派 |
| preload 环境(B) | preload_environment.cc / preload_utils.cc | 310 / 272 | 无 Node 的 electron 模块与脚本执行 |
| preload realm | preload_realm_context.cc | 316 | service worker 的 ShadowRealm |
| JS 入口(A) | lib/renderer/init.ts:68 | 180 | Node 侧 renderer_init bundle |
| JS 入口(B) | common-init.ts:8 | 16 | ipcRenderer 预创建与 webview |
浏览器侧还有两个文件承担"发起方"的角色:renderer_startup_data.cc(194 行,构建推送内容)与 electron_api_web_contents.cc 里的三个函数(MaybeSendRendererStartupData :2764、SendRendererStartupData :2806、HandleNewRenderFrame :2292)。加上 shell/browser/preload_code_cache.*(代码缓存与信任锚),这一章覆盖的代码大约三千行。
两条轴
Electron 的渲染进程配置有两根正交的轴,很多人会把它们混成一根:
轴 1(进程级,启动时决定,之后不可变)
sandbox: true ──► ElectronSandboxedRendererClient ──► 进程里没有 Node.js
sandbox: false ──► ElectronRendererClient ──► 进程里有 Node.js
轴 2(帧级,偏好里决定,每个 frame 各自判定)
contextIsolation: true ──► preload 跑在 ISOLATED_WORLD_ID(999)
contextIsolation: false ──► preload 跑在 MAIN_WORLD_ID(0)
第一根轴决定"谁来执行 preload",第二根轴决定"preload 在哪个 V8 context 里执行"。它们可以自由组合,于是有四种组合,而不是文档暗示的两种:
sandbox | contextIsolation | preload 执行者 | preload 所在 world | preload 里能拿到什么 |
|---|---|---|---|---|
false | false | Node Module._load | main(0) | 完整 Node + 直接改页面 window |
false | true | Node Module._load | isolated(999) | 完整 Node,但只能通过 contextBridge 暴露 |
true | false | V8 CompileFunction | main(0) | 无 Node,electron 模块的子集 + process 仿制品 |
true | true | V8 CompileFunction | isolated(999) | 同上,且必须 contextBridge |
注意第三行:sandbox: true + contextIsolation: false 是允许的,它在 main world 里执行一个没有 Node 的 preload。这一格的语义经常被误解成"不可能"或"等于 sandbox + isolation",实际两者完全不同——它意味着 preload 可以直接改页面 window,但改的时候手里只有 ipcRenderer。
一条主线
整章的因果关系可以压成一句话:
浏览器在导航提交之前把"你该有什么"推过去(一次推送),渲染进程在第一个脚本执行之前把它装好(两个执行器),装的时候要挑一个 world(三个 world),装完还要按文档阶段发四个事件(四个生命周期事件)。
下面每一节对应这句话里的一个括号。
12.1 一个开关决定整个进程的性格
渲染客户端的选择发生得非常早——早到 content::ContentRendererClient 这个对象被创建的时候,也就是 Chromium 的 ContentMainRunner 刚把渲染进程拉起来、还没创建任何 RenderFrame 的时候:
electron_main_delegate.cc:425-435
content::ContentRendererClient*
ElectronMainDelegate::CreateContentRendererClient() {
auto* command_line = base::CommandLine::ForCurrentProcess();
if (IsSandboxEnabled(command_line)) {
renderer_client_ = std::make_unique<ElectronSandboxedRendererClient>();
} else {
renderer_client_ = std::make_unique<ElectronRendererClient>();
}
return renderer_client_.get();
}
四行判断,决定了后面三千行代码走哪一半。但这里有个容易被读错的地方:这个开关读的不是 webPreferences.sandbox,是命令行:
command_line_args.cc:57-60
bool IsSandboxEnabled(base::CommandLine* command_line) {
return command_line->HasSwitch(switches::kEnableSandbox) ||
!command_line->HasSwitch(sandbox::policy::switches::kNoSandbox);
}
两个条件或起来。第二个条件是"没有 --no-sandbox"。所以在默认情况下——两个开关都不加——它返回 true。渲染进程默认是沙箱的,这一点和很多人的直觉相反(2019 年之前确实是反的,sandbox: false 才是默认;contextIsolation 和 sandbox 的默认值在 Electron 12 与 20 两次大版本里翻转,见 12.14 的编年表)。
于是真正要解释的问题变成了反的:webPreferences.sandbox: false 是怎么变成渲染进程上的 --no-sandbox 的?
答案在 RendererProcessPreferences::AppendCommandLineSwitches:
web_contents_preferences.cc:125-141
void RendererProcessPreferences::AppendCommandLineSwitches(
base::CommandLine* command_line,
bool is_subframe) const {
...
// Sandbox can be enabled for renderer processes hosting cross-origin frames
// unless nodeIntegrationInSubFrames is enabled
bool can_sandbox_frame = is_subframe && !node_integration_in_sub_frames;
if (sandboxed || can_sandbox_frame) {
command_line->AppendSwitch(switches::kEnableSandbox);
} else if (!command_line->HasSwitch(switches::kEnableSandbox)) {
command_line->AppendSwitch(sandbox::policy::switches::kNoSandbox);
command_line->AppendSwitch(::switches::kNoZygote);
}
三件事值得逐条抠:
其一,can_sandbox_frame 让"子 frame 比父 frame 更安全"成为可能。 条件是 is_subframe && !node_integration_in_sub_frames。也就是说:一个 sandbox: false 的窗口,它里面的普通 iframe 仍然会被放进沙箱进程——除非你显式开了 nodeIntegrationInSubFrames。这解释了为什么在 sandbox: false 的页面里,iframe 里的 require 是 undefined,而主 frame 里能用。这不是 bug,是这一行的直接后果。
其二,--no-sandbox 后面紧跟着 --no-zygote。 这两个必须成对出现。Linux/ChromeOS 的进程模型是 zygote 预孵化:zygote 进程先把沙箱装上,fork 出来的子进程继承沙箱,从此不能再改。一个必须跑在无沙箱状态的渲染进程不能从 zygote 里 fork 出来,所以只能同时关掉 zygote,让它直接 fork+exec。少写一个 --no-zygote,进程会起来但沙箱仍然生效,然后 Node.js 初始化在 open() 被 EPERM 拒掉时崩掉。
其三,else if (!command_line->HasSwitch(kEnableSandbox)) 这个前置检查。 如果外部已经用命令行全局加了 --enable-sandbox(比如 app.commandLine.appendSwitch('enable-sandbox'),electron_api_app.cc:1621 就是这么做的),那么即使 sandbox: false 也不会再追加 --no-sandbox。全局开关压过单个 WebContents 的偏好。
这三行执行完,浏览器立刻把结果记下来:
electron_browser_client.cc:717-718
renderer_process_sandboxed_[unsafe_process_id] =
!command_line->HasSwitch(sandbox::policy::switches::kNoSandbox);
这就是 12.4 节要用的 IsRendererProcessSandboxed 的数据源——一个按进程 ID 索引的 map。注意它记的是命令行算出来的真相,不是偏好里的期望值。这两者前面说的 can_sandbox_frame 情形下会不一致,所以必须以命令行记录为准。
还有一条环境变量后门:ELECTRON_DISABLE_SANDBOX(electron_main_delegate.cc:197),它直接把 --no-sandbox 加到主进程命令行上,从而让所有渲染进程都变成无沙箱。这个变量在很多 CI 镜像里被默默设着,是"本地能跑、线上崩"的常见成因之一。
于是"帧级的偏好"在跨进程那一刻变成了"进程级的命令行",而进程一旦起来,这个决定就固化了。
这就是第一根轴为什么不可变:它不是配置,是进程的身份。
副作用是:同一个 WebContents 的不同 frame 可能落在不同性格的进程里。一个 sandbox: false 的窗口里嵌一个跨站 iframe,Chromium 的站点隔离会给那个 iframe 单独开进程,而那个进程的命令行是按它自己的偏好拼的。renderer_startup_data.cc:68-76 的注释把这件事说得很直白:
renderer_startup_data.cc:68-76
// Which renderer client will consume the data is a property of the process,
// not of the WebContents: a subframe or DevTools extension frame of a
// sandbox: false WebContents can be placed in a sandboxed process.
bool IsFrameInSandboxedRenderer(content::RenderFrameHost* rfh) {
return ElectronBrowserClient::Get()
->IsRendererProcessSandboxed(rfh->GetProcess()->GetID())
.value_or(WebContentsPreferences::ShouldUseSandbox(
content::WebContents::FromRenderFrameHost(rfh)));
}
三段式:先问"这个进程 ID 的沙箱状态记录过吗",没记录再退回"这个 WebContents 的偏好怎么设的",再没有就按 true 算。value_or 的默认值是沙箱——不确定的时候选更安全的那个。
12.1.1 两个客户端的类关系
content::ContentRendererClient
│
└── RendererClientBase (757 行,两种进程共用)
│
├── ElectronRendererClient (334 行,有 Node)
└── ElectronSandboxedRendererClient (225 行,无 Node)
基类承担了所有"和 Node 无关"的事:scheme 注册、插件覆写、扩展、拼写检查、world 判定、<webview> 的 main world 注入。两个子类只覆写真正分叉的四个方法:
| 虚函数 | 有 Node 的实现 | 无 Node 的实现 |
|---|---|---|
DidCreateScriptContext | 建 Node 环境 + Module._load 跑 preload | 建 process 仿制品 + CompileFunction 跑 preload |
WillReleaseScriptContext | 拆 Node 环境(七步) | 发 exit 事件 |
RunScriptsAtDocumentStart/End | 往真 process 上 EmitEvent | 往 hidden 的 process 上 EmitProcessEvent |
HasScriptsToInject | 恒 true(:422-425) | 看 webview_tag 或启动数据里有没有 preload |
HasScriptsToInject 这个差异非常关键,它是"要不要为这个 frame 强行创建 main world 的 V8 context"的判据,下一节展开。
12.1.2 基类构造:七个 scheme 开关
RendererClientBase 的构造函数(renderer_client_base.cc:176-217)没有做任何初始化逻辑,全部在解析命令行:
// shell/renderer/renderer_client_base.cc:176-217(节选)
RendererClientBase::RendererClientBase() {
auto* command_line = base::CommandLine::ForCurrentProcess();
for (const std::string& scheme :
ParseSchemesCLISwitch(command_line, switches::kServiceWorkerSchemes))
electron::api::AddServiceWorkerScheme(scheme);
for (const std::string& scheme :
ParseSchemesCLISwitch(command_line, switches::kStandardSchemes))
url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITH_HOST);
for (const std::string& scheme :
ParseSchemesCLISwitch(command_line, switches::kCORSSchemes))
url::AddCorsEnabledScheme(scheme.c_str());
for (const std::string& scheme :
ParseSchemesCLISwitch(command_line, switches::kStreamingSchemes))
blink::AddStreamingScheme(scheme.c_str());
for (const std::string& scheme :
ParseSchemesCLISwitch(command_line, switches::kSecureSchemes))
url::AddSecureScheme(scheme.data());
for (const std::string& scheme :
ParseSchemesCLISwitch(command_line, switches::kExtensionSchemes))
url::AddExtensionScheme(scheme.c_str());
DCHECK(command_line->HasSwitch(::switches::kRendererClientId));
renderer_client_id_ =
command_line->GetSwitchValueASCII(::switches::kRendererClientId);
g_renderer_client_base = this;
}
为什么要用命令行传,而不是像浏览器进程那样直接查注册表?因为 protocol.registerSchemesAsPrivileged 的结果存在浏览器进程的 url::SchemeRegistry 里,而 url::SchemeRegistry 是进程内静态表,渲染进程里是空的。Chromium 自己的解决方式就是把 scheme 特权做成一串命令行开关(--standard-schemes=、--cors-schemes= 等),Electron 沿用这套机制。
七个开关的语义:
| 开关 | 效果 | 写错的后果 |
|---|---|---|
--standard-schemes | url::AddStandardScheme(SCHEME_WITH_HOST) | new URL() 解析失败、location.origin 为 null |
--secure-schemes | 视为安全上下文 | crypto.subtle、Service Worker、SharedArrayBuffer 全部不可用 |
--cors-schemes | 允许 CORS 请求 | fetch 到该 scheme 被当作跨域拒绝 |
--streaming-schemes | 支持流式响应 | ReadableStream 响应体被缓冲 |
--service-worker-schemes | 允许注册 SW | navigator.serviceWorker.register 抛 SecurityError |
--bypass-csp-schemes | 无视页面 CSP | 资源被 CSP 拦掉 |
--code-cache-schemes | 允许 V8 代码缓存 | 每次冷启动都重新编译 |
最后那个 renderer_client_id_ 不是 scheme 相关,它是 Chromium 给每个 RenderProcessHost 分配的唯一 ID,Electron 用它拼 process.contextId(后面 12.8 节会看到)。
12.1.3 单例与进程级注册
g_renderer_client_base 是一个裸指针,构造函数里赋值、析构里清空(renderer_client_base.cc:154-155、:216、:220),通过 Get()(:224-227)访问。这不是懒初始化,是"Chromium 只会创建一个 ContentRendererClient"这个事实的直接映射。
同一个构造函数里还有一件隐藏的事:以 root 跑并开沙箱会直接失败(electron_main_delegate.cc:223)。Chrome 的 setuid sandbox helper 拒绝以 root 运行,Electron 只是把 Chromium 的既有规则抄了过来。容器里跑 Electron 常见的第一条报错就是它。
12.2 进程起来之后、第一帧之前
CreateContentRendererClient 返回之后,Chromium 会依次调用几个客户端钩子。Electron 在其中三个里塞了东西。
12.2.1 PostIOThreadCreated:关掉一个 V8 陷阱
electron_renderer_client.cc:72-78
void ElectronRendererClient::PostIOThreadCreated(
base::SingleThreadTaskRunner* io_thread_task_runner) {
// Freezing flags after init conflicts with node in the renderer.
// We do this here in order to avoid having to patch the ctor in
// content/renderer/render_process_impl.cc.
v8::V8::SetFlagsFromString("--no-freeze-flags-after-init");
}
V8 在初始化完成后会"冻结" flag,之后 SetFlagsFromString 静默失效。这对纯 Chromium 是合理的安全措施,对 Electron 不成立:Node.js 的 --v8-options 处理、v8.setFlagsFromString 的语义、以及某些 NODE_OPTIONS 里的 V8 开关,都要求初始化之后还能改 flag。这里选在 IO 线程创建后立刻解冻,是因为此时 V8 已经初始化完,而 Node 环境还没建。
注意这个覆写只在 ElectronRendererClient 里,ElectronSandboxedRendererClient 没有——沙箱渲染进程本来就不跑 Node,不需要解冻。这个细节本身就是两条路径分叉的第一个证据。
12.2.2 RenderThreadStarted:一堆全局注册
renderer_client_base.cc:255-340 是渲染进程唯一一次"全局配置"机会。按执行顺序:
- 打开
MessagePortCloseEvent(:263-264)。这是一段历史债的注释:
// Enable MessagePort close event by default.
// The feature got reverted from stable to test in
// https://chromium-review.googlesource.com/c/chromium/src/+/5276821
// We had the event supported through patch before upstream support,
// this is an alternative option than restoring our patch.
上游把 MessagePort 的 close 事件从 stable 退回 test,Electron 之前是靠补丁支持的,现在改成运行时特性开关——比维护补丁便宜。
- 扩展客户端(
:266-290):注册ElectronExtensionsClient与两个 API provider,然后把chrome-extensionscheme 注册成"支持 Fetch API"、"顶层文档视为第一方"、"绕过 CSP"。 - 拼写检查器(
:292-294)。 <webview>与<browserplugin>变为合法自定义元素名(:296-297):blink::WebCustomElement::AddEmbedderCustomElementName让document.createElement('webview')不抛NotSupportedError。它只做"名字合法",真正的元素定义要靠 JS bundle 调customElements.define。- 五个 scheme 开关的第二轮注册(
:299-323)。构造函数里调的是url::AddStandardScheme这类进程级 URL 层接口,这里调的是blink::WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI这类渲染引擎层接口——两层各有各的表。 file://的特权(:325-330),被 fuse 包着:IsGrantFileProtocolExtraPrivilegesEnabled()为真时才允许file://页面注册 Service Worker 和fetch。关掉它,很多老应用会挂——这正是它被做成 fuse 而不是默认行为的原因。- Windows 的 AppUserModelID(
:332-339)。渲染进程也要设,否则任务栏归组会错。
12.3 每一帧诞生:六个观察者
RenderFrameCreated 是每个 frame(不只是主 frame)都会走一次的钩子。基类版本(renderer_client_base.cc:362-399)在这里创建了六个观察者对象(外加一个非观察者的安全检查调用):
void RendererClientBase::RenderFrameCreated(
content::RenderFrame* render_frame) {
#if defined(TOOLKIT_VIEWS)
new AutofillAgent(render_frame,
render_frame->GetAssociatedInterfaceRegistry());
#endif
new ContentSettingsObserver(render_frame);
#if BUILDFLAG(ENABLE_PRINTING)
new printing::PrintRenderFrameHelper(
render_frame,
std::make_unique<electron::PrintRenderFrameHelperDelegate>());
#endif
// Note: ElectronApiServiceImpl has to be created now to capture the
// DidCreateDocumentElement event.
new ElectronApiServiceImpl(render_frame, this);
MaybeAddSecurityWarnings(render_frame);
...
顺序不是随意的。new 出来的对象都是 RenderFrameObserver 子类,它们自己负责在 frame 销毁时 delete this(各家的 OnDestruct)。谁先创建,谁先收到同一批观察者回调,因为 Chromium 的 RenderFrameObserver 是按注册顺序遍历的。
12.3.1 ElectronApiServiceImpl 为什么必须在这里创建
注释写得很清楚:to capture the DidCreateDocumentElement event。但真正的原因比这更硬:
electron_api_service_impl.cc:130-139
// Associated with content.mojom.Frame, so SetStartupData() arrives before
// the CommitNavigation that follows it — i.e. before DidCreateScriptContext.
render_frame->GetAssociatedInterfaceRegistry()
->AddInterface<mojom::ElectronFrame>(base::BindRepeating(
&ElectronApiServiceImpl::BindFrameReceiver, base::Unretained(this)));
// window.open() popup's about:blank fires DidCreateScriptContext before
// any push can land; the browser attaches its startup data to the
// CreateNewWindowReply and SetPendingCreateNewWindowStartupData() stashes it
// for us on this same call stack. The first real navigation replaces it.
startup_data_ = std::exchange(*GetPendingNewWindowStartupData(), nullptr);
两件事同时发生:
- 它往
AssociatedInterfaceRegistry上挂了mojom::ElectronFrame的接收端。这个 registry 和content.mojom.Frame共用一条 channel,所以浏览器从ReadyToCommitNavigation里发出的SetStartupData一定排在紧随其后的CommitNavigation之前。如果这个时机晚于导航开始,SetStartupData就会因为找不到接收端而被丢弃。 - 它顺手把进程级的"待领启动数据"取走放入自己身上。这份数据来自
window.open()的CreateNewWindowReply,是唯一一条不经过导航的推送路径(12.4.5 展开)。
再往下看 BindTo(:159-172):
electron_api_service_impl.cc:160-167
void ElectronApiServiceImpl::BindTo(
mojo::PendingReceiver<mojom::ElectronRenderer> receiver) {
if (document_created_) {
if (receiver_.is_bound())
receiver_.reset();
receiver_.Bind(std::move(receiver));
receiver_.set_disconnect_handler(base::BindOnce(
&ElectronApiServiceImpl::OnConnectionError, GetWeakPtr()));
} else {
pending_receiver_ = std::move(receiver);
}
}
这里的 document_created_ 是 DidCreateDocumentElement 里置位的。浏览器侧可能在 document element 存在之前就尝试连 ElectronRenderer(比如导航刚提交就要 executeJavaScript),此时 receiver 被暂存,等 document 建好再真正 Bind。一个"等事件"的延迟绑定——这就是注释里说的"必须现在创建才能捕获 DidCreateDocumentElement"的实际用途。
MaybeAddSecurityWarnings(security_warnings.cc:274)在页面是 http:、file: 或 data: 且开了 Node 集成时往 console 打警告。它只在开发时有用,但揭示了一个设计取向:Electron 不阻止危险配置,只在控制台喊。
12.3.2 子类在这之后加自己的东西
electron_renderer_client.cc:80-84
void ElectronRendererClient::RenderFrameCreated(
content::RenderFrame* render_frame) {
new ElectronRenderFrameObserver(render_frame, this);
RendererClientBase::RenderFrameCreated(render_frame);
}
注意顺序:先建自己的 ElectronRenderFrameObserver,后调基类。这意味着 ElectronRenderFrameObserver 比 ElectronApiServiceImpl 更早收到每个观察者回调。
这个顺序确实重要。DidInstallConditionalFeatures(world 创建的唯一入口)由 ElectronRenderFrameObserver 处理,而它里面会调 renderer_client_->DidCreateScriptContext(...)(electron_render_frame_observer.cc:157-158),后者才是真正建 Node 环境、跑 preload 的地方。如果 ElectronRenderFrameObserver 晚于 ElectronApiServiceImpl 创建,启动数据虽然已经在了,但 world 分派会排在别的观察者之后——目前看不会坏,但没有理由冒险。
ElectronSandboxedRendererClient::RenderFrameCreated(:80-84)写法完全一样。两个子类在这个方法上唯一的差别就是基类调用之后的行为,而它们都没有额外行为,所以这个方法实际上是"创建帧观察者 + 走基类"的同义反复。
12.3.3 RenderFrameObserverTracker
electron_render_frame_observer.cc:56-57
: content::RenderFrameObserver(frame),
content::RenderFrameObserverTracker<ElectronRenderFrameObserver>(frame),
RenderFrameObserverTracker<T> 是 Chromium 提供的一个按 RenderFrame 索引的静态映射,T::From(frame) 可以 O(1) 取回实例。Electron 用它让"给定一个 RenderFrame*,找到它的观察者"变成不需要遍历的操作。ElectronApiServiceImpl 同理(electron_api_service_impl.cc:124-125),而且它对外暴露了 Get(render_frame) 静态方法给 preload 环境用(preload_utils.cc:100、electron_renderer_client.cc:187)。
到这里,进程和帧都准备好了,但它们手里还是空的——preload 的路径、内容、环境变量一个都还没有。下一节讲这些数据怎么从浏览器过来。
12.4 启动数据:一次推送,不是一次拉取
12.4.1 老做法为什么必须死
现在搜 BROWSER_SANDBOX_LOAD 只剩注释与常量。这个同步 IPC 曾经是渲染进程初始化的第一件事:渲染进程建好 Node 环境后发一条同步 IPC 问"我该跑哪些 preload、环境变量是什么、helper 在哪",浏览器在自己的 IPC 处理器里读磁盘、拼结构体、回包。
问题在"同步":渲染进程整个主线程挂住等浏览器。而浏览器处理这条消息要读 preload 文件——asar 里就是一次 mmap 冷读,慢盘上几十毫秒。单次不算什么,但这条链路会被并发放大:Chromium 打开多个页面时会并行创建多个渲染进程,每个都发同步 IPC,浏览器主线程串行处理,第 N 个页面要等前面 N−1 个读完。更糟的是如果浏览器此刻正在等某个渲染进程的同步 IPC(ipcRenderer.sendSync),就形成跨进程死锁三角。
新做法把方向反过来:浏览器在导航提交之前把数据推过去,渲染进程只管收。
12.4.2 主路径:ReadyToCommitNavigation
electron_api_web_contents.cc:2834-2839
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
base::AutoReset<bool> resetter(&is_safe_to_delete_, false);
EmitNavigationEvent("-ready-to-commit-navigation", navigation_handle);
MaybeSendRendererStartupData(navigation_handle);
选这个钩子而不是 DidStartNavigation 或 DidFinishNavigation,是因为它是唯一一个同时满足三个条件的时机:
RenderFrameHost已经确定(navigation_handle->GetRenderFrameHost()可用了),所以知道往哪个 frame 发。CommitNavigation还没发出去,所以推送可以通过同一条 channel 排到它前面。- 渲染进程已经知道"要加载哪个 URL、哪个 origin",所以 URL filter 可以按真实文档匹配。
三点里第二点是硬约束。Chromium 的 RenderFrameHost 在渲染进程侧对应一个 mojo::AssociatedRemote<mojom::ElectronFrame>,它和 content.mojom.Frame 共用一条 associated channel。associated interface 的核心特性是保序:同一个 channel 上先发的消息一定先到。所以从 ReadyToCommitNavigation 里 SetStartupData 出去的消息,必然先于浏览器随后发出的 CommitNavigation 到达渲染进程,也就必然先于 DidCreateScriptContext。
api.mojom:48-52 把这个契约写在了接口注释里:
// Per-frame interface associated with content.mojom.Frame, so its messages and
// replies are ordered with navigation and the frame's other host messages:
// SetStartupData() arrives before the CommitNavigation that follows it, and a
// reply is seen after anything the frame told its host while handling the
// request.
interface ElectronFrame {
SetStartupData(RendererStartupData data);
12.4.3 谁该收到:三层过滤
MaybeSendRendererStartupData(:2764-2804)在真正构建数据之前要做三层判断。这三层判断必须和渲染进程侧的 RendererClientBase::ShouldLoadPreload(renderer_client_base.cc:241-253)逐条对齐,否则会出现"浏览器以为不用发、渲染进程以为该有"的空窗:
void WebContents::MaybeSendRendererStartupData(
content::NavigationHandle* navigation_handle) {
auto* web_prefs = WebContentsPreferences::From(web_contents());
content::RenderFrameHost* rfh = navigation_handle->GetRenderFrameHost();
if (!rfh || !rfh->IsRenderFrameLive())
return;
const GURL& url = navigation_handle->GetURL();
bool main_frame = navigation_handle->IsInMainFrame();
bool allow_subframes =
web_prefs && web_prefs->AllowsNodeIntegrationInSubFrames();
bool is_devtools_like =
url.SchemeIs("devtools") ||
(url.SchemeIs("chrome-extension") && !main_frame &&
rfh->GetMainFrame()->GetLastCommittedURL().SchemeIs("devtools"));
if (!main_frame && !allow_subframes && !is_devtools_like)
return;
...
第一层:frame 必须活着。
rfh->IsRenderFrameLive() 为假意味着渲染进程已经崩了或者正在销毁,此时推过去的消息会落进黑洞——更糟的是,如果 frame 处于"待销毁"状态,GetRemoteAssociatedInterfaces() 可能返回一个已经解绑的 channel。直接 return 比 assert 好,因为导航被取消是正常路径。
第二层:主 frame,或者允许子 frame 跑 Node,或者是 DevTools。
is_devtools_like 那个表达式值得单独看:
electron_api_web_contents.cc:2785-2787
url.SchemeIs("devtools") ||
(url.SchemeIs("chrome-extension") && !main_frame &&
rfh->GetMainFrame()->GetLastCommittedURL().SchemeIs("devtools"))
它把两种情况归为同类:一是 DevTools 前端自己(devtools://),二是宿主在 DevTools 前端里的扩展文档(chrome-extension:// 且主 frame 是 devtools://)。后者的典型是 devtools_page 与自定义面板。
而如果是"普通页面里嵌了一个可访问的扩展资源 iframe"(chrome-extension:// 但主 frame 不是 devtools),就不算——它按普通子 frame 处理。
渲染进程侧有一份镜像实现(renderer_client_base.cc:165-172 的 IsDevToolsExtension):比的是"主 frame 的安全 origin 协议是不是 devtools",而不是"最后提交的 URL scheme"。两者在这一场景等价,但实现方式不同——浏览器侧拿不到 blink::WebFrame,渲染进程侧拿不到 NavigationHandle。跨进程的同一判断必须写两遍,这是 Electron 里反复出现的模式。
第三层:data: URL 的 base URL 修正。
electron_api_web_contents.cc:2794-2801
const GURL& base_url = navigation_handle->GetBaseURLForDataURL();
const bool is_load_data_with_base_url =
navigation_handle->IsInPrimaryMainFrame() &&
navigation_handle->GetNetErrorCode() == net::OK &&
url.SchemeIs(url::kDataScheme) && base_url.is_valid();
SendRendererStartupData(
rfh, is_load_data_with_base_url ? base_url : url,
navigation_handle->GetOriginToCommit().value_or(url::Origin()));
loadURL('data:text/html,...', { baseURLForDataURL: 'https://example.com/' }) 这个 API 让 data URL 的文档"假装"自己来自某个 URL。如果 preload 的 URL filter 写的是 https://example.com/*,用户期望它在这个 data URL 上生效。所以匹配要用 base URL 而不是 data: 本身。
IsInPrimaryMainFrame() 这个限定很关键:只有主 frame 的 data URL 才有 GetBaseURLForDataURL(),子 frame 的 data URL 没有 base 概念(它继承父文档的 origin)。加上 IsPrimaryMainFrame 就避免了在子 frame 上误用。
整段判断与 content::NavigationRequest::IsLoadDataWithBaseURL() 逐条对应——注释里明说了。Electron 在这里复制了 Chromium 的内部判定逻辑,因为那个函数不在 public API 里。
12.4.4 构建与发送:为什么可以先阻塞
electron_api_web_contents.cc:2806-2832
void WebContents::SendRendererStartupData(content::RenderFrameHost* rfh,
const GURL& url,
const url::Origin& origin) {
if (!rfh || !rfh->IsRenderFrameLive())
return;
mojom::RendererStartupDataPtr data;
{
// We're on the UI thread. The asar is mmap'd and offset-indexed so warm
// reads are fast; cold reads block briefly. Crucially the renderer is NOT
// parked waiting on us here — we haven't sent CommitNavigation yet — so
// unlike the old sync IPC handler this can't amplify under contention.
ScopedAllowBlockingForElectron allow_blocking;
data = renderer_startup_data::BuildForFrame(rfh, url, origin);
}
mojo::AssociatedRemote<mojom::ElectronFrame> frame_startup;
rfh->GetRemoteAssociatedInterfaces()->GetInterface(&frame_startup);
frame_startup->SetStartupData(std::move(data));
}
ScopedAllowBlockingForElectron 是一个"我知道我在阻塞"的显式声明。Chromium 的线程限制机制会在 release 构建里对 UI 线程上的文件 IO 直接 CHECK 失败,这个 RAII 对象临时解除限制。
为什么这次阻塞可以被接受?注释给了完整论证:渲染进程此刻没有在等我们。CommitNavigation 还没发出去,渲染进程那边连导航都还没开始,没有人在同步等待。所以这里的阻塞只是让浏览器主线程多花了读文件的时间,不会变成跨进程的等待链,也就不会被并发放大。
对比一下老路径:渲染进程发同步 IPC → 挂住 → 浏览器读文件 → 回包 → 渲染进程继续。同样是"读文件花了几毫秒",但老路径里这段时间渲染进程是死的,且多个渲染进程会排队。新路径里所有渲染进程都还没开始跑,浏览器读完就直接发,读完的代价是线性的、不可放大的。
这就是"推 vs 拉"的真正区别,不是"省了一次 IPC 往返"那么简单——是把一个可能形成等待图的同步点,改成了一个不会形成等待图的异步点。
12.4.5 第二处推送:HandleNewRenderFrame 与初始空文档
ReadyToCommitNavigation 覆盖了"正常导航",但有一种情形它覆盖不到:frame 的初始空文档上就创建了 script context。
场景是这样的:webContents 刚创建,还没导航;此时有人调 webFrameMain.executeJavaScript('...'),或者渲染进程里的某些内部逻辑(DevTools 协议、<webview> 的初始化)需要在空文档上跑脚本。Chromium 会为这个空文档创建一个 RenderFrame 和一个 V8 context,DidCreateScriptContext 会触发,但没有任何导航发生过,所以 ReadyToCommitNavigation 没跑过,启动数据是空的。
老的同步 IPC 方案天然没这个问题——渲染进程想什么时候问就什么时候问。新方案必须显式补上:
electron_api_web_contents.cc:2319-2330
// A Node.js renderer used to fetch its preload list with a sync IPC, which
// also worked for a script context created on the frame's initial empty
// document (first navigation still pending or cancelled, then e.g.
// webFrameMain.executeJavaScript()). Push the list at frame creation so
// that case still sees it; the payload is only the paths, so the extra
// message per frame is cheap. ReadyToCommitNavigation refreshes it.
if (!renderer_startup_data::IsFrameInSandboxedRenderer(render_frame_host)) {
const bool allow_subframes =
web_preferences && web_preferences->AllowsNodeIntegrationInSubFrames();
if (!render_frame_host->GetParent() || allow_subframes)
SendRendererStartupData(render_frame_host, GURL(url::kAboutBlankURL),
render_frame_host->GetLastCommittedOrigin());
}
三个限定值得注意:
- 只对非沙箱进程做。 因为沙箱路径的 preload 内容要读文件、要算 hash、要查代码缓存,代价不小;而初始空文档上的 preload 在沙箱路径里几乎不会被执行(沙箱渲染进程的空文档通常还没拿到
preload_scripts,HasScriptsToInject返回假,DidCreateScriptContext直接 return)。注释里"the payload is only the paths, so the extra message per frame is cheap"说的就是这点——非沙箱路径的ReadPreloadScript带read_contents=false,只填id和file_path,不读文件。 - URL 用
about:blank,origin 用GetLastCommittedOrigin()。 这是"我还不知道你要去哪"时最合理的猜测。URL filter 会按about:blank匹配,多半匹配不上,但至少不会误匹配到某个具体站点的规则。 is_subframe也要检查。 主 frame 一律发;子 frame 只在nodeIntegrationInSubFrames时发。
这处推送发生在 HandleNewRenderFrame(:2292)里,比 RenderFrameCreated 更早——它由 WebContentsObserver::RenderFrameCreated 的同级回调触发,此时渲染进程侧的 ElectronApiServiceImpl 可能刚被 new 出来。因为 associated interface 的接收端是在 RenderFrameCreated 里注册的,而浏览器侧这条消息要经过 mojo 序列化、跨进程、再投递到渲染进程主线程,中间至少有若干轮消息循环,所以"发送时接收端还没注册"在这里不会造成丢失。
12.4.6 第三处推送:window.open() 的 CreateNewWindowReply
这是最刁的一条。window.open('about:blank') 的流程是:渲染进程调 window.open → Blink 发一个同步的 CreateNewWindow mojo 调用给浏览器 → 浏览器创建 WebContents、决定 WebPreferences、回一个 CreateNewWindowReply → 渲染进程收到回复后在同一个调用栈里创建新 frame 和它的 V8 context,然后同步返回。
注意"同一个调用栈":从收到 reply 到 DidCreateScriptContext 触发,中间没有任何消息循环。所以任何"异步推送"都不可能在这之前到达。
Electron 的解法是把数据塞进 reply 本身:
renderer_client_base.cc:349-360
void RendererClientBase::SetPendingCreateNewWindowStartupData(
mojo_base::BigBuffer data) {
// Deserialize the opaque blob from CreateNewWindowReply and stash it for
// the about-to-be-created RenderFrame's ElectronApiServiceImpl. Same call
// stack, no reentrancy.
mojom::RendererStartupDataPtr deserialized;
if (mojom::RendererStartupData::Deserialize(base::span<const uint8_t>(data),
&deserialized)) {
ElectronApiServiceImpl::SetPendingNewWindowStartupData(
std::move(deserialized));
}
}
数据在浏览器侧被 flat 序列化成一个不透明 blob(这就是 api.mojom:13-15 里 contents 用 array<uint8> 而不是 BigBuffer 的原因——后者不能参与 flat 序列化),随 reply 一起过来,渲染进程反序列化后放进一个进程级静态变量。
然后新 frame 的 ElectronApiServiceImpl 在构造函数里把它领走:
electron_api_service_impl.cc:136-139
// window.open() popup's about:blank fires DidCreateScriptContext before
// any push can land; the browser attaches its startup data to the
// CreateNewWindowReply and SetPendingCreateNewWindowStartupData() stashes it
// for us on this same call stack. The first real navigation replaces it.
startup_data_ = std::exchange(*GetPendingNewWindowStartupData(), nullptr);
std::exchange 保证只被领一次。存储介质是一个 base::NoDestructor<mojom::RendererStartupDataPtr>(:53-60),配了 DCHECK(content::RenderThread::Get()) 断言必须在渲染主线程调用——因为这里没有任何锁,正确性完全依赖"set → 创建 frame → take 全在一个同步调用栈里"这个事实。
三处推送的分工:
| 场景 | 入口 | 内容 | 顺序保证 |
|---|---|---|---|
| 正常导航 | ReadyToCommitNavigation | 完整(含 contents / cache / env) | associated channel,早于 CommitNavigation |
| 初始空文档 | HandleNewRenderFrame | 只有路径(仅非沙箱) | 早于任何帧上消息 |
window.open 空文档 | CreateNewWindowReply → 静态变量 → ctor | 完整 | 同一个调用栈 |
---|---|---|---|---|
| 正常导航 | ReadyToCommitNavigation → MaybeSendRendererStartupData | 导航 | 完整(含 contents / cache / env) | associated channel,早于 CommitNavigation |
| 初始空文档 | HandleNewRenderFrame | frame 创建 | 只有路径(非沙箱) | 早于任何帧上消息 |
| window.open 空文档 | CreateNewWindowReply → 静态变量 → ctor | 同步 reply | 完整 | 同一个调用栈 |
12.5 启动数据里到底装了什么
renderer_startup_data.h 里三个函数的注释已经把语义写死了,但细节藏在实现里。
12.5.1 结构
api.mojom:10-17
struct PreloadScriptData {
string id;
string file_path;
// UTF-8 contents. array<uint8> rather than BigBuffer so RendererStartupData
// can be flat-serialized into an opaque blob for the CreateNewWindowReply
// path.
array<uint8> contents;
// Set if the file could not be read; surfaced via the 'preload-error' event.
string? error;
// V8 code cache, produced by the first renderer to compile this preload and
// persisted under userData/Code Cache/electron-preload/. Only shipped when
// its recorded source hash matches |contents|.
array<uint8>? code_cache;
};
struct RendererStartupData {
array<PreloadScriptData> preload_scripts;
// Browser process.env, captured fresh per push.
map<string, string> environment;
string helper_exec_path;
};
三个字段的三种用途:preload_scripts 两条路径都用;environment 与 helper_exec_path 只给沙箱路径用(非沙箱渲染进程有真的 process.env 与 process.execPath)。contents 用 array<uint8> 而不用 BigBuffer,唯一原因是后者不能参与 flat 序列化——而 window.open 那条路要把整个结构塞进不透明 blob。
12.5.2 顺序:session preload 在前,webPreferences.preload 在后
renderer_startup_data.cc:160-167
// shell/browser/renderer_startup_data.cc:160-192(节选)
mojom::RendererStartupDataPtr BuildForFrame(content::RenderFrameHost* rfh,
const GURL& url,
const url::Origin& origin) {
const preload_code_cache::Scope scope =
preload_code_cache::ScopeForFrame(rfh);
auto* web_contents = content::WebContents::FromRenderFrameHost(rfh);
const bool sandboxed = IsFrameInSandboxedRenderer(rfh);
std::vector<preload_code_cache::ServedPreload> served;
auto data = BuildInternal(rfh->GetBrowserContext(),
PreloadScript::ScriptType::kWebFrame, url, &origin,
scope, sandboxed ? &served : nullptr, sandboxed);
...
auto* web_prefs = WebContentsPreferences::From(web_contents);
std::optional<base::FilePath> preload;
if (web_prefs)
preload = web_prefs->GetPreloadPath();
if (preload && preload->IsAbsolute()) {
data->preload_scripts.push_back(ReadPreloadScript(
preload_code_cache::IdForWebPreferencesPreload(*preload), *preload,
scope, sandboxed ? &served : nullptr, sandboxed));
}
BuildInternal 先按 session 注册顺序把 session.registerPreloadScript() 注册的脚本塞进去,然后这里再把 webPreferences.preload 追加到末尾。
这个顺序是规范的一部分。 renderer_startup_data.h:40-43 的注释说它"与 legacy BROWSER_SANDBOX_LOAD 处理器的 getPreloadScriptsFromEvent() 相同"。为什么重要?因为 preload 之间会通过 window 上的隐藏变量互相通信(webFrame.setPreloadScripts 时代就有的做法),后跑的能看见先跑的留下的东西。顺序变了,用户的 preload 会突然读不到 session preload 设的值。
12.5.3 MatchesDocument 与 URL filter
renderer_startup_data.cc:125-139
auto* session_prefs = SessionPreferences::FromBrowserContext(browser_context);
if (session_prefs) {
for (const auto& script : session_prefs->preload_scripts()) {
if (script.script_type != type)
continue;
if (!script.file_path.IsAbsolute())
continue;
if (!(origin ? script.MatchesDocument(url, *origin)
: script.MatchesURL(url))) {
continue;
}
data->preload_scripts.push_back(ReadPreloadScript(
script.id, script.file_path, scope, served, sandboxed));
}
}
三个跳过条件:
- 类型不匹配。
kWebFrame与kServiceWorker分开,一个脚本只能属于一类。 - 路径不是绝对路径。 相对路径的基准在浏览器里是"当前工作目录",在渲染进程里是"进程的 cwd",两者可能不同。直接跳过比猜更安全。
- URL filter 不匹配。 注意 frame 用
MatchesDocument(url, origin),service worker 用MatchesURL(url)(origin传nullptr)。preload_script.h:68-71解释了差别:MatchesDocument在MatchesURL之外还检查 origin——因为 service worker 的 scope 没有文档 origin 概念。
12.5.4 沙箱与非沙箱:读不读文件内容
renderer_startup_data.cc:80-110
mojom::PreloadScriptDataPtr ReadPreloadScript(
const std::string& id,
const base::FilePath& path,
const preload_code_cache::Scope& scope,
std::vector<preload_code_cache::ServedPreload>* served,
bool read_contents) {
auto ps = mojom::PreloadScriptData::New();
ps->id = id;
ps->file_path = path.AsUTF8Unsafe();
// A frame with Node.js integration loads its preloads through Node's own
// module loader and only needs to be told which files; reading them (and
// consulting the code cache) here would be wasted work.
if (!read_contents)
return ps;
std::string contents;
if (!asar::ReadFileToString(path, &contents)) {
ps->error =
"ENOENT: no such file or directory, open '" + ps->file_path + "'";
return ps;
}
ps->contents.assign(contents.begin(), contents.end());
...
read_contents 就是 sandboxed。非沙箱路径只拿到 id 和 file_path,文件由渲染进程自己用 Node 的 Module._load 读。沙箱路径拿到 contents,因为渲染进程里没有 fs。
这个差异带来一个不那么直观的后果:非沙箱路径的 preload 文件读取错误,报错文案来自 Node.js(Cannot find module '...'),而沙箱路径的报错来自这里(ENOENT: no such file or directory, open '...')。同一个错误,两条路径给出两种文案——这是排查问题时判断"我到底在哪种渲染进程里"的最快方法,比 process.sandboxed 还快,因为在 preload 崩掉的情况下你连 process 都拿不到。
asar::ReadFileToString 而不是 base::ReadFileToString:asar 是一条 Electron 自己实现的虚拟文件系统,fs 模块的读取被劫持到它上面,但 C++ 侧的正常文件 API 不会。要读 asar 内部的文件必须走 asar:: 命名空间。
12.5.5 环境变量快照:每次推送重取
CaptureBrowserEnvironment(renderer_startup_data.cc:38-52)用 uv_os_environ 而不是 getenv:前者读的是 libuv 维护的数组,Node 的 process.env 写入会同步到它;getenv 在某些平台读的是进程启动时的 environ 快照,会漏掉 Node 层的修改。
三个细节:每次推送都重取(主进程改 process.env.FOO 之后新开的页面能看见,老页面看不见,与老的 { ...process.env } 展开一致);用 insert_or_assign(Windows 上变量名大小写不敏感,同一个变量可能出现两次,后者应覆盖前者);只在 sandboxed 时填。
helper_exec_path 来自 content::CHILD_PROCESS_EXE。macOS 上它指向 Electron Helper.app 里的可执行文件——沙箱渲染进程需要它来拼 process.execPath,因为 argv[0] 拿到的是 helper 而不是主 app。
12.5.6 代码缓存:一个完整的信任链
沙箱路径的 preload 编译一次很贵——它要处理一个可能几千行的脚本,还要建整个 contextBridge 的表。V8 的 code cache 能把"编译"这一步的结果存下来,下次直接 consume。但 V8 的缓存校验有漏洞:
preload_code_cache.h:56-62
// Entries are bound to the source hash: V8's own CachedData source check
// hashes only the source *length*, so without this a same-length source
// change would execute stale bytecode. V8 still validates version/flags at
// consume time.
V8 自带的校验只比对源码长度。 这意味着你把 if (admin) { grant(); } 改成 if (false) { grant(); }——长度完全一样——V8 会认为缓存有效,直接执行旧字节码。这在 Electron 里是安全问题:preload 是特权代码,执行旧的 preload 等于降级到旧版本的权限模型。
Electron 的做法是在三层上加自己的校验:
第一层:浏览器按 (scope, id, 源码哈希) 查缓存。
Scope 有三道隔离:dir 是磁盘分区(每个 BrowserContext 一个),context_id 是 session 身份,process_lock 是渲染进程的安全身份(站点、沙箱状态、存储分区等)。三者都相等才认为缓存可用。
process_lock 这一道的意义:如果不用它,一个无沙箱渲染进程(有完整 Node 权限)产出的字节码可能被一个沙箱渲染进程消费。字节码里有编译期的常量折叠与内联缓存假设,跨安全等级复用是明确不安全的。
第二层:浏览器记录"这一帧我到底发出去什么"。
renderer_startup_data.cc:186-190
// Remember exactly what was served to this frame; SetPreloadCodeCache()
// only accepts cache writes that match this record, so the renderer never
// gets to pick the source a cache entry is validated against.
if (sandboxed)
preload_code_cache::RecordServedPreloads(rfh, std::move(served));
served 是 (id, sha256) 的列表,在 ReadPreloadScript 里填(:101-108)。当渲染进程事后回传一份新产出的缓存时(下一节讲),浏览器拿它的 (id, hash) 去这份记录里比对——对不上就丢弃。
这条防线的攻击模型很明确:如果一个被攻破的渲染进程能自由决定"这份缓存是针对哪份源码的",它就能把一份恶意字节码绑定到一份合法的 preload 源码上,然后让后续所有同 scope 的渲染进程执行它。记录 served 之后,渲染进程只能说"我给这份你刚发给我的、哈希是 X 的源码生成了缓存",别的都说不了。
第三层:参数名写进源码尾部注释。
preload_utils.cc:146-153
// V8 validates a code cache against the source but not against the
// parameter names. Name the parameters in a trailing comment so a persisted
// cache made for a different parameter list (an older Electron with the same
// V8) is rejected and rebuilt rather than run against this one.
body = v8::String::Concat(
isolate, body,
gin::StringToV8(isolate, "\n//# electronPreloadParameters=" +
base::JoinString(param_name_strings, ",")));
V8 的缓存校验只覆盖源码正文。而 Electron 是用 CompileFunction 编译 preload 的,参数名(require, process, exports, module, global)是编译的输入之一,不在正文里。如果 Electron 改了参数列表(比如某版本加了第六个参数),旧缓存会被认为有效,然后 preload 拿到一个参数位置全错的函数。
解法很土但很有效:把参数名拼成注释粘到源码末尾,让源码哈希随之改变。//# 是 Chrome 的 sourceURL 风格注释前缀,不会影响执行。
这三层加起来,才让"preload 的代码缓存"这个东西可以被安全地持久化到 userData/Code Cache/electron-preload/。
12.6 非沙箱路径:Node.js 就是 preload 的运行器
现在数据已经在渲染进程手里了。接下来的问题是"怎么用"。先看有 Node 的那条路径。
12.6.1 DidCreateScriptContext 的十四个动作
ElectronRendererClient::DidCreateScriptContext(electron_renderer_client.cc:120-215)是一个将近一百行的函数,是整个非沙箱初始化的全部。逐步看。
void ElectronRendererClient::DidCreateScriptContext(
v8::Isolate* const isolate,
v8::Local<v8::Context> renderer_context,
content::RenderFrame* render_frame) {
RendererClientBase::DidCreateScriptContext(isolate, renderer_context,
render_frame);
动作 1:基类调用。 基类版本(renderer_client_base.cc:415-420)只做一件事:RegisterOomStackTraceCallback(isolate)。它把 OOM 时的栈回溯钩子挂到 isolate 上,这样渲染进程 OOM 崩溃时能看到 JS 栈。
动作 2:ShouldLoadPreload 判定。
renderer_client_base.cc:251-252
return (is_main_frame || is_devtools || allow_node_in_sub_frames) &&
!IsWebViewFrame(isolate, context, render_frame);
前半句是"该不该有 Node",后半句是"这个 frame 是不是 <webview>"(renderer_client_base.cc:241-253)。
IsWebViewFrame(:676-694)不查任何 C++ 标记,而是去读子 frame 的 window.frameElement,看那个元素上有没有 JS 隐藏属性 isWebView——这个属性是 SetIsWebView(:141-144)往元素对象上打的。
原因很简单:<webview> 是用户态的自定义元素,浏览器进程并不认为它是特殊的 frame 类型,它就是一个普通的跨进程 iframe。只有渲染进程里的 JS bundle 知道自己造了这么个东西,所以也只有 JS 层能识别。代价是这个判断是"软的":页面只要在自己的 iframe 元素上打一个同名隐藏属性,那个 iframe 就被认为"不该加载 Node"。方向上只会更少权限,危害为零,但值得知道。
动作 3:一次性初始化 Node。
electron_renderer_client.cc:135-139
if (!node_integration_initialized_) {
node_integration_initialized_ = true;
node_bindings_->Initialize(isolate, renderer_context);
node_bindings_->SetUpIsolate(isolate);
blink::WasmResponseExtensions::Initialize(isolate);
}
node_integration_initialized_ 是 ElectronRendererClient 的成员,一个进程只有一个实例,所以这三行只在进程里第一个 script context 上跑。
第三行是必要的补丁:
// SetUpIsolate registers Node's WebAssembly streaming callback, whose JS
// side kNoBrowserGlobals never installs; put Blink's back.
blink::WasmResponseExtensions::Initialize(isolate);
Node 在 SetUpIsolate 里会注册一个 WebAssembly 流式编译的回调(WebAssembly.compileStreaming 要用),但它假设宿主是一个完整 Blink 环境,而它注册的版本对应的 JS 侧在 kNoBrowserGlobals 模式下不会被安装。结果就是 Node 的回调盖掉了 Blink 的回调,compileStreaming 崩。所以要把 Blink 的版本装回去。
这是"两个 V8 使用者共用一个 isolate"必然要付的代价:同一个回调槽,谁后装谁生效,必须手工排序。
动作 4:一帧一环境的不变式。
electron_renderer_client.cc:144-147
CHECK(!environments_.contains(render_frame));
auto frame_env = std::make_unique<FrameEnvironment>(
render_frame->IsMainFrame(), node_bindings_.get(),
electron_bindings_.get());
environments_ 是 std::map<content::RenderFrame*, std::unique_ptr<FrameEnvironment>>。这个 CHECK 断言"同一个 frame 不会初始化两次"——如果 Blink 因为某种原因对同一个 frame 调了两次 DidCreateScriptContext(导航到同文档、或 context 被重建),这里会直接崩。用 CHECK 而不是"覆盖旧的",是因为覆盖会静默泄漏一个 Node 环境(它的 uv loop、它的定时器、它的 require 缓存),比崩更难查。
动作 5:记录 world。这是整章最容易被忽略的一行。
electron_renderer_client.cc:148-149
frame_env->world_id =
render_frame->GetWebFrame()->GetScriptContextWorldId(renderer_context);
GetScriptContextWorldId 问 Blink:"这个 v8::Context 属于哪个 world?"答案可能是 0(main world,contextIsolation: false)或 999(isolated world,contextIsolation: true)。
为什么要在这里记?因为过一会儿就问不出来了。注释说得很准:The world of |environment|'s context, recorded while Blink can still map the context to its frame. 一旦 Node 环境建起来,这个 v8::Context 就被 Node 接管了一部分,Blink 的 context→frame 映射在某些销毁路径上会先失效。
后面 ShouldNotifyClient(electron_render_frame_observer.cc:223-245)会用到它:
if (std::optional<int> env_world_id =
renderer_client_->GetEnvironmentWorldId(render_frame_))
return *env_world_id == world_id;
含义是:一旦这个 frame 有了 Node 环境,那么只有"环境所在的那个 world"的事件才通知客户端,别的 world 一概不理。 这是一个非常强的规则,它保证了 WillReleaseScriptContext 不会漏掉、DidCreateScriptContext 不会重复建环境。
注释解释了不用"当前 WebPreferences"来判断的原因:
// Once this frame has a Node.js environment, only the world of its context
// is notified. Choosing from the current WebPreferences instead would create
// a second environment, or skip the release of the first, when they change.
WebPreferences 是可以在导航之间变的。如果 frame 第一次导航时 contextIsolation: false(环境在 world 0),第二次导航时页面改了偏好变成 true(新 context 在 world 999),按偏好判断就会在 world 999 上再建一个环境,而 world 0 的那个永远不会被释放。
动作 6:FrameEnvironment 的 uv loop 归属。
FrameEnvironment 的构造函数(electron_renderer_client.cc:36-50)分两支:主 frame 且 primary 的 uv env 还空着时借用进程级的 node_bindings_(它绑的是 uv_default_loop()),其他情况新建一套 NodeBindings + ElectronBindings,loop 参数传 nullptr 表示"自己建一个线程本地的 loop"。
主 frame 必须用 uv_default_loop(),因为 Chromium 渲染进程的主线程就是 Blink 主线程,而 uv_default_loop() 一旦初始化就固定绑定这个线程——否则会有两个 loop 争同一线程。子 frame(nodeIntegrationInSubFrames: true 时)也跑在同一线程上,但 node::Environment 假定"一 env 一 loop",共用会让 uv_run 的回调跑进错误的 env,所以给每个子 frame 一个独立的 loop 对象(仍在同线程,但状态分开)。
动作 7-8:初始化 context 并暂停文档解析。
electron_renderer_client.cc:153-156
v8::Maybe<bool> initialized = node::InitializeContext(renderer_context);
CHECK(!initialized.IsNothing() && initialized.FromJust());
// Before we load the node environment, let's tell blink to hold off on
// loading the body of this frame. We will undefer the load once the preload
// script has finished. This allows our preload script to run async (E.g.
// with ESM) without the preload being in a race
render_frame->GetWebFrame()->GetDocumentLoader()->SetDefersLoading(
blink::LoaderFreezeMode::kStrict);
SetDefersLoading(kStrict) 是整段代码里最关键的一步。它的含义是:这个 frame 的文档加载器现在暂停了,网络响应会到达但不会被解析、不会被交给 HTML 解析器。
为什么必须暂停?因为 preload 可能是 ESM 的(.mjs),而 ESM 的加载是异步的:import 语句要经过模块解析、抓取、实例化、求值几个阶段,中间会让出事件循环。如果不暂停文档解析,HTML 解析器会继续往下跑,<script> 会执行,页面的脚本可能在 preload 还没跑完的时候就开始跑了。
那 preload 的意义就没了:preload 的职责是"在页面脚本之前准备环境",如果页面脚本先跑,环境还没准备好。
动作 9:建环境,并挂上"恢复加载"的回调。
electron_renderer_client.cc:163-166
std::shared_ptr<node::Environment> env = node_bindings->CreateEnvironment(
isolate, renderer_context, nullptr, 0,
base::BindRepeating(&ElectronRendererClient::UndeferLoad,
base::Unretained(this), render_frame));
第五个参数是 on_ready 回调,Node 在环境 bootstrap 完成时调它。UndeferLoad(:115-118):
electron_renderer_client.cc:115-117
void ElectronRendererClient::UndeferLoad(content::RenderFrame* render_frame) {
render_frame->GetWebFrame()->GetDocumentLoader()->SetDefersLoading(
blink::LoaderFreezeMode::kNone);
}
注意这个回调的时机:不是"preload 跑完",而是"Node 环境 bootstrap 完"。所以 ESM preload 的异步性不是靠这个回调兜住的——是靠 LoaderFreezeMode::kStrict 本身。kStrict 会让文档加载器在 JS 执行期间一直保持暂停状态,直到有代码显式解除。解除发生在哪里?
在 lib/renderer/init.ts 的末尾——onPreloadsLoaded() 里调 appCodeLoaded()。appCodeLoaded 是 node::Environment 提供的一个回调,调它就等于"我的应用代码加载完了",Node 会继续走 bootstrap 的后续步骤,最终触发 on_ready → UndeferLoad。
于是整条链是:
SetDefersLoading(kStrict)
↓
CreateEnvironment(on_ready = UndeferLoad)
↓
LoadEnvironment(env) ──► 跑 renderer_init bundle(init.ts)
↓
init.ts 同步 load CJS preload / 异步 await ESM preload
↓
onPreloadsLoaded() ──► process.appCodeLoaded()
↓
Node bootstrap 完成 ──► on_ready() ──► SetDefersLoading(kNone)
↓
HTML 解析器继续
这就是"preload 一定在页面脚本之前跑完"的物理保证。 它不是靠约定,是靠文档加载器被停住。
动作 10:两个选项。
electron_renderer_client.cc:172-173
env->options()->force_context_aware = true;
env->options()->unhandled_rejections = "warn-with-error-code";
force_context_aware = true 的注释是 If we have disabled the site instance overrides we should prevent loading any non-context aware native module.。翻译一下:Electron 关闭了 Chromium 的 SiteInstance 覆写(因为它要自己控制进程分配),于是原生模块的"进程级缓存"假设不再成立——同一个进程里可能有多个不同 origin 的 frame。非 context-aware 的 native module 会把状态存在进程级静态变量里,跨 origin 泄漏。强制 context-aware 让每个 node::Environment 有独立的模块实例。
unhandled_rejections = "warn-with-error-code" 让未处理的 Promise rejection 打警告但不崩溃。Node 的默认行为(从 15 起)是 throw,会杀掉进程。渲染进程被一个未处理的 rejection 杀掉,用户看到的是白屏 + 一次崩溃上报,非常难查。所以 Electron 改成 warn-with-error-code:打警告,设置退出码,但活着。
动作 11-12:绑定 Electron API 与 process.preloadPaths。
electron_renderer_client.cc:178-180
frame_env->electron_bindings->BindTo(env->isolate(), env->process_object());
gin_helper::Dictionary process_dict(env->isolate(), env->process_object());
BindProcess(env->isolate(), &process_dict, render_frame);
BindProcess(renderer_client_base.cc:229-239)加三个只读属性:
void RendererClientBase::BindProcess(v8::Isolate* isolate,
gin_helper::Dictionary* process,
content::RenderFrame* render_frame) {
auto context_id =
absl::StrFormat("%s-%" PRId64, renderer_client_id_, ++next_context_id_);
process->SetReadOnly("isMainFrame", render_frame->IsMainFrame());
process->SetReadOnly("contextIsolated",
render_frame->GetBlinkPreferences().context_isolation);
process->SetReadOnly("contextId", context_id);
}
contextId 的格式是 <渲染进程 ID>-<进程内自增计数>。自增计数是 RendererClientBase 的成员,所以同一个渲染进程里每个 frame 拿到不同的数字。这个字段是给"区分同一个进程里的多个 frame"用的——process.pid 不够,因为子 frame 共享 pid。
然后:
{
v8::LocalVector<v8::Value> preload_paths(isolate);
if (auto* api_service = ElectronApiServiceImpl::Get(render_frame)) {
if (const auto& data = api_service->startup_data()) {
for (const auto& script : data->preload_scripts)
preload_paths.push_back(gin::StringToV8(isolate, script->file_path));
}
}
process_dict.SetHidden(
"preloadPaths",
v8::Array::New(isolate, preload_paths.data(), preload_paths.size()));
}
启动数据在这里被取出来,但只取 file_path。这与 12.5.4 讲的 read_contents=false 严丝合缝:非沙箱路径的数据里本来就只有路径。
SetHidden("preloadPaths") 而不是 Set,是为了不污染 process 的可枚举属性——Object.keys(process) 里不应该出现一个内部字段。JS 侧用 v8Util.getHiddenValue(process, 'preloadPaths') 读回来(lib/renderer/init.ts:152)。
动作 13:LoadEnvironment → 进入 JS。
base::WeakPtr<FrameEnvironment> weak_frame_env =
frame_env->weak_factory.GetWeakPtr();
environments_[render_frame] = std::move(frame_env);
node_bindings->LoadEnvironment(env.get());
注意顺序:先把 frame_env 放进 map,再 LoadEnvironment。 因为 LoadEnvironment 会同步执行整个 renderer_init bundle,而那个 bundle 里的 preload 可能回调到 C++、可能抛异常、可能触发 frame 销毁。如果此时 map 里还没有这个 frame,GetEnvironment(render_frame) 会返回 nullptr,preload 里某些功能会静默失效。
LoadEnvironment(node_bindings.cc:1006-1050)做三件事:
electron::util::FeedEnvironmentCodeCache(env);
node::DebugOptions* const debug_options = env->options()->get_debug_options();
const bool break_first_line = debug_options->break_first_line;
debug_options->break_first_line = false;
const std::string bundle_id =
"internal/electron/js2c/" + std::string(ProcessType()) + "_init";
node::LoadEnvironment(env, [&](const node::StartExecutionCallbackInfo& info) {
...
v8::LocalVector<v8::String> params =
js2c::MakeBundleParams(isolate, js2c::kInitBundleParams);
v8::Local<v8::Value> args[] = {info.process_object, require};
v8::Local<v8::Function> bundle;
if (!electron::util::CompileBundle(context, bundle_id.c_str(), ¶ms)
.ToLocal(&bundle)) {
return v8::MaybeLocal<v8::Value>();
}
return bundle->Call(context, v8::Null(isolate), std::size(args), args);
}, &OnNodePreload);
三件事:
FeedEnvironmentCodeCache。注释解释了它解决的竞态:Node 的BuiltinLoader从构建期的快照缓存启动,但node::Environment的构造函数会把node_mksnapshot嵌进去的同名 bundle 缓存合并覆盖上来。RefreshCodeCache用的是insert_or_assign,所以 Node 版本的条目会把 Electron 版本的挤掉。需要在之后重新灌一遍。--inspect-brk的补偿。 Node 会在 embedder 入口点之前暂停。如果不处理,--inspect-brk会停在一个内部 bundle 的第一行,而不是用户的应用代码。这里临时把break_first_line关掉,等进入 bundle 之后再打开并刷新缓存。bundle_id是拼出来的:"internal/electron/js2c/" + ProcessType() + "_init"。ProcessType()在渲染进程里返回"renderer",所以完整 id 是internal/electron/js2c/renderer_init——对应lib/renderer/init.ts:68编译出来的 bundle。
动作 14:把 loop 交出去。
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(
[](base::WeakPtr<FrameEnvironment> frame_env) {
if (!frame_env)
return;
frame_env->node_bindings->PrepareEmbedThread();
frame_env->node_bindings->StartPolling();
},
weak_frame_env));
注释:This context may have been created from inside a script (e.g. the opener's window.open() call), so give the loop its first run from a fresh task.
如果是 window.open() 触发的,我们现在还在页面脚本的执行栈里。如果此时直接启动 uv loop 的轮询,就会出现"在 JS 执行中途重入事件循环"——Node 的微任务队列会跑、定时器会触发、IPC 回调会执行,全都叠在页面脚本的调用栈上面。用 PostTask 推迟一个任务,等到脚本返回、消息循环回到顶层再启动。
weak_frame_env 用来防御"这个 frame 在我跑之前就没了"。
12.6.2 反向流程:WillReleaseScriptContext 的七步
electron_renderer_client.cc:217-237
void ElectronRendererClient::WillReleaseScriptContext(
v8::Isolate* const isolate,
v8::Local<v8::Context> context,
content::RenderFrame* render_frame) {
node::Environment* env = GetEnvironment(render_frame);
if (!env || env->context() != context)
return;
gin_helper::EmitEvent(isolate, env->process_object(), "exit");
auto iter = environments_.find(render_frame);
std::unique_ptr<FrameEnvironment> frame_env = std::move(iter->second);
environments_.erase(iter);
// Park the embed thread so FreeEnvironment's uv_run is the loop's only user.
frame_env->node_bindings->set_uv_env(nullptr);
frame_env->node_bindings->StopPolling();
frame_env->electron_bindings->EnvironmentDestroyed(env);
// Freeing the environment runs its loop, i.e. enters Node.js.
util::ExplicitMicrotasksScope microtasks_scope(context->GetMicrotaskQueue());
frame_env->environment.reset();
}
七个动作:env->context() != context 直接 return(同一 frame 可能有多个 context,只有拥有环境的那个才处理);发 exit 事件给 preload 收尾;把 frame_env 从 map 里 std::move 出来并 erase(后续回调即使重入 GetEnvironment 也不会拿到正在销毁的环境);set_uv_env(nullptr) 把嵌入线程停住,让 FreeEnvironment 的 uv_run 成为 loop 的唯一使用者;StopPolling();EnvironmentDestroyed(env) 让 ElectronBindings 清掉挂在环境上的东西;最后 ExplicitMicrotasksScope + environment.reset()。
FreeEnvironment 跑 loop 这件事值得强调:它是"销毁一个 Node 环境"的隐藏成本。如果环境里有一个永远不结束的 setInterval,这里会卡住——不是因为 interval 本身(它会被清理),而是因为清理过程中触发的一连串回调。
12.6.3 lib/renderer/init.ts:Node 侧的七个动作
C++ 侧走完 LoadEnvironment 之后,控制权就交给 JS 了。lib/renderer/init.ts:7-13(180 行)是这个 bundle 的全部。
动作 1:堵住 vm 模块。
const Module = require('module') as NodeJS.ModuleInternal;
// We do not want to allow use of the VM module in the renderer process as
// it conflicts with Blink's V8::Context internal logic.
const originalModuleLoad = Module._load;
Module._load = function (request: string) {
if (request === 'vm') {
console.warn(
"The vm module of Node.js is unsupported in Electron's renderer process due to incompatibilities with the Blink rendering engine. Crashes are likely and avoiding the module is highly recommended. This module may be removed in a future release."
);
}
return originalModuleLoad.apply(this, arguments as any);
};
只警告不拦截。这是一个折中:vm 模块在渲染进程里真的会崩(它创建的 v8::Context 不在 Blink 的 world 表里,GC 和 document 访问都会出问题),但直接 throw 会破坏太多现有代码。
动作 2:改写 Module.wrapper,让 preload 拿到八个参数。
Module.wrapper = [
'(function (exports, require, module, __filename, __dirname, process, global, Buffer) { ' +
'return function (exports, require, module, __filename, __dirname) { ',
'\n}.call(this, exports, require, module, __filename, __dirname); });'
];
这是整份文件里最精妙的一段。Node 的模块包装默认是:
(function (exports, require, module, __filename, __dirname) { ... })
但 preload 需要 process、global、Buffer 三个在模块作用域里可写的变量——因为用户代码可能写 process = something,而在严格模式下这会抛错,非严格模式下会创建一个局部变量遮蔽全局。Electron 的语义是:preload 里的 process 就是那个全局 process,不能被局部遮蔽。
所以包装变成两层:
(function (exports, require, module, __filename, __dirname, process, global, Buffer) {
return function (exports, require, module, __filename, __dirname) {
<用户代码>
}.call(this, exports, require, module, __filename, __dirname);
});
外层函数接收八个参数(其中 process/global/Buffer 是注入的),内层只接收五个标准参数,然后用 .call(this, ...) 显式把五个参数传进去。这样内层的参数列表里没有 process,用户代码里写 process = x 时会去找外层作用域的 process 并赋值——外层是函数作用域,赋值只影响这一次调用,不污染全局也不抛错。
注释里还有一句关键警告:Node 后来加了一条 C++ 侧的快速包装路径,不走 Module.wrapper,但那条路径只在 Module.wrapper 是默认值时才启用——改了它就退回 JS 路径。这是一个靠"检测默认值"实现的开关。
动作 3:加载共享初始化。
require('@electron/internal/common/init');
动作 4:补 getProcessMemoryInfo。
process.getProcessMemoryInfo = () => {
return ipcRendererInternal.invoke<Electron.ProcessMemoryInfo>(IPC_MESSAGES.BROWSER_GET_PROCESS_MEMORY_INFO);
};
这个方法在真 Node 里不存在,是 Electron 加的,且必须走 IPC(内存信息在浏览器侧的 ProcessMetrics 里)。
动作 5:nodeIntegration 分支。
global.module = new Module('internal/electron/js2c/renderer_init');
global.require = makeRequireFunction(global.module) as NodeRequire;
makeRequireFunction 来自 internal/modules/helpers——Node 的公开 API 里没有"造一个 require"的方法,只能借内部实现。这是 Electron 与 Node 内部结构耦合最深的地方之一,每次 Node 大版本升级都要确认这个 import 还在。
随后是 __filename/__dirname 的伪造:file:// 页面下它们就是那个 HTML 文件及其目录(所以 require('./foo') 能工作);非 file:// 页面下是一个不存在的路径(electron.asar/renderer/init.js),纯粹为了兼容那些读 __filename 的库。Windows 网络共享路径还要补 //server 前缀:file://server/share/x.html 解析出来 pathname 是 /share/x.html,少这一段就还原不成 UNC 路径。
动作 6:window.onerror → uncaughtException。
有 uncaughtException 监听器时把页面异常转发给 process,返回 true 阻止默认 console 输出;没有监听器时返回 false 让 Blink 按默认方式报错。这让"页面里的未捕获异常"能被 Node 那套错误上报接住——很多老应用依赖这条路径。
动作 7:preload 分流与全局清理。
const shouldDeleteRendererNodeGlobals = !nodeIntegration && !process.contextIsolated;
const { appCodeLoaded } = process;
delete process.appCodeLoaded;
const onPreloadsLoaded = () => {
if (shouldDeleteRendererNodeGlobals) {
delete (global as any).process;
delete (global as any).Buffer;
delete (global as any).setImmediate;
delete (global as any).clearImmediate;
delete (global as any).global;
delete (global as any).root;
delete (global as any).GLOBAL;
}
appCodeLoaded!();
};
这个 shouldDeleteRendererNodeGlobals 是本章最值得反复读的一段。它处理的是"nodeIntegration: false 但 sandbox: false"这一格——进程里有 Node,但页面不该看见。
问题在于:preload 需要 process,页面不需要。 两者共享同一个 main world(如果 contextIsolation: false)。所以只能在 preload 跑完之后把全局删掉。
删的时机是历史 bug 的产物:
// In a non context-isolated renderer without Node integration, the Node
// globals (process, Buffer, ...) must be removed from the renderer's main
// world before the page's own scripts run, but only after the preload
// scripts have had a chance to use them. The 'loaded' event fires on the
// next tick after init returns, which is before any async ESM preload
// finishes executing, leaving its code with no `process` (#46142). So we
// instead schedule the deletion explicitly once preloads are loaded.
原来是在 loaded 事件里删的。loaded 是 process 上的一个事件,在 init 返回后的下一个 tick 触发。但 ESM preload 是异步的,await import(...) 过程中会让出事件循环,于是 loaded 先触发了,process 被删了,ESM preload 的后续代码执行时 process 就没了——issue #46142。
修法是把删除动作绑到"所有 preload 都跑完"这个真实信号上,而不是"init 返回了"这个近似信号。
动作 8:preload 分流执行。
const preloadPaths: string[] = v8Util.getHiddenValue(process, 'preloadPaths') ?? [];
const cjsPreloads = preloadPaths.filter((p) => path.extname(p) !== '.mjs');
const esmPreloads = preloadPaths.filter((p) => path.extname(p) === '.mjs');
if (cjsPreloads.length) {
for (const preloadScript of cjsPreloads) {
try {
Module._load(preloadScript);
} catch (error) {
console.error(`Unable to load preload script: ${preloadScript}`);
console.error(error);
ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, preloadScript, error);
}
}
}
if (esmPreloads.length) {
const { runEntryPointWithESMLoader } =
require('internal/modules/run_main') as typeof import('@node/lib/internal/modules/run_main');
runEntryPointWithESMLoader(async (cascadedLoader: any) => {
for (const preloadScript of esmPreloads) {
await cascadedLoader
.import(pathToFileURL(preloadScript).toString(), undefined, Object.create(null))
.catch((err: Error) => { ... });
}
}).finally(onPreloadsLoaded);
} else {
onPreloadsLoaded();
}
四个细节:
- 按扩展名分流,不按内容。
.mjs走 ESM,其他都走 CJS。没有自动探测,因为探测需要读文件内容(可能不合法)且代价高。 - CJS 全跑完才开始 ESM。 所以同时注册
a.js和b.mjs时,a.js一定先执行,即使注册顺序相反——一个顺序反转的陷阱。 - 每个 ESM preload 是独立
import。 所以它们之间不共享模块图(Object.create(null)作为 import attributes,避免属性继承)。 runEntryPointWithESMLoader是 Node 的内部 API,用来在已有环境里跑 ESM 入口。同上,属于与 Node 内部结构的耦合点。
BROWSER_PRELOAD_ERROR 这条 IPC 最终会变成浏览器侧的 preload-error 事件,参数是 (event, preloadPath, error)。
12.7 沙箱路径:一个没有 Node 的 preload 环境
同样的数据,完全不同的执行方式。
12.7.1 DidCreateScriptContext 的六个动作
electron_sandboxed_renderer_client.cc:98-147
void ElectronSandboxedRendererClient::DidCreateScriptContext(
v8::Isolate* const isolate,
v8::Local<v8::Context> context,
content::RenderFrame* render_frame) {
RendererClientBase::DidCreateScriptContext(isolate, context, render_frame);
if (!ShouldLoadPreload(isolate, context, render_frame) ||
!HasScriptsToInject(render_frame)) {
return;
}
injected_frames_.insert(render_frame);
v8::HandleScope handle_scope{isolate};
v8::Context::Scope context_scope{context};
// Create ipcRenderer up front so that messages from the browser have
// somewhere to go before a preload script asks for it.
preload_utils::GetBinding(isolate,
gin::StringToV8(isolate, "electron_renderer_ipc"));
const blink::web_pref::WebPreferences& prefs =
render_frame->GetBlinkPreferences();
if (prefs.webview_tag && render_frame->IsMainFrame()) {
auto binding = gin_helper::Dictionary::CreateEmpty(isolate);
binding.SetMethod<&preload_utils::GetBinding>("get");
binding.Set("contextIsolated", prefs.context_isolation);
v8::LocalVector<v8::String> params =
js2c::MakeBundleParams(isolate, js2c::kWebViewBundleParams);
v8::LocalVector<v8::Value> args(isolate, {binding.GetHandle()});
util::CompileAndCall(isolate, context, js2c::kWebViewBundleId, ¶ms, &args);
}
auto* api_service = ElectronApiServiceImpl::Get(render_frame);
if (api_service && api_service->startup_data() &&
!api_service->startup_data()->preload_scripts.empty()) {
SetUpPreloadEnvironment(isolate, context, render_frame,
api_service->startup_data());
}
preload_environment::EmitProcessEvent(context, "loaded");
}
六个动作,其中三个和 Node 路径完全不同:
其一:额外的 HasScriptsToInject 门。
bool ElectronSandboxedRendererClient::HasScriptsToInject(
content::RenderFrame* render_frame) const {
// The <webview> element is implemented by the bundle in the embedder.
if (render_frame->GetBlinkPreferences().webview_tag)
return true;
auto* api_service = ElectronApiServiceImpl::Get(render_frame);
return api_service && api_service->startup_data() &&
!api_service->startup_data()->preload_scripts.empty();
}
非沙箱路径的 HasScriptsToInject 恒返回 true(renderer_client_base.cc:422-425),因为那条路径下"有 Node 环境"本身就是目的——即使没有 preload,nodeIntegration: true 的页面也要有 require。
沙箱路径没有 Node,所以"要不要干活"完全取决于"有没有东西要注入"。webview_tag 单独算一种:<webview> 的实现 bundle 要进 main world,这本身就算"有东西"。
这个判据还被基类的 DidClearWindowObject(renderer_client_base.cc:427-442)使用:
void RendererClientBase::DidClearWindowObject(
content::RenderFrame* render_frame) {
// Blink only creates a document's main-world script context once the page
// runs script. Preload scripts and Node.js have to run even in a document
// with no scripts of its own, so force the context for the frames Electron
// injects into (see ShouldLoadPreload()); leave every other frame alone.
const auto& prefs = render_frame->GetBlinkPreferences();
if ((render_frame->IsMainFrame() || prefs.node_integration_in_sub_frames ||
IsDevTools(render_frame) || IsDevToolsExtension(render_frame)) &&
HasScriptsToInject(render_frame)) {
blink::WebLocalFrame* web_frame = render_frame->GetWebFrame();
v8::HandleScope handle_scope(
web_frame->GetAgentGroupScheduler()->Isolate());
web_frame->MainWorldScriptContext();
}
}
这一段的含义是:Blink 是懒的,如果一个页面没有任何脚本,它就不创建 main world 的 V8 context。 而 Electron 的 preload 必须跑,所以得主动戳一下 MainWorldScriptContext() 把这个 context 逼出来。
注释里的那句"leave every other frame alone"很重要:不满足条件的 frame(比如一个没有 preload 的子 frame)不戳,省掉一个 V8 context。一个页面里可能有几百个 iframe,每个都建 context 是巨大的内存开销。
其二:预创建 ipcRenderer 的 binding。
preload_utils::GetBinding(isolate,
gin::StringToV8(isolate, "electron_renderer_ipc"));
目的写在注释里:so that messages from the browser have somewhere to go before a preload script asks for it。
这条比看起来重要。浏览器可能在 preload 还没跑之前就发 ipc-message(比如主进程在 did-finish-load 之前 webContents.send)。如果 ipcRenderer 的 native binding 还没实例化,那些消息会找不到接收者而被丢弃。先 GetBinding 一次,让 binding 在全局的隐藏缓存里就位,消息就有地方去了。
同样的动作在 common-init.ts 里也有一份(非沙箱路径用的):
// Creates ipcRenderer up front so that messages from the browser have
// somewhere to go before anything imports it.
process._linkedBinding('electron_renderer_ipc');
其三:<webview> bundle 直接编进当前 context。
if (prefs.webview_tag && render_frame->IsMainFrame()) {
auto binding = gin_helper::Dictionary::CreateEmpty(isolate);
binding.SetMethod<&preload_utils::GetBinding>("get");
binding.Set("contextIsolated", prefs.context_isolation);
...
util::CompileAndCall(isolate, context, js2c::kWebViewBundleId, ¶ms, &args);
}
对比非沙箱路径的做法(renderer_client_base.cc:696-737 的 SetupMainWorldOverrides):那边是把 kIsolatedBundleId 编进 main world,并且用 PassValueToOtherContext 把 guestViewInternal 从隔离世界搬过去。这边没有隔离世界可言,直接编进当前 context。
两条路径的分叉在这一个 API 上体现得最清楚:同一个 <webview>,在两种渲染进程里由两个不同的 bundle 实现。
其四:loaded 在这里发。 它在 SetUpPreloadEnvironment 之后,而不是像非沙箱路径那样在"preload 全跑完"之后——因为沙箱路径的 preload 全是同步的(CompileFunction 加直接调用),SetUpPreloadEnvironment 返回时 preload 确实已经跑完了,不存在 #46142 那个竞态。
12.7.2 SetUpPreloadEnvironment:拼一个 process
electron_sandboxed_renderer_client.cc:46-68
void ElectronSandboxedRendererClient::SetUpPreloadEnvironment(
v8::Isolate* isolate,
v8::Local<v8::Context> context,
content::RenderFrame* render_frame,
const mojom::RendererStartupDataPtr& startup_data) {
auto process = gin_helper::Dictionary::CreateEmpty(isolate);
ElectronBindings::BindProcess(isolate, &process, metrics_.get());
BindProcess(isolate, &process, render_frame);
process.SetMethod<&preload_utils::Uptime>("uptime");
process.Set("argv", base::CommandLine::ForCurrentProcess()->argv());
process.Set("pid", base::GetCurrentProcId());
process.Set("sandboxed", true);
process.Set("type", "renderer");
v8::Local<v8::Object> preload_process =
preload_environment::CreateProcessObject(context, process, startup_data);
v8::Local<v8::Object> electron_module =
preload_environment::CreateElectronModule(
context, preload_environment::Flavor::kRenderer);
preload_environment::RunPreloadScripts(
context, render_frame, /*service_worker_data=*/nullptr, preload_process,
electron_module, preload_environment::Flavor::kRenderer, startup_data);
}
三层拼装:ElectronBindings::BindProcess 给公共进程信息(platform、arch、resourcesPath、versions,非沙箱路径里也是这一份);RendererClientBase::BindProcess 给 isMainFrame/contextIsolated/contextId;最后手工补 uptime、argv、pid、sandboxed: true、type: "renderer"。pid 与 argv 可以直接从 C++ 拿——沙箱限制的是系统调用,不是进程自身信息。
metrics_ 在构造函数里建,同一个构造函数里还有一行容易被略过:
// Explicitly register electron's builtin bindings.
NodeBindings::RegisterBuiltinBindings();
沙箱渲染进程没有 Node 运行时,但它链接了 Node 的 binding 注册表。 这就是 process._linkedBinding('electron_renderer_ipc') 能用的原因——binding 的注册是纯静态的,不需要跑 Node 的 bootstrap。
12.7.3 createElectronModule:七个懒加载模块
preload_environment.cc:42-51
constexpr auto kModules = std::to_array<ModuleEntry>({
{"contextBridge", "electron_renderer_context_bridge", "contextBridge", false},
{"crashReporter", "electron_renderer_crash_reporter", nullptr, true},
{"ipcRenderer", "electron_renderer_ipc", "ipcRenderer", false},
{"nativeImage", "electron_common_native_image", "nativeImage", false},
{"sharedTexture", "electron_common_shared_texture", nullptr, true},
{"webFrame", "electron_renderer_web_frame", "mainFrame", true},
{"webUtils", "electron_renderer_web_utils", nullptr, true},
});
四个字段:name(electron 模块上的属性名)、binding(native binding 名)、key(从 binding 的导出里取哪个属性,nullptr 表示导出本身就是模块)、renderer_only(service worker 里是否可用)。
这张表就是"沙箱 preload 能用哪些 API"的完整清单。没有 BrowserWindow、没有 app、没有 shell——因为它们全在主进程。也没有 protocol、net——同理。
注意 webFrame 的 key 是 "mainFrame":electron_renderer_web_frame 这个 binding 的导出是一个对象,里面 mainFrame 才是 webFrame 模块。这是一个历史包袱(早期 webFrame 和 webFrameMain 共用一个 binding)。
sharedTexture 有特例:electron_common_shared_texture 的导出整体作为 subtle,再把 setSharedTextureReceiver 提到同一层,以对齐公开 API 的形状。
懒加载靠 SetLazyDataProperty:属性第一次被读时才调 getter,之后变成普通数据属性。三个好处——省掉不需要的模块(只用 ipcRenderer 的 preload 不会去建 nativeImage 的构造函数模板);属性仍可枚举(Object.keys(require('electron')) 能列出全部七个,而 getter 方案会让它看到访问器属性);ReadOnly | DontDelete(注释说"Read-only like the getter-only accessors these used to be",SetLazyDataProperty 是后来的优化,语义没变)。ModuleGetter 用 info.Data().As<v8::Int32>() 把模块表下标编码进属性回调,七个属性共用一个 getter。
12.7.4 require:一个只有三个合法参数的函数
preload_environment.cc:93-115
void Require(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Array> data = info.Data().As<v8::Array>();
v8::Local<v8::Value> module, renderer_flavor;
if (!data->Get(context, 0).ToLocal(&module) ||
!data->Get(context, 1).ToLocal(&renderer_flavor)) {
return;
}
std::string name;
if (info.Length() > 0) {
v8::Local<v8::String> name_string;
if (info[0]->ToString(context).ToLocal(&name_string))
name = gin::V8ToString(isolate, name_string);
}
if (name == "electron" || name == "electron/common" ||
(renderer_flavor->IsTrue() && name == "electron/renderer")) {
info.GetReturnValue().Set(module);
return;
}
isolate->ThrowException(v8::Exception::Error(
gin::StringToV8(isolate, base::StrCat({"module not found: ", name}))));
}
这是沙箱路径的全部 require。三个合法参数:electron、electron/common、electron/renderer(后者只在 renderer flavor 下)。其他一律 throw new Error("module not found: X")。
注意错误类型是 Error 而不是 MODULE_NOT_FOUND 那个带 code 属性的错误。所以 try { require('fs') } catch (e) { e.code } 拿到的是 undefined。这是一个兼容性坑:很多库会检测 e.code === 'MODULE_NOT_FOUND' 来判断"这个模块不存在,我可以用降级方案",在沙箱 preload 里这个检测会失败,然后错误往上抛。
require 函数的 Data 里塞了一个两元素数组:[module, Boolean(flavor == kRenderer)]。这是为了避免为每个 context 创建闭包——v8::Function::New 的 data 参数让同一个 C++ 回调服务不同的 context。
12.7.5 CreateProcessObject:一个长得像 process 的对象
preload_environment.cc:209-244
v8::Local<v8::Object> CreateProcessObject(
v8::Local<v8::Context> context,
gin_helper::Dictionary base,
const mojom::RendererStartupDataPtr& data) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Object> process = gin_helper::NewNodeEventEmitter(context);
gin_helper::Dictionary dict(isolate, process);
// Object.assign(process, base, data.process)
v8::Local<v8::Object> base_object = base.GetHandle();
v8::Local<v8::Array> keys;
if (base_object->GetOwnPropertyNames(context).ToLocal(&keys)) {
for (uint32_t i = 0; i < keys->Length(); ++i) {
v8::Local<v8::Value> key, value;
if (keys->Get(context, i).ToLocal(&key) &&
base_object->Get(context, key).ToLocal(&value)) {
process->CreateDataProperty(context, key.As<v8::Name>(), value).Check();
}
}
}
preload_utils::SetProcessProperties(isolate, &dict, data);
dict.Set("getProcessMemoryInfo",
v8::Function::New(context, GetProcessMemoryInfo, {}, 0,
v8::ConstructorBehavior::kThrow)
.ToLocalChecked());
// Like Node.js's --expose-internals: lets the tests reach internal bindings.
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
"unsafely-expose-electron-internals-for-testing")) {
dict.SetMethod<&preload_utils::GetBinding>("_linkedBinding");
}
gin_helper::Dictionary(isolate, context->Global())
.SetHidden(kProcessKey, process.As<v8::Value>());
return process;
}
五个要点:
其一,NewNodeEventEmitter。 这个 process 必须是一个 EventEmitter——process.on('document-start') 要用。gin_helper::NewNodeEventEmitter 从 Node 的 JS 侧拿 EventEmitter 构造函数(Node 已经 bootstrap 过,即使在沙箱进程里 Node 的 JS 内置模块也是可用的,只是没有 require 暴露给用户)。
其二,手写 Object.assign。 为什么不直接 v8::Object::Assign?因为 CreateDataProperty 建的是数据属性,而普通赋值会触发 setter。base 里的 process 是个 gin_helper::Dictionary,如果它的原型链上有 setter,普通赋值会跑进去。用 CreateDataProperty 绕过一切属性描述符。
其三,SetProcessProperties。
preload_utils.cc:256-270
void SetProcessProperties(v8::Isolate* isolate,
gin_helper::Dictionary* process,
const mojom::RendererStartupDataPtr& data) {
process->Set("arch", node::per_process::metadata.arch);
process->Set("platform", node::per_process::metadata.platform);
process->Set("version", "v" + node::per_process::metadata.versions.node);
process->Set("versions", BuildVersions(isolate));
auto env = gin_helper::Dictionary::CreateEmpty(isolate);
if (data) {
for (const auto& [k, v] : data->environment)
env.Set(k, v);
}
process->Set("env", env);
process->Set("execPath", data ? data->helper_exec_path : std::string());
}
node::per_process::metadata 是 Node 的静态元数据表——它不需要 node::Environment 就能读。所以沙箱进程能报告准确的 process.version、process.arch、process.platform,即使它没跑 Node。
process.env 来自启动数据里那份快照(12.5.5)。process.execPath 来自 helper_exec_path。
BuildVersions(:219-252)特别值得看:
// Builds process.versions from per-process metadata — no node::Environment
// needed. cldr/tz are runtime ICU state; the sandboxed renderer doesn't run
// Node bootstrap (which would call InitializeIntlVersions()), so compute them
// from the renderer's own ICU.
v8::Local<v8::Value> BuildVersions(v8::Isolate* isolate) {
static base::NoDestructor<std::string> cldr_version([] {
UErrorCode status = U_ZERO_ERROR;
UVersionInfo version_array;
char buf[U_MAX_VERSION_STRING_LENGTH] = {0};
ulocdata_getCLDRVersion(version_array, &status);
if (U_SUCCESS(status))
u_versionToString(version_array, buf);
return std::string(buf);
}());
static base::NoDestructor<std::string> tz_version([] {
UErrorCode status = U_ZERO_ERROR;
const char* tz = icu::TimeZone::getTZDataVersion(status);
return U_SUCCESS(status) && tz ? std::string(tz) : std::string();
}());
...
process.versions.cldr 和 process.versions.tz 在真 Node 里是 InitializeIntlVersions() 填的,而那个函数在 node::Environment bootstrap 里调。沙箱进程没有 bootstrap,所以这两个值得直接从 ICU 现算。为了让 process.versions 完整,Electron 在这里直接调了 ICU 的 C API。
base::NoDestructor + 静态 lambda:只算一次,永不析构。这是 Chromium 里"进程级不可变缓存"的标准写法——避免静态初始化顺序问题和退出时的析构顺序问题。
其四,getProcessMemoryInfo 与 _linkedBinding。
前者返回 ipcRendererInternal.invoke('BROWSER_GET_PROCESS_MEMORY_INFO') 的 Promise(内存信息在浏览器侧的 ProcessMetrics 里,渲染进程自己拿不到)。后者只在 --unsafely-expose-electron-internals-for-testing 时挂上,暴露完整的 native binding 注册表给测试用。
其五,hidden key。
constexpr std::string_view kProcessKey = "electron:preload-process";
拼装好的 process 被挂到全局的隐藏属性上,键名就是这个常量。这是为了让 EmitProcessEvent(:300-308)在任何时刻都能把它找回来。注意它不是全局的 process——沙箱路径里 global.process 可能压根不存在。require('electron') 的返回值、preload 的 process 参数、全局隐藏属性三者是同一个对象,但只有隐藏属性是可靠可达的。
12.7.6 RunPreloadScripts:编译、绑定五个参数、调用
preload_environment.cc:246-298
void RunPreloadScripts(v8::Local<v8::Context> context,
content::RenderFrame* render_frame,
ServiceWorkerData* service_worker_data,
v8::Local<v8::Object> process,
v8::Local<v8::Object> electron_module,
Flavor flavor,
const mojom::RendererStartupDataPtr& data) {
if (!data)
return;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Value> require_data_items[] = {
electron_module, v8::Boolean::New(isolate, flavor == Flavor::kRenderer)};
v8::Local<v8::Function> require =
v8::Function::New(context, Require,
v8::Array::New(isolate, require_data_items, 2), 1,
v8::ConstructorBehavior::kThrow)
.ToLocalChecked();
require->SetName(gin::StringToSymbol(isolate, "require"));
const std::vector<std::string> parameters = {"require", "process", "exports",
"module", "global"};
for (const auto& script : data->preload_scripts) {
v8::TryCatch try_catch(isolate);
if (script->error) {
ReportPreloadError(
context, script->file_path,
v8::Exception::Error(gin::StringToV8(isolate, *script->error)));
continue;
}
if (base::span<const uint8_t>(script->contents).empty())
continue;
v8::Local<v8::Value> fn = preload_utils::CreatePreloadScript(
render_frame, service_worker_data, isolate, script->id, parameters);
if (fn.IsEmpty() || !fn->IsFunction()) {
if (try_catch.HasCaught())
ReportPreloadError(context, script->file_path, try_catch.Exception());
continue;
}
v8::Local<v8::Object> exports = v8::Object::New(isolate);
auto module = gin_helper::Dictionary::CreateEmpty(isolate);
module.Set("exports", exports);
v8::Local<v8::Value> args[] = {require, process, exports,
module.GetHandle(), context->Global()};
if (fn.As<v8::Function>()
->Call(context, v8::Undefined(isolate), std::size(args), args)
.IsEmpty() &&
try_catch.HasCaught() && !try_catch.HasTerminated()) {
ReportPreloadError(context, script->file_path, try_catch.Exception());
}
}
}
五个参数:require、process、exports、module、global。对比 Node 路径的八个(exports, require, module, __filename, __dirname, process, global, Buffer)——沙箱路径没有 __filename、__dirname、Buffer。
没有 Buffer 是个硬限制:沙箱 preload 里不能用 Buffer.from(...)。要处理二进制得用 Uint8Array 或 ArrayBuffer。
exports 和 module 每个脚本新建一份,所以 preload 之间不共享模块状态。
错误处理有四条独立路径:script->error 有值(浏览器侧读文件失败)直接报并跳过;contents 为空静默跳过(空文件的正常情况);编译返回空且 try_catch 抓到异常则报;调用返回空且 try_catch 抓到且未被 terminated 则报。最后一个条件里的 HasTerminated() 检查很关键——terminated 意味着脚本被 TerminateExecution() 强制中断(导航走了、用户点了停止),这种情况下抛的异常没有意义,报出来只是噪音。
ReportPreloadError(:173-187):
void ReportPreloadError(v8::Local<v8::Context> context,
const std::string& file_path,
v8::Local<v8::Value> error) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::TryCatch try_catch(isolate);
std::array<v8::Local<v8::Value>, 1> message{gin::StringToV8(
isolate, base::StrCat({"Unable to load preload script: ", file_path}))};
ConsoleError(context, message);
std::array<v8::Local<v8::Value>, 1> error_arg{error};
ConsoleError(context, error_arg);
std::array<v8::Local<v8::Value>, 3> ipc_args{
gin::StringToV8(isolate, "BROWSER_PRELOAD_ERROR"),
gin::StringToV8(isolate, file_path), error};
std::ignore = CallIpcRendererInternal(isolate, "send", ipc_args);
}
三件事:打两行 console.error(与 Node 路径的文案完全一致,这是刻意的)、再发一条 IPC 让浏览器进程也能知道。
外面套一个 v8::TryCatch 是为了防止"报错过程本身出错"(比如 console.error 被页面替换成了一个会抛的函数)。这个 try_catch 被立即丢弃,异常被吞掉——报错时不能再抛错。
12.7.7 代码缓存的生产与回传
回到 preload_utils.cc:138-144 的 CreatePreloadScript(:116-206),这是沙箱路径真正编译 preload 的地方:
base::span<const uint8_t> contents = ps->contents;
v8::Local<v8::String> body;
if (!v8::String::NewFromUtf8(
isolate, reinterpret_cast<const char*>(contents.data()),
v8::NewStringType::kNormal, base::checked_cast<int>(contents.size()))
.ToLocal(&body)) {
return {};
}
NewFromUtf8 是唯一一次"把 native buffer 变成 V8 字符串"的拷贝(注释:only the single NewFromUtf8 copy for the compile touches V8)。
然后拼参数名注释、构造 ScriptOrigin、编译:
v8::ScriptOrigin origin(gin::StringToV8(isolate, ps->file_path));
v8::ScriptCompiler::Source compiler_source(body, origin, cached_data.release());
auto options = had_cache ? v8::ScriptCompiler::kConsumeCodeCache
: v8::ScriptCompiler::kNoCompileOptions;
// CompileFunction() takes the bare body + parameter names — no wrapper
// string, and stack traces get correct line numbers.
v8::Local<v8::Function> fn;
if (!v8::ScriptCompiler::CompileFunction(
context, &compiler_source, param_names.size(), param_names.data(), 0,
nullptr, options)
.ToLocal(&fn)) {
return {};
}
CompileFunction 而不是"拼一个 (function(require, process...){...}) 字符串再 Compile",有两个好处:栈追踪的行号正确(不需要减一),以及参数名是编译器的输入(这样 12.5.6 第三层的注释技巧才有意义)。
编译之后,如果没有可用的缓存,就生产一份并回传:CreateCodeCacheForFunction(fn) 产出的 blob 连同浏览器刚发给我们的那份 contents 的 sha256(不是字节码的哈希)一起通过 SetPreloadCodeCache 送回浏览器,好让它去 RecordServedPreloads 的记录里比对(12.5.6 第二层)。!consumed && render_frame 两个条件缺一不可:没消费成功才生产,有 frame 才回传——service worker 没有回传通道。
回传的 source_hash 是浏览器刚发给我们的那份 contents 的哈希,不是我们编译的字节码的哈希。这样浏览器可以拿它去 RecordServedPreloads 的记录里比对(12.5.6 第二层)。
至此两条路径的全貌都有了。下一节看它们共同面对的问题:world。
12.8 四个 world 与 contextIsolation 的真实机制
12.8.1 world ID 的取值
world_ids.h:13-29
enum WorldIDs : int32_t {
MAIN_WORLD_ID = 0,
// Use a high number far away from 0 to not collide with any other world
// IDs created internally by Chrome.
ISOLATED_WORLD_ID = 999,
// Numbers for isolated worlds for extensions are greater than or equal to
// this number, up to ISOLATED_WORLD_ID_EXTENSIONS_END.
ISOLATED_WORLD_ID_EXTENSIONS = 1 << 20,
// Last valid isolated world ID.
ISOLATED_WORLD_ID_EXTENSIONS_END =
blink::IsolatedWorldId::kEmbedderWorldIdLimit - 1
};
三个数字:0 是 main world,999 是 Electron 的隔离世界,1<<20 到 kEmbedderWorldIdLimit-1 留给扩展。
999 这个数字是"随手挑的高位"——Chrome 内部用的 isolated world id 大多是 1、2、3 这种小数字(内容脚本、密码管理器等),挑 999 是为了不撞车。这是一种约定而非机制,升级 Chromium 时需要人工确认没有新代码占用 999。
第四个 world 在哪里?preload_realm_context.cc:273 用的是 blink::DOMWrapperWorld::WorldType::kShadowRealm,它不是一个数字 id,而是一类独立的 world 类型(service worker 的 preload 用它,机制见第 16 章)。
12.8.2 隔离世界是被"召唤"出来的
关键在 DidInstallConditionalFeatures(electron_render_frame_observer.cc:96-180)。这个方法由 Blink 在每个 world 的 context 安装完条件特性之后调用,参数是那对 (context, world_id)。
对 contextIsolation: true 的主 frame,执行顺序是这样的:
第 1 次进入:world_id = 0(main world 刚建好)
├─ ShouldNotifyClient(0) → false(因为 context_isolation=true 时只认 999)
├─ 跳过 DidCreateScriptContext
└─ should_create_isolated_context = true → CreateIsolatedWorldContext()
└─ ExecuteScriptInIsolatedWorld(999, "void 0")
└─ Blink 创建 world 999 的 context
└─ 第 2 次进入:world_id = 999
├─ ShouldNotifyClient(999) → true
├─ DidCreateScriptContext(999) → 建 Node 环境 / 跑 preload
└─ should_create_isolated_context = false(is_main_world 为假)
也就是说:隔离世界是 main world 的回调里主动创建的,创建动作触发的新一轮回调才真正跑 preload。 两次进入是同一套代码,靠 world_id 区分角色。
void ElectronRenderFrameObserver::CreateIsolatedWorldContext() {
auto* frame = render_frame_->GetWebFrame();
blink::WebIsolatedWorldInfo info;
// This maps to the name shown in the context combo box in the Console tab
// of the dev tools.
info.human_readable_name =
blink::WebString::FromUtf8("Electron Isolated Context");
// Setup document's origin policy in isolated world
info.security_origin = frame->GetDocument().GetSecurityOrigin();
blink::SetIsolatedWorldInfo(WorldIDs::ISOLATED_WORLD_ID, info);
// Create initial script context in isolated world
blink::WebScriptSource source("void 0");
frame->ExecuteScriptInIsolatedWorld(
WorldIDs::ISOLATED_WORLD_ID, source,
blink::BackForwardCacheAware::kPossiblyDisallow);
}
三个细节:
human_readable_name就是 DevTools Console 里那个 world 下拉框显示的文字。调试时看到 "Electron Isolated Context" 就知道你切到了 preload 的世界。security_origin显式设成文档的 origin。 不设的话隔离世界会有一个空的/不透明的 origin,导致fetch全被 CORS 拒、localStorage抛SecurityError。ExecuteScriptInIsolatedWorld("void 0")是纯为了触发创建。 Blink 的 isolated world context 是懒创建的:第一次在这个 world 里执行脚本时才建。执行一个空操作就能把它逼出来。kPossiblyDisallow是说"如果页面进了 BFCache,这个 script 可能被丢弃"——对void 0无所谓。
12.8.3 ShouldNotifyClient:三条规则
这个函数(:223-245)决定了"哪个 world 的事件该通知客户端",是整个 world 机制的调度中心:
bool ElectronRenderFrameObserver::ShouldNotifyClient(int world_id) const {
// Once this frame has a Node.js environment, only the world of its context
// is notified. Choosing from the current WebPreferences instead would create
// a second environment, or skip the release of the first, when they change.
if (std::optional<int> env_world_id =
renderer_client_->GetEnvironmentWorldId(render_frame_))
return *env_world_id == world_id;
const auto& prefs = render_frame_->GetBlinkPreferences();
// about:blank subframes commit synchronously in the renderer and never get
// the browser's preload startup data (see MaybeSendRendererStartupData), so
// they are left without preload scripts and Node.js integration.
if (prefs.node_integration_in_sub_frames && !render_frame_->IsMainFrame() &&
GURL{render_frame_->GetWebFrame()->GetDocument().Url()}.IsAboutBlank())
return false;
if (prefs.context_isolation &&
(render_frame_->IsMainFrame() || prefs.node_integration_in_sub_frames))
return is_isolated_world(world_id);
return is_main_world(world_id);
}
三条规则,优先级从高到低:
规则一(已有环境):只认环境所在的 world。 它的作用是锁定——一旦 preload 在某个 world 里跑起来,那个 world 就是"这个 frame 的 Electron 世界",其他 world 的事件一概不通知。这也是 12.6.1 动作 5 记录 world_id 的唯一用途。
规则二(about:blank 子 frame):谁都不通知。 这类子 frame 在渲染进程里同步提交,永远收不到浏览器推的启动数据。既然没有数据,就不该有 preload 也不该有 Node 环境;返回 true 只会让 preload 空跑一次,反而让人误以为它执行过。
规则三(正常情况):contextIsolation 决定认哪个 world。 条件里的 (IsMainFrame() || node_integration_in_sub_frames) 是必要的:一个 contextIsolation: true 的普通子 frame(没有 nodeIntegrationInSubFrames)不该有 preload,所以不该认 999。这个条件与 ShouldLoadPreload 的前半句完全一致。
注意规则三的返回值是"等于",不是"或"。 context_isolation 为真时,world_id == 999 才返回 true,world_id == 0 返回 false。这意味着 main world 的 DidInstallConditionalFeatures 里 DidCreateScriptContext 不会被调用——正是这一点让 12.8.2 的两阶段顺序成立。
12.8.4 GetContext 的优先级链
renderer_client_base.cc:649-664
v8::Local<v8::Context> RendererClientBase::GetContext(
blink::WebLocalFrame* frame,
v8::Isolate* isolate) const {
auto* render_frame = content::RenderFrame::FromWebFrame(frame);
DCHECK(render_frame);
if (render_frame) {
v8::Local<v8::Context> env_context = GetEnvironmentContext(render_frame);
if (!env_context.IsEmpty())
return env_context;
}
if (render_frame && render_frame->GetBlinkPreferences().context_isolation)
return frame->GetScriptContextFromWorldId(isolate,
WorldIDs::ISOLATED_WORLD_ID);
else
return frame->MainWorldScriptContext();
}
三级:
- Node 环境的 context 优先。
GetEnvironmentContext是虚函数,非沙箱客户端返回env->context()(electron_renderer_client.cc:313-317),沙箱客户端返回空。所以有 Node 时,preload 的 context 就是这个 frame 的"Electron context"。 - 没有 Node 但开了隔离 → 999。
- 否则 → main world。
这个函数被 IsWebViewFrame(:676-694)用来读 window.frameElement——也就是说,判断"是不是 webview"是在 preload 的 context 里做的,而不是 main world。这点很重要:如果 contextIsolation: true,preload 在 999 里读 frameElement,得到的是隔离世界视角的 DOM 包装(同样的元素,不同的 JS wrapper)。隐藏属性 isWebView 是在 main world 打的,跨 world 读得到吗?
严格说读不到:Blink 的 DOM wrapper 是按 world 分别创建的,同一个元素在 world 0 和 999 有两个不同的 JS 对象。所以这个判断在 contextIsolation: true 时可能误判,不致命(<webview> 的 guest 本来就不该有 Node),而且 createGuest 在浏览器侧还有一次权威判定(第 10 章 10.8)。
12.8.5 SetupMainWorldOverrides:为什么 main world 也需要代码
renderer_client_base.cc:696-737
void RendererClientBase::SetupMainWorldOverrides(
v8::Isolate* const isolate,
v8::Local<v8::Context> context,
content::RenderFrame* render_frame) {
auto prefs = render_frame->GetBlinkPreferences();
// We only need to run the isolated bundle if webview is enabled
if (!prefs.webview_tag)
return;
v8::HandleScope handle_scope{isolate};
v8::Context::Scope context_scope{context};
auto isolated_api = gin_helper::Dictionary::CreateEmpty(isolate);
isolated_api.SetMethod<&AllowGuestViewElementDefinition>(
"allowGuestViewElementDefinition");
isolated_api.SetMethod<&SetIsWebView>("setIsWebView");
auto source_context = GetContext(render_frame->GetWebFrame(), isolate);
gin_helper::Dictionary global(isolate, source_context->Global());
v8::Local<v8::Value> guest_view_internal;
if (global.GetHidden("guestViewInternal", &guest_view_internal)) {
auto result = api::PassValueToOtherContext(
isolate, source_context, context, guest_view_internal,
source_context->Global(), false, api::BridgeErrorTarget::kSource);
if (!result.IsEmpty()) {
isolated_api.Set("guestViewInternal", result.ToLocalChecked());
}
}
v8::LocalVector<v8::String> isolated_bundle_params =
js2c::MakeBundleParams(isolate, js2c::kIsolatedBundleParams);
v8::LocalVector<v8::Value> isolated_bundle_args(isolate,
{isolated_api.GetHandle()});
util::CompileAndCall(isolate, context, js2c::kIsolatedBundleId,
&isolated_bundle_params, &isolated_bundle_args);
}
这段代码只在 webview_tag 为真时跑,因为 <webview> 的实现必须住在 main world:customElements.define('webview', ...) 注册的表是 per-window 的,在隔离世界注册的元素页面看不到。
而 main world 里的 bundle 需要一个能访问 C++ 的入口,所以从隔离世界传一个字典过去:allowGuestViewElementDefinition(允许定义嵌入者自定义元素)和 setIsWebView(打隐藏属性)。
第三个参数 guestViewInternal 用 PassValueToOtherContext 搬过去——这是 contextBridge 的底层函数(第 15 章),它在两个 world 之间复制一个值,走完整的"深度克隆 + 代理"流程。最后一个参数 BridgeErrorTarget::kSource 表示"出错时报给源 world 的 console",桥接失败时错误出现在隔离世界,定位时不会找错地方。
AllowGuestViewElementDefinition 需要特殊权限:它先建一个 blink::WebCustomElement::EmbedderNamesAllowedScope(默认情况下 customElements.define('webview') 会被拒,因为 webview 是 embedder 名字,只有在这个 RAII scope 里才允许),再用 RequestExecuteV8Function 把注册回调扔回 Blink 的任务队列执行,避免在 customElements.define 的调用栈里重入。
12.9 两个时序陷阱
12.9.1 window.open() 的子窗口:为什么 Node 初始化要延后
electron_render_frame_observer.cc:120-147
// When a child window is created with window.open, its WebPreferences will
// be copied from its parent, and Chromium will initialize JS context in it
// immediately.
// Normally the WebPreferences is overridden in browser before navigation,
// but this behavior bypasses the browser side navigation and the child
// window will get wrong WebPreferences in the initialization.
// This will end up initializing Node.js in the child window with wrong
// WebPreferences, leads to problem that child window having node integration
// while "nodeIntegration=no" is passed.
// We work around this issue by delaying the child window's initialization of
// Node.js if this is the initial empty document, and only do it when the
// actual page has started to load.
auto* web_frame =
static_cast<blink::WebLocalFrameImpl*>(render_frame_->GetWebFrame());
if (web_frame->Opener() && web_frame->IsOnInitialEmptyDocument()) {
// FIXME(zcbenz): Chromium does not do any browser side navigation for
// window.open('about:blank'), so there is no way to override WebPreferences
// of it. We should not delay Node.js initialization as there will be no
// further loadings.
GURL url = web_frame->GetDocument().Url();
if (!url.IsAboutBlank()) {
has_delayed_node_initialization_ = true;
return;
}
}
has_delayed_node_initialization_ = false;
问题链条:
window.open('https://evil.com')在渲染进程里发起。- Blink 立刻为子窗口创建 frame,并且先把父窗口的
WebPreferences复制过去,然后建 JS context、触发DidInstallConditionalFeatures。 - 与此同时,同步的
CreateNewWindowIPC 才刚发给浏览器;浏览器收到后才算出"这个子窗口该用什么 WebPreferences"(可能是不同 origin 的一套),再从命令行/推送把正确的一套给它。 - 于是第 2 步用的偏好在第 3 步被推翻。如果第 2 步按父窗口的
nodeIntegration: true建了 Node 环境,子窗口就带着一个本该没有的require进去了。
修法:如果是"有 opener + 初始空文档 + 不是 about:blank"这三条同时成立,就先不建 Node 环境,只打个标记。
标记在 DidClearWindowObject 里被消费(:76-94):
void ElectronRenderFrameObserver::DidClearWindowObject() {
// Do a delayed Node.js initialization for child window.
// Check DidInstallConditionalFeatures below for the background.
auto* web_frame =
static_cast<blink::WebLocalFrameImpl*>(render_frame_->GetWebFrame());
if (has_delayed_node_initialization_ &&
!web_frame->IsOnInitialEmptyDocument()) {
v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate();
v8::HandleScope handle_scope{isolate};
v8::Local<v8::Context> context = web_frame->MainWorldScriptContext();
v8::MicrotasksScope microtasks_scope(
context, v8::MicrotasksScope::kDoNotRunMicrotasks);
v8::Context::Scope context_scope(context);
// DidClearWindowObject only emits for the main world.
DidInstallConditionalFeatures(context, MAIN_WORLD_ID);
}
renderer_client_->DidClearWindowObject(render_frame_);
}
IsOnInitialEmptyDocument() 变成假,意味着真正的文档开始加载了,WebPreferences 已经被浏览器改过,此时补上初始化。
为什么排除 about:blank?注释里说得明白:Chromium 对 window.open('about:blank') 根本不做浏览器侧导航,所以永远不会有"偏好被改过来"的时刻。如果也延后,Node 环境就永远不建了——子窗口彻底没有 require。
最后一行 renderer_client_->DidClearWindowObject(...) 是基类的实现(12.7.1 里讲的"戳一下 MainWorldScriptContext"),在延后路径上会被调用两次(一次从 DidInstallConditionalFeatures → DidCreateScriptContext 的链路,一次从 DidClearWindowObject),但基类那个是幂等的(MainWorldScriptContext() 第二次只是取回已有的)。
12.9.2 这个陷阱的一般形式
根源是:WebPreferences 是浏览器侧的概念,渲染进程侧看到的是一份拷贝,而拷贝的时机不由你控制。 render_frame->GetBlinkPreferences() 每次返回当前快照,在 window.open 的子窗口里第一个快照是错的——ShouldNotifyClient 里 prefs.context_isolation 的判断也因此可能读到错值,只是被 has_delayed_node_initialization_ 的提前 return 挡住了。
这就是为什么 ShouldNotifyClient 的第一条规则(已有环境就只认环境所在的 world)如此重要。 它把"偏好在变"的影响范围限制在"第一次建环境之前",一旦环境建了,后续判断只看 world_id,与偏好无关。
12.10 四个生命周期事件
process 上有四个由初始化流程发出的事件。它们在两条路径下的发送机制完全不同,但语义一致。
| 事件 | 时机 | 非沙箱发送点 | 沙箱发送点 |
|---|---|---|---|
document-start | RunScriptsAtDocumentStart | electron_renderer_client.cc:94-95 | electron_sandboxed_renderer_client.cc:89 |
document-end | RunScriptsAtDocumentEnd | :110-112 | :95 |
loaded | preload 全部执行完 | node_bindings.cc:1052 | electron_sandboxed_renderer_client.cc:146 |
exit | context 即将销毁 | electron_renderer_client.cc:224 | :160 |
12.10.1 非沙箱:直接往真 process 上发
void ElectronRendererClient::RunScriptsAtDocumentStart(
content::RenderFrame* render_frame) {
RendererClientBase::RunScriptsAtDocumentStart(render_frame);
// Inform the document start phase.
v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
node::Environment* env = GetEnvironment(render_frame);
if (env) {
v8::Context::Scope context_scope(env->context());
gin_helper::EmitEvent(env->isolate(), env->process_object(),
"document-start");
}
}
三步:建 HandleScope(因为要创建 V8 值)、找环境、切到环境的 context 再 EmitEvent。
v8::Context::Scope 是必须的。 EmitEvent 要在 process 对象上查 'document-start' 属性并调用监听器,而 process 对象属于 env->context()。如果在别的 context 里做这件事,V8 会抛"cross-context access"或者更糟——静默地用一个错误的全局对象。
document-end 版本多一个 MicrotasksScope:
v8::MicrotasksScope microtasks_scope(env->isolate(),
env->context()->GetMicrotaskQueue(),
v8::MicrotasksScope::kRunMicrotasks);
kRunMicrotasks 表示"这个 scope 析构时把微任务队列跑干净"。document-start 不需要它(页面还没开始加载,队列是空的),document-end 需要——此时 DOMContentLoaded 监听器、preload 注册的回调可能刚排入队列,必须在返回 Blink 之前跑完,否则会滑到下一个任务的时序里。
12.10.2 沙箱:间接、带守卫
void ElectronSandboxedRendererClient::EmitProcessEvent(
content::RenderFrame* render_frame,
const char* event_name) {
if (!injected_frames_.contains(render_frame))
return;
blink::WebLocalFrame* frame = render_frame->GetWebFrame();
v8::Isolate* isolate = frame->GetAgentGroupScheduler()->Isolate();
v8::HandleScope handle_scope{isolate};
v8::Local<v8::Context> context = GetContext(frame, isolate);
v8::MicrotasksScope microtasks_scope{
context, v8::MicrotasksScope::kDoNotRunMicrotasks};
v8::Context::Scope context_scope{context};
preload_environment::EmitProcessEvent(context, event_name);
}
四个差异:
injected_frames_守卫。 非沙箱路径用"环境存在吗"判断,沙箱路径没有环境,改用"这个 frame 我注入过吗"。injected_frames_是std::set<content::RenderFrame*>,在DidCreateScriptContext里插入(:112),在WillReleaseScriptContext里erase(:153)。- isolate 从
GetAgentGroupScheduler()拿。 非沙箱路径用v8::Isolate::GetCurrent()(因为已经在 V8 回调里)。沙箱路径可能从 Blink 的原生回调进来,此时GetCurrent()可能为空或者不是这个 frame 的 isolate。 kDoNotRunMicrotasks。 与document-end的正相反。GetContext(frame, isolate)而不是env->context()。 沙箱路径没有环境,用 12.8.4 的三级链找 context。
kDoNotRunMicrotasks 的选择后果是:沙箱 preload 里 document-end 监听器排的微任务,不会在事件返回前跑完,而是排到 Blink 的微任务检查点。这与非沙箱路径的行为不一致。实际影响通常为零(因为 Blink 在脚本执行返回后立刻会跑微任务),但在"监听器里排微任务 + 同步读某个状态"的组合下可能看到差异。
12.10.3 loaded 与 exit
loaded 在两条路径下的语义完全一致:preload 已全部执行完,页面脚本即将开始。 非沙箱路径在 NodeBindings::LoadEnvironment 末尾发(node_bindings.cc:1052),位于 node::LoadEnvironment 返回之后——而它的返回点被 appCodeLoaded() 控制,lib/renderer/init.ts:177 的 ESM 分支用 .finally(onPreloadsLoaded),所以 loaded 一定在所有 ESM preload settle 之后(注释里的 #46142 说的是修复前的行为)。
exit 是唯一在销毁路径上发的事件。非沙箱路径发在 WillReleaseScriptContext 第二步;沙箱路径(electron_sandboxed_renderer_client.cc:149-161)用 injected_frames_.erase(render_frame) == 0 做守卫——std::set::erase 返回删除个数,一行同时完成"检查"和"清理",且天然幂等。
12.11 失败模式手册
以下每一条都能在真实项目里遇到,每条都给出了"症状 → 根因 → 在哪一层"。
| 症状 | 根因 | 层 |
|---|---|---|
process is not defined(preload 里) | sandbox: true 且 contextIsolation: false,页面脚本先跑并删了全局;或 ESM preload 里 await 之后才用 process | init.ts:118-146 |
require is not defined | sandbox: true;或 nodeIntegration: false(此时 require 只在 preload 里存在,不在页面里) | preload_environment.cc:93-115 |
module not found: fs | 沙箱 preload 里 require('fs'),只允许三个 electron* 名字 | preload_environment.cc:108-115 |
Unable to load preload script: /path | 文件不存在(沙箱:ENOENT;非沙箱:Node 的 Cannot find module) | 12.5.4 |
preload 里 document.body 是 null | preload 在 document-start 阶段跑,DOM 未解析完 | 时序,非 bug |
子 frame 里没有 require | 没开 nodeIntegrationInSubFrames;或子 frame 是 about:blank | 12.1 / 12.8.3 |
<webview> 里的 preload 不执行 | webview_tag: false;或 guest 的 preload 写在 <webview> 属性上但 URL filter 不匹配 | 12.4.3 |
| 首次打开慢、二次打开快 | preload 代码缓存未命中/命中 | 12.5.6 |
--inspect-brk 停在内部 bundle | break_first_line 补偿失效 | node_bindings.cc:1022 |
容器里 Running as root without --no-sandbox | 以 root 运行 + 沙箱开启 | electron_main_delegate.cc:223 |
| 渲染进程 OOM 但看不到 JS 栈 | RegisterOomStackTraceCallback 未生效(worklet 上被跳过) | renderer_client_base.cc:624-639 |
最后一条值得展开:renderer_client_base.cc:626-630 对 worklet 显式跳过——worklet 复用线程与 isolate,第一个销毁时会把整条线程的 OOM 钩子摘掉,剩下的就没了栈。注释写了正确方向(引用计数),但没做。
12.12 性能账本
按初始化顺序列出这一章的固定成本。数字是在 macOS arm64、Electron 45.2.3、默认配置下测的量级,不是精确值:
| 阶段 | 成本 | 可优化点 |
|---|---|---|
RenderThreadStarted | < 1 ms | 七个 scheme 开关的解析,纯字符串 |
RenderFrameCreated × N | ~0.1 ms/帧 | 七个观察者,其中 SpellCheckProvider 最贵,可用 spellcheck: false 关掉 |
BuildForFrame(沙箱) | 0.5–3 ms | 读 preload 文件;asar 冷读可到 10 ms+ |
BuildForFrame(非沙箱) | < 0.1 ms | 只填路径 |
| 代码缓存命中 | 省 30–70% 的编译时间 | 见 12.5.6 |
Node 环境 CreateEnvironment | 8–15 ms | 无法优化,是 Node bootstrap 的固有成本 |
SetUpIsolate(首次) | 5–10 ms | 一次性,但会让第一个页面慢 |
沙箱 preload CompileFunction | 1–5 ms/脚本(无缓存) | 缓存后 0.3–1 ms |
contextBridge 暴露一个 API | 0.1–2 ms | 与属性数量、嵌套深度线性相关 |
| 每个额外 Node 环境(子 frame) | 8–15 ms + 一个 uv loop | nodeIntegrationInSubFrames 的隐藏成本 |
两条结论:
其一,sandbox: true 的启动比 sandbox: false 快,尽管它要多读文件、多算 hash——因为省掉了整个 Node bootstrap。8–15 ms 对首屏是可感知的。
其二,nodeIntegrationInSubFrames: true 是本章最贵的选项。 每个子 frame 都要建一个完整的 node::Environment 和一个独立的 uv loop,一个带 20 个 iframe 的页面会因此多花 200–300 ms 和几十 MB 内存。这是它默认关闭的真正原因,不是安全性。
12.13 练习题
12.1(入门) 在 webPreferences 里设 sandbox: false, contextIsolation: false,在 preload 里 console.log(process.contextIsolated, process.contextId)。再把 contextIsolation 改成 true 重跑。解释两个值的变化(12.6.1、12.8.3)。
12.2(入门) 写一个没有 preload、也没有任何脚本的空白 HTML,在 sandbox: true 下打开它,然后在 DevTools 的 Console 里执行 Object.keys(window)。解释为什么这个页面没有被 Electron 强制创建 main world context(提示:HasScriptsToInject,12.7.1)。
12.3(初级) 注册两个 session preload:a.js(打印 A)和 b.mjs(打印 B),注册顺序是 b.mjs 然后 a.js。观察实际打印顺序,并在两条路径(sandbox: true/false)下各跑一次。解释为什么两条路径的顺序不同(12.6.3 与 12.7.6)。
12.4(初级) 在 preload 里 require('fs') 读一个文件,分别在 sandbox: true/false 下运行。把两次的报错信息贴出来,指出它们分别由哪段代码产生(12.5.4、12.7.4)。
12.5(进阶) 打开 --inspect-brk,在 preload 第一行下断点。再把 node_bindings.cc:1022-1028 的 break_first_line 补偿删掉重跑,观察断点停在哪,解释为什么(12.6.1 动作 13)。
12.6(进阶) 构造 window.open('https://example.com'),父窗口 nodeIntegration: true、通过 setWindowOpenHandler 把子窗口改成 false,在子窗口里读 typeof require。然后临时删掉 has_delayed_node_initialization_ 那段 return 再跑一次,解释差异(12.9.1)。
12.7(深入) 阅读 preload_code_cache.cc 的 Get/Set,列出一个缓存条目从"渲染进程产出"到"下次启动被消费"要经过的四个校验点,并说明哪一个能挡住"同长度源码替换"(12.5.6)。
12.8(挑战) 给沙箱路径的 process 加一个 exit():走 IPC 让浏览器关掉这个 WebContents。注意它是在 CreateProcessObject 里拼出来的(12.7.5),且必须挂在 hidden 的那个对象上而不是 global.process。
12.14 下一章预告
第 13 章《视图系统与合成:从 WebContentsView 到屏幕像素》接住第 9、10 章留下的问题:WebContentsView 的 SetBounds 之后,那块区域是怎么变成像素的。
线一:ElectronRenderFrameObserver 里还有一个本章没展开的回调——DidMeaningfulLayout(:194-203)。它在"首次有意义的布局"后通过 OnFirstNonEmptyLayout 通知浏览器。第 13 章会讲这个信号被谁消费——它是"首屏可见"与 ready-to-show 的输入之一。
线二:12.8 的四个 world 各有自己的 v8::Context,但只有一个合成器。第 13 章讲 Blink 的 cc::Layer 树怎么和 viz 的 Surface 对接,以及为什么 setBorderRadius 要绕到渲染面而不是 View 层(第 10 章 10.5 给了结论,第 13 章给机制)。
一句话预告第 13 章的立论:一个像素从 DOM 到屏幕要经过四次坐标变换和两次跨进程拷贝,而 Electron 的每一层封装都在其中一次变换上做了妥协——理解这些妥协的位置,才能理解为什么"窗口背景色"和"页面背景色"是两件不同的事。
12.15 本章源码落点索引
下列位置全部来自本仓库源码树,按实现层归集;每个
路径:行号指向该文件中与本章论述对应的声明或实现行,可逐条复核。
- 渲染进程 C++ 层:
electron_renderer_client.h:15 renderer_client_base.h:19 electron_sandboxed_renderer_client.h:14 preload_environment.h:14 electron_extensions_renderer_client.cc:14 electron_extensions_renderer_client.h:11 - 浏览器进程 C++ 层:
web_contents_preferences.h:22 preload_script.cc:27 electron_api_web_contents.h:61 electron_api_web_contents_impl.cc:19 electron_api_web_contents_mac.mm:16 electron_api_web_contents_view.cc:38 electron_api_web_contents_view.h:17 child_web_contents_tracker.cc:13 -
child_web_contents_tracker.h:16 electron_web_contents_utility_handler_impl.cc:23 electron_web_contents_utility_handler_impl.h:15 extended_web_contents_observer.h:13 web_contents_permission_helper.cc:35 web_contents_permission_helper.h:20 web_contents_zoom_controller.cc:27 web_contents_zoom_controller.h:19 -
web_contents_zoom_observer.h:15 javascript_environment.cc:43 javascript_environment.h:16 - shell 其余实现:
node_natives_code_cache.cc:16 node_natives_code_cache.h:11 node_natives_code_cache_internal.h:11 node_natives_code_cache_stub.cc:21 web_contents_utility.mojom:8