《Electron 45.2.3 内核解剖》第 10 章 BaseWindow、BrowserWindow 与 WebContentsView:一个窗口能装什么

3 阅读1小时+

《Electron 45.2.3 内核解剖》第 10 章 BaseWindow、BrowserWindow 与 WebContentsView:一个窗口能装什么

第 9 章讲完了一个窗口的四个身体:JS 壳、api::BaseWindow、electron::NativeWindow、平台实现。 但那只回答了"窗口怎么被造出来",没有回答"窗口里装什么"。 这一章补上后半句,并且会推翻一个几乎所有人都有的直觉: BrowserWindow 的 webContents 并不在 win.contentView 里。


10.0 三个类,一个被误解的继承关系

先看一段几乎每个 Electron 应用都写过的代码:

const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://example.com')

这段代码里有三个对象同时在活:一个 BrowserWindow、一个 WebContents、一个原生窗口。第 9 章拆过。但下面这段代码,很多人会写错:

const { BrowserWindow, View } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
const overlay = new View()
overlay.setBackgroundColor('#ff000080')
overlay.setBounds({ x: 0, y: 0, width: 800, height: 40 })
win.contentView.addChildView(overlay)

直觉上,overlay 会被加到窗口内容区的最底层,因为"contentView 是内容容器"。实际上它会盖在网页上面。原因不是 z-index,而是这个 contentView 与网页所在的 WebContentsView 是兄弟节点,而 contentView 排在后面。

反过来,另一段代码会让人更困惑:

const win = new BrowserWindow()
win.contentView.children.length      // 0

窗口里明明有一个网页在渲染,contentView 却是空的。

这两件事指向同一个设计事实:

在 Electron 45 里,BrowserWindow 不是一个"自带网页的窗口",而是一个"预装了一个 WebContentsView 的 BaseWindow"。网页从来没在 contentView 里,它在 contentView 的兄弟节点上。

本章就围绕这句话展开。它解释了:

  • 为什么 BaseWindow 要存在(一个能装任意视图的容器);
  • 为什么 BrowserWindow 只能装一个网页(它的构造函数写死了一次 AddChildViewAt);
  • 为什么 WebContentsView 是唯一一个把整个渲染进程装进视图的 View 子类;
  • 为什么 <webview> 是这条路线上的第三条分支,也是最老的一条。

10.0.1 本章的四层地图

和第 9 章一样,本章的每个结论都能落到某一层。先把这四层的文件位置摆出来:

层文件行数职责
JS API 层base-window.ts:610只做一件事:给 BaseWindow 挂 setTouchBar
JS API 层browser-window.ts:6233_init 钩子、静态查找方法、17 个转发函数、BrowserView 管理
JS API 层browser-view.ts171纯 JS 实现的 BrowserView(已废弃),内部持有一个 WebContentsView
绑定层electron_api_base_window.cc1636159 个原型成员,几乎全部转发给 NativeWindow
绑定层electron_api_browser_window.cc395构造 70 行、WebContentsObserver、NativeWindowObserver
绑定层electron_api_view.cc638View 的 11 个方法、布局、动画、圆角
绑定层electron_api_web_contents_view.cc342视图入树/出树的六个动作、圆角、windowControlsOverlay
原生层native_window.h:80 / .cc662 / 1209SetContentView 纯虚、content_view_、GetContentsView
原生层root_view.cc:31-38197main_view_ 容器与菜单栏
原生层root_view_mac.mm:1629macOS 的 RootViewMac(FillLayout,没有 main_view_)
原生层inspectable_web_contents_view.cc344真正承载 views::WebView 的那一层

WebContentsView 有一个值得注意的空白:lib/ 下没有它的 TypeScript 文件。它不在 lib/browser/api/ 里,而是直接从绑定层导出:

lib/browser/api/module-list.ts:47-49

	{
	name: 'WebContentsView',
	loader: () => process._linkedBinding('electron_browser_web_contents_view').WebContentsView
	},

对比同文件里 View 的导出(第 44 行):

lib/browser/api/module-list.ts:44

	{ name: 'View', loader: () => process._linkedBinding('electron_browser_view').View },

两者都是裸绑定,都没有 JS 包装。但 BrowserView 有包装(第 8 行 require('./browser-view')),BrowserWindow 也有(browser-window.ts 那 233 行)。

有没有 JS 包装,恰好标出了这个类"需不需要在 JS 层补逻辑":

类有 JS 包装补了什么
BaseWindow有,10 行setTouchBar(TouchBar 是 JS 类,C++ 层拿不到)
BrowserWindow有,233 行_init、静态查找、17 个转发、BrowserView 兼容层
WebContentsView无三个方法,全在 C++
View无11 个方法,全在 C++
BrowserView有,171 行整个类都是 JS 写的(已废弃)

这条"包装厚度"梯度不是偶然,它准确反映了每个类在历史上被改过多少次:BrowserWindow 改了十几年,补丁摞补丁;View 系是后来的,还没有历史包袱。


10.1 原型链是怎么接起来的

在讨论行为之前,先把继承关系钉死。Electron 的类继承有两套同时存在的链:C++ 的模板继承和 V8 的原型链。它们由一行代码绑定。

10.1.1 V8 侧的继承:CreateConstructor 的第三个参数

BrowserWindow 的构造函数是这么注册的:

electron_api_browser_window.cc:387-390

	dict.Set("BrowserWindow",
		gin_helper::CreateConstructor<BrowserWindow>(
			isolate, base::BindRepeating(&BrowserWindow::New),
			electron::api::BaseWindow::GetConstructorTemplate(isolate)));

第三个参数是"父类的 FunctionTemplate"。gin_helper::CreateConstructor 拿到它之后会做 template->Inherit(parent_template),于是 V8 里 BrowserWindow.prototype.__proto__ === BaseWindow.prototype。

这意味着:

const { BrowserWindow, BaseWindow } = require('electron')
Object.getPrototypeOf(BrowserWindow.prototype) === BaseWindow.prototype   // true
new BrowserWindow() instanceof BaseWindow                                  // true

最后一行很重要。instanceof BaseWindow 为真,不是因为 JS 层做了任何事,而是因为 C++ 模板继承了。 所以 BaseWindow.getAllWindows() 返回的数组里可以混着 BaseWindow 和 BrowserWindow 实例,而 BrowserWindow.getAllWindows() 需要在 JS 层过滤一次:

browser-window.ts:75-86

const isBrowserWindow = (win: any) => {
	return win && win.constructor.name === 'BrowserWindow';
};
BrowserWindow.fromId = (id: number) => {
	const win = BaseWindow.fromId(id);
	return isBrowserWindow(win) ? (win as any as BWT) : null;
};
BrowserWindow.getAllWindows = () => {
	return BaseWindow.getAllWindows().filter(isBrowserWindow) as any[] as BWT[];
};

注意 isBrowserWindow 用的是 win.constructor.name === 'BrowserWindow',而不是 instanceof。为什么?因为 instanceof BrowserWindow 对 BaseWindow 实例是 false(方向对了),但对 BrowserWindow 实例是 true——看起来 instanceof 也能用。真正的理由是 constructor.name 在 minify 之后仍然稳定(第 8 章讲过 keepNames: true,BrowserWindow.name 是 API),而 instanceof 需要持有构造函数的引用,在跨 context 的场景下会失效。这是个防御性写法。

10.1.2 C++ 侧的继承:TrackableObject 与 WrappableBase

C++ 侧没有多重继承的花样:

electron_api_base_window.h:46-48

class BaseWindow : public gin_helper::TrackableObject<BaseWindow>,
				private NativeWindowObserver {

electron_api_browser_window.h:19-20

// shell/browser/api/electron_api_browser_window.h(经 grep 确认)
class BrowserWindow : public BaseWindow,
					private content::WebContentsObserver {

BrowserWindow 继承 BaseWindow,同时私有一份 content::WebContentsObserver。这个 private 继承不是修饰,它决定了外部无法把 BrowserWindow 当成 WebContentsObserver 用——它只在内部观察自己的 WebContents。

而 api::WebContentsView 的继承列表更长:

electron_api_web_contents_view.h:29-32

class WebContentsView : public View,
						private content::WebContentsObserver,
						private NativeWindowObserver,
						public DraggableRegionProvider {

四份继承,三个是 private,只有 DraggableRegionProvider 是 public。public 的那一个是唯一"对外承诺"的接口:

draggable_region_provider.h:11-13

class DraggableRegionProvider {
	public:
	virtual int NonClientHitTest(const gfx::Point& point) = 0;
};

一个只有一个纯虚函数的接口。 它存在的唯一理由是让 NativeWindow 能在非客户区命中测试时,把坐标问一遍所有"知道自己有可拖拽区域"的对象:

native_window.cc:775-780

	for (DraggableRegionProvider* provider : draggable_region_providers_) {
	int hit = provider->NonClientHitTest(point);
	if (hit != HTNOWHERE)
	return hit;
	}
	return HTNOWHERE;

一个 WebContentsView 之所以能成为拖拽区域的提供者,是因为它内部包着一个 WebContents,而 WebContents 知道页面里哪些 CSS 区域被标成了 -webkit-app-region: drag。第 9 章讲 NonClientHitTest 的三层时提过这个链条,这里补上链条的起点。

10.1.3 JS 与 C++ 的缝合点:_init

现在到了本章第一个真正的机制细节。

browser-window.ts:6-13 开头是一段看起来没头没尾的代码:

browser-window.ts:6-21

BrowserWindow.prototype._init = function (this: BWT) {
	// Avoid recursive require.
	const { app } = require('electron');
	// Set ID at construction time so it's accessible after
	// underlying window destruction.
	const id = this.id;
	Object.defineProperty(this, 'id', {
	value: id,
	writable: false
	});
	// Redirect focus/blur event to app instance too.
	this.on('blur', (event: Electron.Event) => {
	app.emit('browser-window-blur', event, this);
	});

_init 是谁调的?在 JS 里搜不到任何 ._init() 的调用点。它在 C++ 里被调:

wrappable.cc:68-75

void WrappableBase::InitWith(v8::Isolate* isolate,
							v8::Local<v8::Object> wrapper) {
	CHECK(wrapper_.IsEmpty());
	isolate_ = isolate;
	wrapper->SetAlignedPointerInInternalField(0, this,
											v8::kEmbedderDataTypeTagDefault);
	wrapper_.Reset(isolate, wrapper);
	wrapper_.SetWeak(this, FirstWeakCallback,
				v8::WeakCallbackType::kInternalFields);
	OnWrapped(isolate);
	// Call object._init if we have one.
	v8::Local<v8::Function> init;
	if (Dictionary(isolate, wrapper).Get("_init", &init))
	init->Call(isolate->GetCurrentContext(), wrapper, 0, nullptr).IsEmpty();
}

WrappableBase::InitWith 在挂完内部字段、设完弱引用之后,会去包装对象上找 _init 属性,找到就同步调用一次。

这是一个非常"低成本"的设计:C++ 不需要知道 JS 层想做什么,JS 也不需要导出初始化函数。双方只约定一个同名属性。代价是隐式:读 C++ 的人不知道 _init 里有什么,读 JS 的人不知道它什么时候被调。

_init 干的六件事,一件比一件重要:

  1. 把 id 冻成不可写属性。第 9 章说过,窗口关闭后原生对象可能已被 DeleteSoon 回收,但 JS 对象还在;此时 this.id 会走 getter 去问 C++,拿不到。所以在构造期读一次、存成普通属性。
  2. 把 focus/blur 转发到 app,产生 browser-window-focus / browser-window-blur 两个全局事件。
  3. 装一个"无响应"去抖器(26–55 行),把 webContents 的 unresponsive 事件延迟 50ms 再冒泡到窗口。
  4. 初始化 _browserViews 数组,并在 closed 时逐个 close({ waitForBeforeUnload: true })。
  5. app.emit('browser-window-created', { preventDefault() {} }, this),让应用能在窗口刚建好时介入。
  6. 定义 devToolsWebContents 只读属性,转发到 this.webContents.devToolsWebContents。

第 5 条的时间点值得单独说。browser-window-created 是在 _init 里发的,而 _init 是在 InitWithArgs 里被调的,而 InitWithArgs 在 BrowserWindow 构造函数里位于第 89 行——在 AddChildViewAt(第 98 行)之前。也就是说:

当 browser-window-created 的监听器跑起来时,这个窗口的 WebContentsView 还没有被加进视图树。

这个时间窗口非常窄,但完全可观测。你在 browser-window-created 里执行:

app.on('browser-window-created', (e, win) => {
	console.log(win.contentView.children.length)   // 0
	console.log(win.webContents.getURL())          // ''(还没 load)
})

contentView.children 是 0,因为 BrowserWindow 的 contentView 一直是那个空的 views::View(10.4 会详述),WebContentsView 加在它的父节点上。

10.1.4 _init 为什么只能在这个时刻跑

_init 里要访问 this.webContents、this.id、this.on——这些都是原型上已经就位的成员,但 wrapper 必须先是"活的"。InitWith 恰好是第一个满足条件的时刻:内部字段已挂、弱引用已设、原型链已生效。早一步 GetWrapper() 是空的,晚一步用户代码可能已经开始用这个对象。

InitWith 里还有一条顺序约束,写在 OnWrapped 的声明处:

wrappable_base.h:54

	// Called by InitWith once GetWrapper() works, before the wrapper's JS _init

OnWrapped 在 _init 之前。BaseWindow::OnWrapped 装的是应用菜单:

electron_api_base_window.cc:165-172

void BaseWindow::OnWrapped(v8::Isolate* isolate) {
#if !BUILDFLAG(IS_MAC)
	// The application menu is each window's menu bar until it sets its own,
	// which the JS that runs while constructing it may already do.
	if (Menu* menu = Menu::application_menu())
	SetMenuNatively(menu);
#endif
}

注释说明了顺序的理由:先装默认菜单,再跑 JS 的 _init,这样 _init 里若调了 setMenu(null) 能覆盖掉默认值。反过来就覆盖不了。

10.1.5 构造模板的隐式依赖

BaseWindow 的构造模板是懒创建的,且只有在被调过一次之后,SetConstructor 才执行:

electron_api_base_window.cc:1395-1404

v8::Local<v8::FunctionTemplate> BaseWindow::GetConstructorTemplate(
	v8::Isolate* isolate) {
	static bool created = false;
	if (!created) {
	created = true;
	SetConstructor(isolate, base::BindRepeating(&BaseWindow::New));
	}
	return GetConstructor(isolate);
}

而"第一次调用"是由 BrowserWindow 注册时那次传父模板完成的(10.1.1)。也就是说:new BaseWindow() 能用,是因为 BrowserWindow 的注册代码顺带初始化了它。 如果哪天有人把那个父模板参数去掉,BaseWindow 的构造模板就再也不会被创建,new BaseWindow() 直接崩——没有任何断言保护这条依赖。

对比 View::GetConstructorTemplate(electron_api_view.cc:572-582),它把模板缓存进 base::NoDestructor<v8::Global<v8::FunctionTemplate>>,不依赖外部触发。两种写法的差别不是风格,是"有没有隐式前置条件"。


10.2 BaseWindow:一个只负责"装"的窗口

BaseWindow 的 C++ 构造函数只有 34 行(:130-163),但它决定了后面所有事。

10.2.1 构造函数逐段

electron_api_base_window.cc:130-163

BaseWindow::BaseWindow(v8::Isolate* isolate,
					const gin_helper::Dictionary& options) {
	// make sure we don't override title on back/forward navigation
	// if the title is provided
	if (std::string title; options.Get(options::kTitle, &title))
	title_set_from_api_ = true;
	// The parent window.
	gin_helper::Handle<BaseWindow> parent;
	if (options.Get("parent", &parent) && !parent.IsEmpty())
	parent_window_.Reset(isolate, parent.ToV8());
	// Offscreen windows are always created frameless.
	gin_helper::Dictionary web_preferences;
	bool offscreen;
	if (options.Get(options::kWebPreferences, &web_preferences) &&
	web_preferences.Get(options::kOffscreen, &offscreen) && offscreen) {
	const_cast<gin_helper::Dictionary&>(options).Set(options::kFrame, false);
	}
	// Creates NativeWindow.
	NativeWindow* parent_native = parent.IsEmpty() ? nullptr : parent->window();
	window_ = NativeWindow::Create(GetID(), options, parent_native);
	window_->AddObserver(this);
	SetContentView(View::Create(isolate));
	...

六段,每段都有一个"为什么必须在这里"的理由。

第一段:title_set_from_api_。 这不是一个字段的初始化,而是一个状态标记。第 9 章说过,页面标题变化会同步到窗口标题;但如果用户显式传了 title 选项,就不能被页面标题盖掉。所以这里在构造最开始就把标记置上——早于任何可能触发 OnPageTitleUpdated 的代码。

第二段:parent。 拿的是 JS 的 BaseWindow 包装,存成 v8::Global。注意 parent_window_.Reset(isolate, parent.ToV8()) 存的是 JS 对象而不是 C++ 指针。这保证了子窗口活着的时候父窗口的 JS 对象不会被 GC——而 C++ 侧的关联由 parent_native 传给 NativeWindow::Create 单独完成。同一条关系存了两份,一份给 GC,一份给布局。

第三段:offscreen 强制无框。 这里有个 const_cast。options 是 const gin_helper::Dictionary&,但要往里塞 frame: false。为什么不等后面处理?因为 NativeWindow::Create 会立刻读 frame 去决定造不造边框,晚了就来不及。这也是 45.2.3 里少数还在用 const_cast 改入参的地方——它承认了"构造函数会修改配置"这个事实。

第四段:造原生窗口。 GetID() 是 TrackableObject 分配的进程内唯一 ID。三参数版本 Create(id, options, parent_native) 第 9 章拆过。紧接着 AddObserver(this) 把自己挂成观察者——注意这是在 SetContentView 之前,所以 SetContentView 触发的任何 OnWindow* 通知,BaseWindow 都能收到。

第五段:装一个空视图。

第六段:#if defined(TOOLKIT_VIEWS) 的图标块。 只有 Views 平台有,且只在用户传了 icon 时执行。它放在最后一位,因为它要等 window_ 完全就绪才能调 SetIconImpl。

10.2.2 SetContentView(View::Create(isolate)) 的深意

这一行是整章的锚点:

electron_api_base_window.cc:155

	SetContentView(View::Create(isolate));

View::Create 不是 new View(),它走的是"先造 JS 对象、再从 JS 对象反查 C++ 对象"的路:

electron_api_view.cc:592-601

gin_helper::Handle<View> View::Create(v8::Isolate* isolate) {
	v8::Local<v8::Context> context = isolate->GetCurrentContext();
	v8::Local<v8::Object> obj;
	if (GetConstructor(isolate)->NewInstance(context, 0, nullptr).ToLocal(&obj)) {
	gin_helper::Handle<View> view;
	if (gin::ConvertFromV8(isolate, obj, &view))
	return view;
	}
	return {};
}

为什么不直接 new api::View()?因为 api::View 的构造函数是 protected(electron_api_view.h:59),而且所有暴露给 JS 的对象都必须是先有 JS 对象、再有 C++ 对象的——InitWithArgs 拿的是 args->GetHolder(),也就是正在构造的那个 JS 对象。反过来造会得到一个没有 wrapper 的 C++ 对象,GetWrapper() 返回空,后续所有 gin_helper::Handle 操作都会失败。

于是 BaseWindow 的构造过程里嵌了一次完整的 JS 构造:new View() 走 View::New → new View() → InitWithArgs(args) → InitWith → OnWrapped → 找 _init(View.prototype 上没有,跳过)。

结果:每个 BaseWindow 在构造期都会在 V8 堆里多造一个 View 对象。 这是不可避免的设计代价,也是"窗口即容器"这个模型的入场费。

然后 SetContentView 把它绑到原生侧:

electron_api_base_window.cc:417-420

void BaseWindow::SetContentView(gin_helper::Handle<View> view) {
	content_view_.Reset(JavascriptEnvironment::GetIsolate(), view.ToV8());
	window_->SetContentView(view->view());
}

两行,两份记账:content_view_ 是 v8::Global<v8::Value>(保住 JS 对象不被 GC),window_->SetContentView 是原生树操作。

10.2.3 为什么要保住那个 v8::Global

content_view_ 是个 v8::Global<v8::Value>,在 GetContentView 里被读回:

electron_api_base_window.cc:1114-1119

v8::Local<v8::Value> BaseWindow::GetContentView() const {
	if (content_view_.IsEmpty())
	return v8::Null(isolate());
	else
	return v8::Local<v8::Value>::New(isolate(), content_view_);
}

如果这里不存 v8::Global,会发生什么?views::View* 还挂在原生树上,但对应的 JS 包装会被 GC。之后用户调 win.contentView.addChildView(x) 时,GetContentView() 得现造一个 api::View 包住那个游离的 views::View*——于是同一个原生视图对应两个 JS 对象,child_views_ 的记账、OnViewIsDeleting 的回调都会错乱。

v8::Global 在这里的作用不是"防泄漏",而是"保证一对一"。 这个区别很重要:Electron 里绝大多数 v8::Global<v8::Object> 成员都在干这件事——BrowserWindow::web_contents_、WebContentsView::web_contents_、BaseWindow::parent_window_、BrowserWindow::web_contents_view_,全是同一个模式。

代价是明确的:只要窗口活着,这个空 View 的 JS 对象和 C++ 对象就都活着。 一个 800×600 的窗口,白占一个 api::View + 一个 views::View + 一个 v8::Object。这是"容器化"的费用,每个 BaseWindow 都交。

10.2.4 换 contentView 会发生什么

setContentView 是个 setter,可以换:

const win = new BaseWindow()
win.setContentView(new View())

原生侧的实现分平台。Views 平台:

native_window_views.cc:567-580

void NativeWindowViews::SetContentView(views::View* view) {
	if (views::View* old_view = content_view()) {
	set_content_view(nullptr);
	focused_view_ = nullptr;
	if (old_view->owned_by_client())
	root_view_.GetMainView()->RemoveChildView(old_view);
	else
	root_view_.GetMainView()->RemoveChildViewT(old_view);
	}
	set_content_view(view);
	focused_view_ = view;
	root_view_.GetMainView()->AddChildViewRaw(content_view());
	FlushPendingRootLayout(root_view_.GetMainView());
}

七步,每一步都在处理一个具体的坑:

  1. 先 set_content_view(nullptr)。为什么不等移除完再设?因为 RemoveChildView 会触发 OnChildViewRemoved 等观察者回调,如果此时 content_view_ 还指着旧视图,回调里若有人查 content_view() 会拿到一个正在被拆的对象。先断开引用,再拆。
  2. focused_view_ = nullptr。焦点视图即将被移除,不清空会变成悬垂指针。
  3. owned_by_client() 分支。这是第 9 章讲过的 set_owned_by_client:Electron 的视图由 JS 对象持有所有权,所以用 RemoveChildView(只摘不删);原生自己造的视图用 RemoveChildViewT(摘下来并 delete)。
  4. focused_view_ = view。新视图直接成为焦点视图。这有点粗暴——它不检查新视图是否 focusable。实际效果是键盘事件会先发给它,如果它不接受焦点,views 会继续向下找。
  5. AddChildViewRaw。注意是 Raw 版本:调用方保留所有权,views::View 不接管。
  6. FlushPendingRootLayout。强制同步布局一次。

第 6 步值得展开。第 9 章提过这个函数,这里是它的全部四行:

native_window.cc:320-325

void NativeWindow::FlushPendingRootLayout(views::View* view) {
	view->InvalidateLayout();
	if (views::Widget* widget = view->GetWidget())
	widget->LayoutRootViewIfNecessary();
}

InvalidateLayout() 只打个脏标记;LayoutRootViewIfNecessary() 才在必要时同步跑一次布局。为什么 SetContentView 末尾要主动 flush?因为换 contentView 是同步 API,调用方(JS)期待下一行 getBounds() 就是正确结果;不 flush 的话拿到的是旧尺寸——新视图还没被布局到父容器大小。

这个"同步语义 vs 延迟布局"的冲突在 View 层更常见,10.4.6 会从另一个角度再遇到它。

macOS 的实现是另一份:

native_window_mac.mm:327-336

	views::View* root_view = GetContentsView();
	if (views::View* old_view = content_view()) {
	set_content_view(nullptr);
	if (old_view->owned_by_client())
	root_view->RemoveChildView(old_view);
	else
	root_view->RemoveChildViewT(old_view);
	}

没有 focused_view_ 的处理——macOS 不用 views 的焦点管理器管窗口焦点,它用 NSWindow 的 first responder。差异不是遗漏,是平台模型不同。

10.2.5 159 个方法里的平台分叉

BaseWindow 的原型上有 159 次 SetMethod/SetProperty 调用(含构造函数上的 4 个静态方法)。绝大多数是一行转发(maximize() → window_->Maximize()),真正值得注意的是平台专属的那一批:

electron_api_base_window.cc:1412-1419

// shell/browser/api/electron_api_base_window.cc:1412-1460(节选)
	.SetMethod<&BaseWindow::SetContentView>("setContentView")
	.SetMethod<&BaseWindow::Close>("close")
	...
	.SetMethod<&BaseWindow::SetThumbarButtons>("setThumbarButtons")
#if defined(TOOLKIT_VIEWS)
	.SetMethod<&BaseWindow::SetIcon>("setIcon")
#endif
#if BUILDFLAG(IS_WIN)
	.SetMethod<&BaseWindow::IsSnapped>("isSnapped")
	.SetProperty<&BaseWindow::IsSnapped>("snapped")
	.SetMethod<&BaseWindow::SetAccentColor>("setAccentColor")
	.SetMethod<&BaseWindow::GetAccentColor>("getAccentColor")
	.SetMethod<&BaseWindow::HookWindowMessage>("hookWindowMessage")

setThumbarButtons 不在任何 #if 里,但它在 Windows 之外的实现直接 return true——"方法存在但什么也不做"是 Electron 跨平台 API 的常态,比"方法不存在"常见得多,因为后者会让用户代码在加载期就炸,前者只是静默失效。setIcon 有 TOOLKIT_VIEWS 条件,因为 macOS 走 NSImage 另一条路;setAccentColor 只有 Windows 有,因为它是 Windows 11 的标题栏强调色,别的平台没有对应概念。

10.2.6 四个静态方法与窗口注册表

electron_api_base_window.cc:1623-1628

	constructor.SetMethod<&BaseWindow::FromWeakMapID>("fromId");
	constructor.SetMethod<&BaseWindow::GetAll>("getAllWindows");
	constructor.SetMethod<&BaseWindow::GetFocusedWindow>("getFocusedWindow");
	constructor.SetMethod<&BaseWindow::ClearPersistedState>(
	"clearPersistedState");

fromId 走的是 TrackableObject 的弱引用表(第 7 章讲过 FromWeakMapID)。getAllWindows 走 WindowList:

electron_api_base_window.cc:826-832

BaseWindow* BaseWindow::GetFocusedWindow() {
	for (BaseWindow* window : GetAllNative()) {
	if (window->window() && window->IsFocused())
	return window;
	}
	return nullptr;
}

注意 window->window() 的空检查。这个检查存在的原因是:GetAllNative() 返回的是 api::BaseWindow* 列表,而 api::BaseWindow 在 OnWindowClosed 之后会把 window_ 置空吗?不,window_ 是 std::unique_ptr<NativeWindow>,只在析构时 release()。所以 window() 非空但可能已 CloseImmediately。

真正的空值风险在别处:BaseWindow::IsLive。

electron_api_base_window.h:78-80

	// |window| may be dangling.
	static bool IsLive(const BaseWindow* window);

注释直说了"可能悬垂"。这让 GetAllWindows 的返回值必须经过 IsLive 过滤,而 GetFocusedWindow 又额外查了一次 window()——两层防御,因为这两条路径被调用的时机不同。

10.2.7 三道构造前的校验

BaseWindow::New 在 new 之前做三次检查(electron_api_base_window.cc:1312-1330),失败就 ThrowTypeError 且不构造对象。三道里只有第一道对所有平台生效:

// :1332-1352
bool BaseWindow::IsWindowNameValid(const gin_helper::Dictionary& options,
								std::string* error_message) {
	std::string window_name;
	if (options.Get(options::kName, &window_name) && !window_name.empty()) {
	// Check if window name is already in use by another window
	// Window names must be unique for state persistence to work correctly
	const auto& windows = electron::WindowList::GetWindows();
	bool name_in_use = std::any_of(windows.begin(), windows.end(),
								[&window_name](const auto* const window) {
									return window->GetName() == window_name;
								});

窗口名必须唯一,因为它是状态持久化的字典键。 第 9 章讲过 windowStatePersistence 把窗口位置写进 Local State 的 windowStates,键就是窗口名。两个窗口同名,恢复时互相覆盖。

这是"选项之间有隐式约束"的典型:name 看起来是自由字段,实际参与了持久化协议。而错误抛在构造时而不是开启持久化时,因为持久化可能在你不知道的时候被打开。

另外两道 IsAppShimValid(:1354)与 IsParentValid(:1383)只在 macOS 且涉及 app shim 时才有意义,约束是同一件事的两面:shim 窗口没有自己的 NSWindow,所以它既不能是模态、不能有 parent,也不能当别人的 parent。


10.3 BrowserWindow:一个写死了一次 AddChildViewAt 的 BaseWindow

如果只能读一段代码来理解 BrowserWindow,读它的构造函数。395 行的文件里,前 103 行解释了其余 292 行存在的全部理由。

10.3.1 构造函数的七个阶段

electron_api_browser_window.cc:30-103

BrowserWindow::BrowserWindow(gin::Arguments* args,
							const gin_helper::Dictionary& options)
	: BaseWindow(args->isolate(), options) {

第一行就值得停一下。它调的是 BaseWindow(v8::Isolate*, const Dictionary&) 这个 protected 重载,不是 BaseWindow(gin::Arguments*, const Dictionary&) 那个 public 重载。

两个重载的差别在 10.2.1 里没展开,这里补上:

electron_api_base_window.cc:174-179

BaseWindow::BaseWindow(gin::Arguments* args,
					const gin_helper::Dictionary& options)
	: BaseWindow(args->isolate(), options) {
	InitWithArgs(args);
	// Init window after everything has been setup.
	window()->InitFromOptions(options);
}

public 重载 = "建原生窗口 + InitWithArgs + InitFromOptions"。BrowserWindow 只借用了前半截,把 InitWithArgs 和 InitFromOptions 推迟到自己认为合适的时刻。这个推迟是本章最关键的时序设计,10.3.3 详述。

阶段 1:BaseWindow 构造(隐含)。 造 NativeWindow,装一个空 View 当 contentView。此时窗口对象存在,但没有任何内容。

阶段 2:准备 webPreferences。

electron_api_browser_window.cc:34-36

// :34-36
	v8::Isolate* isolate = args->isolate();
	auto web_preferences = gin_helper::Dictionary::CreateEmpty(isolate);
	options.Get(options::kWebPreferences, &web_preferences);

注意 CreateEmpty 之后立刻 Get。如果用户传了 webPreferences,Get 会把它填进同一个 gin_helper::Dictionary(gin 的 Dictionary 是引用语义,指向 JS 对象);如果没传,web_preferences 保持空,Get 返回 false 但对象仍可用。这是一个"可选参数默认空对象"的惯用法,Electron 里到处是它。

阶段 3:三处注入。

第一处,背景色:

electron_api_browser_window.cc:39-44

// :38-48
	// Copy the backgroundColor to webContents.
	std::string color;
	if (options.Get(options::kBackgroundColor, &color)) {
	web_preferences.SetHidden(options::kBackgroundColor, color);
	} else if (window()->IsTranslucent()) {
	// If the BrowserWindow is transparent or a vibrancy type has been set,
	// also propagate transparency to the WebContents unless a separate
	// backgroundColor has been set.
	web_preferences.SetHidden(options::kBackgroundColor,
							ToRGBAHex(SK_ColorTRANSPARENT));
	}

第 9 章 9.7 讲过"透明窗口全黑"的三层透明度。这里是第一层与第二层的桥:窗口的 backgroundColor 被复制进 webPreferences,让 WebContents 的合成器背景也透明。

SetHidden 而不是 Set——这个细节重要。SetHidden 会在 JS 对象上设一个不可枚举属性。为什么?因为 webPreferences 是用户可读的对象(webContents.getLastWebPreferences() 会返回它),如果往里塞一个用户没传的 backgroundColor 且可枚举,用户遍历时就会看到"我没设过的字段"。Electron 用 SetHidden 传递内部约定的值,用 Set 传递用户可见的值。 全仓库搜 SetHidden 能搜到 20 多处,都是这个用途。

第二处,show:

electron_api_browser_window.cc:52-57

// :50-58
	// Copy the show setting to webContents, but only if we don't want to paint
	// when initially hidden
	bool paint_when_initially_hidden = true;
	options.Get(options::kPaintWhenInitiallyHidden, &paint_when_initially_hidden);
	if (!paint_when_initially_hidden) {
	bool show = true;
	options.Get(options::kShow, &show);
	web_preferences.Set(options::kShow, show);
	}

这段的注释写得比代码更清楚:"只在不想在初始隐藏时绘制的情况下,才把 show 复制进 webContents"。

逻辑是:默认 paintWhenInitiallyHidden: true,即窗口 show: false 时页面照样绘制(这样 ready-to-show 才有意义)。如果用户显式设 paintWhenInitiallyHidden: false,那么 show: false 就要真的传下去,让 WebContents 一开始就不绘制。

这是一个"两个选项互相调制"的例子:show 的含义取决于 paintWhenInitiallyHidden。单看 show 的文档,你理解不了它为什么会被复制到 webPreferences 里。

第三处,webContents:

electron_api_browser_window.cc:61-65

// :60-67
	// Copy the webContents option to webPreferences.
	v8::Local<v8::Value> value;
	if (options.Get("webContents", &value)) {
	web_preferences.SetHidden("webContents", value);
	}
	if (!web_preferences.Has(options::kShow))
	web_preferences.Set(options::kShow, true);

允许用户把已有的 WebContents 塞进新窗口。这是 45.x 加的能力(WebContentsView 也支持),实现方式是"藏在 webPreferences 的 webContents 字段里"——因为 WebContents::CreateFromWebPreferences 只接受一个 webPreferences 参数,所有配置都得走这个独木桥。

第 66-67 行补一个 show: true 默认值。为什么是 true?因为 WebContents 层面的 show 语义是"页面是否可见",而不是"窗口是否可见"。一个窗口可以 show: false(不显示)但页面仍在绘制。所以 WebContents 的默认值是显示。

阶段 4:造 WebContentsView。

electron_api_browser_window.cc:70-76

// :69-76
	// Creates the WebContentsView.
	gin_helper::Handle<WebContentsView> web_contents_view =
	WebContentsView::Create(isolate, web_preferences);
	DCHECK(web_contents_view.get());
	window()->AddDraggableRegionProvider(web_contents_view.get());
	window()->InitPrimaryWebContentsView(
	static_cast<InspectableWebContentsView*>(web_contents_view->view()));
	web_contents_view_.Reset(isolate, web_contents_view.ToV8());

四件事,每件都在建立一条引用:

  1. WebContentsView::Create 走的是"造 JS 对象再反查"(同 View::Create),内部会 WebContents::CreateFromWebPreferences,于是渲染进程的启动从这里开始。
  2. AddDraggableRegionProvider 把视图注册为拖拽区域提供者(10.1.2 的链条起点)。
  3. InitPrimaryWebContentsView 把 InspectableWebContentsView* 记进 NativeWindow:

native_window.cc:162-167

void NativeWindow::InitPrimaryWebContentsView(
	InspectableWebContentsView* view) {
	CHECK(!primary_web_contents_view_);
	primary_web_contents_view_.SetView(view);
}

CHECK(!...) —— 一个窗口只能有一个 primary web contents view。这是 BrowserWindow 的硬约束,也是它与 BaseWindow 最本质的区别:BaseWindow 可以有 0 到 N 个 WebContentsView,BrowserWindow 恰好有 1 个且被标记为 primary。

primary_web_contents_view_ 是 views::ViewTracker(native_window.h:634),一个能在视图被销毁时自动置空的弱引用。为什么不用裸指针?因为 WebContents 可能在窗口之前被销毁(webContents.close()),此时视图没了但 NativeWindow 还在,裸指针就悬垂了。

  1. web_contents_view_.Reset(...) 保住 JS 对象。

阶段 5:拿 WebContents,双向绑定。

electron_api_browser_window.cc:79-85

// :78-87
	// Save a reference of the WebContents.
	gin_helper::Handle<WebContents> web_contents =
	web_contents_view->GetWebContents(isolate);
	web_contents_.Reset(isolate, web_contents.ToV8());
	api_web_contents_ = web_contents->GetWeakPtr();
	api_web_contents_->AddObserver(this);
	Observe(api_web_contents_->web_contents());
	// Associate with BrowserWindow.
	web_contents->SetOwnerWindow(window());

注意这里同时建立了三条引用,强弱不同:

成员类型强度用途
web_contents_v8::Global<v8::Value>强(GC 根)保住 JS 包装
api_web_contents_base::WeakPtr<api::WebContents>弱调 API 不阻止销毁
Observe(...)content::WebContentsObserver观察者收生命周期事件

三条引用指向同一个对象的三个层面。为什么不用一条? 因为它们的失效时机不同:JS 包装可能先被 GC(如果用户不持有引用且 web_contents_ 被 Reset),api::WebContents 可能被 Destroy(),底层 content::WebContents 可能被 Chromium 单独关闭。三种死法,三种检测方式。

SetOwnerWindow(window()) 是第 9 章"尾巴二"的入口,10.7 会专门拆。

阶段 6:InitWithArgs——JS 初始化。

// :89
	InitWithArgs(args);

一行,但它干了:设内部字段、设弱回调、OnWrapped(装菜单)、调 BrowserWindow.prototype._init(10.1.3 的六件事)、发 browser-window-created。

阶段 7:入树与收尾。

electron_api_browser_window.cc:98-100

// :91-102
	// Install the content view after BaseWindow's JS code is initialized.
	// The WebContentsView is added a sibling of BaseWindow's contentView (before
	// it in the paint order) so that any views added to BrowserWindow's
	// contentView will be painted on top of the BrowserWindow's WebContentsView.
	// See https://github.com/electron/electron/pull/41256.
	// Note that |GetContentsView|, confusingly, does not refer to the same thing
	// as |BaseWindow::GetContentView|.
	window()->GetContentsView()->AddChildViewAt(web_contents_view->view(), 0);
	window()->GetContentsView()->DeprecatedLayoutImmediately();
	// Init window after everything has been setup.
	window()->InitFromOptions(options);

这段注释是整章最重要的文献。它明确说了三件事:

  1. WebContentsView 是 contentView 的兄弟,不是子节点。
  2. 它被插在 index 0,在绘制顺序上位于 contentView 之前(先画,所以在下面)。
  3. GetContentsView 和 GetContentView 不是一回事。

10.3.2 为什么 InitWithArgs 必须在 AddChildViewAt 之前

注释第一句给了答案的一半:"Install the content view after BaseWindow's JS code is initialized."——在 JS 初始化之后才装内容视图。

反过来想:如果先装 WebContentsView 再 InitWithArgs,会怎样?

_init 里会发 browser-window-created。如果此时 WebContentsView 已经在树里,监听器里执行 win.contentView.addChildView(overlay) 会得到一个"已经能工作"的窗口——看起来更好。但问题是 _init 里还有这一段:

browser-window.ts:59-61

	this.on('closed', () => {
	this._browserViews.forEach((b) => b.webContents?.close({ waitForBeforeUnload: true }));
	});

以及 _browserViews = [] 的初始化(第 57 行)。如果 _init 抛异常(比如用户没装 app 模块导致 require('electron') 循环),那么 _browserViews 就是 undefined,后续 addBrowserView 会崩。所以顺序是防御性的:把可能失败的用户可见代码(browser-window-created)放在视图树完整之前,这样即使它抛异常,构造函数也已经走完一半,DCHECK 和析构路径仍然成立。

但真正的理由是更朴素的一条:initWithArgs 会调 InitWith,而 InitWith 里有 CHECK(wrapper_.IsEmpty())。 只能调一次。BaseWindow 的 public 重载已经调过了——但 BrowserWindow 用的是 protected 重载,绕过它。所以 BrowserWindow 必须自己调,且必须在 content_view_ 已经就位(BaseWindow 构造时设的)之后、在 InitFromOptions 之前。

InitFromOptions 必须最后,理由第 9 章 9.3.4 讲过:它会读 options 里的尺寸、位置、show 等,并做 ClampSize、Center、Show 等动作。如果视图树还没建好就 Show(),用户会看到一个空白窗口闪一下。

七个阶段的正确顺序是:造窗口 → 造内容 → 绑定 → JS 初始化 → 入树 → 布局 → 显示。 任何一步提前,都会产生可见的瑕疵或崩溃。

10.3.3 AddChildViewAt(..., 0) 为什么要插在最前

AddChildViewAt 的 index 语义在 View 层是"第几个孩子"。而 views::View 的绘制顺序是:index 小的先画,也就是在下面。

BrowserWindow 构造时,main_view_ 里已经有一个孩子了——BaseWindow 造的那个空 contentView。所以:

  • 不指定 index(追加到末尾):[contentView, WebContentsView],网页在上面,用户往 contentView 里加的东西看不见。
  • 指定 index 0(插到最前):[WebContentsView, contentView],网页在下面,contentView 里的一切都盖在网页上。

PR #41256 之前用的是哪种?注释里说得很清楚:"The WebContentsView is added a sibling of BaseWindow's contentView (before it in the paint order) so that any views added to BrowserWindow's contentView will be painted on top."

这个设计把 BrowserWindow.contentView 从"内容容器"变成了"覆盖层容器"。 语义上它更合理(contentView 里放的东西应该看得见),但它和 BaseWindow.contentView 的语义正好相反——后者装的就是内容。

这是本章最容易踩的坑,10.4 会给出完整的两棵树对照。

10.3.4 只有三个原型成员

BrowserWindow 的 BuildPrototype 极短:

electron_api_browser_window.cc:355-362

void BrowserWindow::BuildPrototype(v8::Isolate* isolate,
								v8::Local<v8::FunctionTemplate> prototype) {
	prototype->SetClassName(gin::StringToV8(isolate, "BrowserWindow"));
	gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
	.SetMethod<&BrowserWindow::FocusOnWebView>("focusOnWebView")
	.SetMethod<&BrowserWindow::BlurWebView>("blurWebView")
	.SetProperty<&BrowserWindow::GetWebContents>("webContents");
}

三个。 对比 BaseWindow 的 159 个。

也就是说,BrowserWindow 的 API 表面上和 BaseWindow 一样多(文档里 browser-window.md:148 有 1862 行),但多出来的部分全部来自两处:

  1. 继承:BaseWindow 的 159 个成员通过模板继承自动可见。
  2. JS 层的 20 个转发(10.3.5)。

C++ 层只多了三个:focusOnWebView / blurWebView / webContents。前两个是"只把焦点给网页、不动窗口"的精细操作:

electron_api_browser_window.cc:278-281

// :278-284
void BrowserWindow::FocusOnWebView() {
	web_contents()->GetRenderViewHost()->GetWidget()->Focus();
}
void BrowserWindow::BlurWebView() {
	web_contents()->GetRenderViewHost()->GetWidget()->Blur();
}

它们存在的理由是离屏渲染。看 Focus():

electron_api_browser_window.cc:237-240

// :237-242
void BrowserWindow::Focus() {
	if (api_web_contents_ && api_web_contents_->IsOffScreen())
	FocusOnWebView();
	else
	BaseWindow::Focus();
}

离屏窗口没有真实的原生窗口焦点(它可能根本没有 NSWindow),所以 Focus() 必须退化成"给渲染 widget 发焦点"。同一套 API 在 OSR 模式下走完全不同的一条路,这是 Electron 里反复出现的模式:IsOffScreen() 分支。

webContents 是个 property,getter 返回保存的 JS 对象:

electron_api_browser_window.cc:286-289

// :286-290
v8::Local<v8::Value> BrowserWindow::GetWebContents(v8::Isolate* isolate) {
	if (web_contents_.IsEmpty())
	return v8::Null(isolate);
	return v8::Local<v8::Value>::New(isolate, web_contents_);
}

IsEmpty 的情况发生在 WebContentsDestroyed 之后:

electron_api_browser_window.cc:118-120

// :118-121
void BrowserWindow::WebContentsDestroyed() {
	api_web_contents_ = nullptr;
	CloseImmediately();
}

网页没了,窗口就关。 这是 BrowserWindow 与 BaseWindow 最深的一条差异:它的生命周期被 WebContents 绑住了。一个 BaseWindow 可以在所有 WebContentsView 都销毁后继续存在(变成一个空窗口),BrowserWindow 不会。

10.3.5 JS 层的转发函数

browser-window.ts:109-114

// lib/browser/api/browser-window.ts:107-175(节选)
// Forwarded to webContents:
BrowserWindow.prototype.loadURL = function (...args) {
	return this.webContents.loadURL(...args);
};
BrowserWindow.prototype.getURL = function () {
	return this.webContents.getURL();
};
BrowserWindow.prototype.loadFile = function (...args) {
	return this.webContents.loadFile(...args);
};

loadURL / getURL / loadFile / reload / send / openDevTools / closeDevTools / isDevToolsOpened / isDevToolsFocused / toggleDevTools / inspectElement / inspectSharedWorker / inspectServiceWorker / showDefinitionForSelection / capturePage / getBackgroundThrottling / setBackgroundThrottling——17 个方法,加上 addBrowserView / setBrowserView / removeBrowserView / getBrowserView / getBrowserViews / setTopBrowserView 六个 BrowserView 管理方法,共 23 个。

为什么不放 C++?三个理由:

理由一:这些方法在 BrowserWindow 上只是历史遗留。 2013 年的 Electron(当时还叫 atom-shell)里,BrowserWindow 就是网页,没有 WebContents 这个公开概念。后来 WebContents 被抽出来,为了不破坏 API,BrowserWindow 上的方法被保留成转发。它们的存在本身就是一段考古证据。

理由二:转发在 JS 层更便宜。 C++ 转发要写一个成员函数、注册到原型、处理返回值转换。JS 一行搞定,且 ...args 能无脑透传任意参数——C++ 做不到(gin::Arguments 要手动展开每个参数)。

理由三:webContents 可能为 null。 如果用 C++ 转发,web_contents() 返回空时会崩;JS 转发则会抛出 Cannot read properties of null,错误信息更接近用户认知。

代价是这些方法不在 BrowserWindow.prototype 的 V8 模板里,而在 JS 层被赋上去。这导致一个可观测的差异:

const win = new BrowserWindow()
win.loadURL === win.webContents.loadURL          // false
win.loadURL.toString().includes('this.webContents.loadURL')   // true
Object.getOwnPropertyNames(BrowserWindow.prototype).includes('loadURL')  // true(JS 赋的)

loadURL 是 BrowserWindow.prototype 的自有属性(因为 BrowserWindow.prototype.loadURL = ... 是直接赋值),但它不是原生方法。这解释了第 9 章练习题 9.1 为什么要验证 win.loadURL !== win.webContents.loadURL。

一个副作用:loadURL 的 this 绑定错了会炸,但 bind 之后能用:

const { loadURL } = win
loadURL('https://example.com')     // TypeError: Cannot read properties of undefined
loadURL.call(win, 'https://example.com')   // 正常

10.3.6 关闭路径被改写成"先关网页"

BrowserWindow 覆盖了 OnCloseButtonClicked:

electron_api_browser_window.cc:159-166

// :159-177
void BrowserWindow::OnCloseButtonClicked(bool* prevent_default) {
	// When user tries to close the window by clicking the close button, we
	// do not close the window immediately, instead we try to close the web page
	// first, and when the web page is closed the window will also be closed.
	*prevent_default = true;
	// Already closed by renderer.
	if (!web_contents() || !api_web_contents_)
	return;
	// Required to make beforeunload handler work.
	api_web_contents_->NotifyUserActivation();
	if (web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
	web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
	} else {
	web_contents()->Close();
	}
}

四步:

  1. 无条件 *prevent_default = true。窗口永远不在这一次点击里直接关。这是一个"拦截并改道"的模式。
  2. NotifyUserActivation()。注释说"Required to make beforeunload handler work"——因为 Chromium 的 beforeunload 对话框需要用户激活(user activation)才能弹出。点击关闭按钮是一次真实交互,但 Chromium 不认为这是"页面获得激活",所以要手动补。
  3. NeedToFireBeforeUnloadOrUnloadEvents():页面有没有 beforeunload 监听器。有就走 DispatchBeforeUnload,没有就直接 Close()。
  4. DispatchBeforeUnload(false):auto_cancel=false 意味着不自动取消,让对话框决定。

如果用户点了"取消",链路是 BeforeUnloadDialogCancelled:

electron_api_browser_window.cc:114-115

// :114-116
void BrowserWindow::BeforeUnloadDialogCancelled() {
	WindowList::WindowCloseCancelled(window());
}

WindowCloseCancelled 会通知 WindowList,"这个窗口本来要关,现在不关了"。第 9 章讲过 WindowList 的 window-all-closed 计数逻辑——如果不通知,计数就会错位,应用可能在一个窗口还活着的时候退出。

整条链是:点击 → 拦截 → 问网页 → 网页同意 → WebContents 关 → WebContentsDestroyed → CloseImmediately → 窗口关。 五步,跨两个对象,其中任何一步失败都会留下一个"半关闭"的窗口。

10.3.7 焦点、显示与标题

三处覆盖都源于同一个事实:BrowserWindow 有一个"主网页",所以窗口级的事件要翻译成网页级的行为。

焦点:

electron_api_browser_window.cc:186-191

// :186-210(节选)
void BrowserWindow::OnWindowFocus() {
	if (api_web_contents_ && !FocusIsInAnotherView()) {
	web_contents()->RestoreFocus();
#if !BUILDFLAG(IS_MAC)
	if (!api_web_contents_->IsDevToolsOpened())
	web_contents()->Focus();
#endif
	}
	BaseWindow::OnWindowFocus();
}

FocusIsInAnotherView()(:201-210)的判断是"views 焦点管理器里的当前焦点视图,是否在 primary_web_contents_view() 之外"。它存在的原因是 45.x 才暴露的一个老 bug:窗口关闭时会发 focus/blur,此时焦点可能已经被移到同窗口内的子 WebContentsView(用户点进去的那个),无条件 Focus() 会把它抢回来。

这是"多视图窗口普及之后才暴露的问题"——在"一窗口一网页"的时代,primary_web_contents_view() 是唯一视图,焦点不可能在别处。macOS 上直接 return false,因为焦点归 NSWindow 的 first responder 管。

显示:

electron_api_browser_window.cc:292-296

// :292-310(节选)
void BrowserWindow::OnWindowShow() {
	if (!web_contents_shown_) {
	web_contents()->WasShown();
	web_contents_shown_ = true;
	}
	BaseWindow::OnWindowShow();
}

WasShown() / WasOccluded() 是 Chromium 的可见性协议,也是 backgroundThrottling 的底层。web_contents_shown_ 这个 bool 保证幂等:用户调 win.show() 走 Show(),随后原生层又发 OnWindowShow,两次都调 WasShown() 会让可见性状态机出错。

标题:

electron_api_browser_window.cc:142-148

// :137-153(节选)
	auto self = weak_factory_.GetWeakPtr();
	if (!Emit("page-title-updated", title, explicit_set)) {
	// |this| might be deleted, or marked as destroyed by close().
	if (self && !IsDestroyed()) {
	if (from_same_document_history_navigation) {
		SetTitleFromPageIfNotSetFromApi(base::UTF16ToUTF8(title));
	} else {
		SetTitleFromPage(base::UTF16ToUTF8(title));
	}
	}
	}

auto self = ... 在下一行就被检查,看似多余——中间只有 Emit,而监听器里可能调 close() 或 destroy()。"发事件前取弱引用"是 Electron 的固定写法。

from_same_document_history_navigation 分成两条路径:SPA 路由变化走 IfNotSetFromApi(尊重用户设过的 title),真实导航走 SetTitleFromPage(强制覆盖)。这就是 10.2.1 里 title_set_from_api_ 的用武之地。

10.3.8 析构与"用户直接销毁对象"

electron_api_browser_window.cc:105-108

// :105-112
BrowserWindow::~BrowserWindow() {
	if (api_web_contents_) {
	// Cleanup the observers if user destroyed this instance directly instead of
	// gracefully closing content::WebContents.
	api_web_contents_->RemoveObserver(this);
	api_web_contents_->Destroy();
	}
}

api_web_contents_ 非空说明 WebContentsDestroyed 没被调过——也就是用户没走"关网页"的路,而是让 JS 对象被 GC 或者 destroy()。

此时析构函数要手动清理:先摘观察者(否则 Destroy() 会回调 WebContentsDestroyed,而 this 正在析构),再 Destroy() 底层 WebContents。

顺序不能反。 反了就是"析构中收到回调",第 7 章讲过的经典崩溃。


10.4 两棵树:contentView 与 GetContentsView

现在解决开篇那个矛盾:为什么 win.contentView.children.length === 0,而网页明明在渲染。

10.4.1 四个名字,三样东西

Electron 在这个位置上的命名混乱程度,值得单独列一张表:

名字语言实际指向谁是它的孩子
win.contentViewJSapi::View,包着一个空的 views::View用户 addChildView 加的东西
BaseWindow::GetContentView()C++同上,返回那个 v8::Global同上
NativeWindow::content_view()C++content_view_,即上面那个 views::View*同上
NativeWindow::GetContentsView()C++main_view_(Views)或 RootViewMac(Mac)content_view_ + primary WebContentsView

前三个是同一个东西。第四个是它们的父节点。

注释里那句"Note that |GetContentsView|, confusingly, does not refer to the same thing as |BaseWindow::GetContentView|"就是在提醒这件事——而且这句提醒是写给未来改这段代码的人看的,不是给用户看的。它出现在源码里,说明连维护者都觉得这个命名是个坑。

10.4.2 GetContentsView 的两个平台实现

Views 平台(Windows / Linux):

native_window_views.cc:1993-1995

views::View* NativeWindowViews::GetContentsView() {
	return root_view_.GetMainView();
}

main_view_ 是 RootView 的第二个孩子(第一个是菜单栏,按需插入):

root_view.cc:41-51

RootView::RootView(NativeWindow* window)
	: window_{raw_ref<NativeWindow>::from_ptr(window)},
	main_view_{raw_ref<views::View>::from_ptr(
		AddChildView(std::make_unique<views::View>()))} {
	set_owned_by_client(OwnedByClientPassKey{});
	views::BoxLayout* layout =
	SetLayoutManager(std::make_unique<views::BoxLayout>(
		views::BoxLayout::Orientation::kVertical));
	main_view_->SetUseDefaultFillLayout(true);
	layout->SetFlexForView(&main_view_.get(), 1);
}

三个细节:

  1. RootView 用 BoxLayout(垂直),main_view_ 的 flex 是 1——所以菜单栏占固定高度,main_view_ 吃掉剩下的全部。
  2. main_view_->SetUseDefaultFillLayout(true)——main_view_ 内部用"填充布局",所有孩子都铺满。这就是为什么 contentView 和 WebContentsView 尺寸相同。
  3. set_owned_by_client——RootView 归 JS 侧所有(NativeWindow 持有它但不删它)。这是第 9 章讲的所有权模式。

macOS:

native_window_mac.mm:1770-1772

views::View* NativeWindowMac::GetContentsView() {
	return root_view_.get();
}

macOS 没有 main_view_ 这一层,直接返回 RootViewMac。

root_view_mac.mm:24-27

RootViewMac::RootViewMac(NativeWindow* window) : window_(window) {
	set_owned_by_client(OwnedByClientPassKey{});
	SetLayoutManager(std::make_unique<views::FillLayout>());
}

FillLayout,没有菜单栏孩子(macOS 的菜单是 NSMenu,不在视图树里)。

所以同一个 AddChildViewAt(view, 0),在两个平台上的效果是:

平台目标容器容器里原有插入后顺序
Windows/Linuxmain_view_[content_view_][WebContentsView, content_view_]
macOSRootViewMac[content_view_][WebContentsView, content_view_]

顺序一致,容器不同。 这个差异对用户不可见,但对读源码的人是第一个"两个平台不是同一棵树"的冲击。

10.4.3 完整的树形 dump

把一个刚构造完的 BrowserWindow 的视图树画出来。Views 平台:

views::Widget
└── RootView                          (BoxLayout vertical, owned_by_client)
	├── MenuBar                       (按需,index 0,固定高度)
	└── main_view_                    (flex=1, UseDefaultFillLayout)   ← GetContentsView()
		├── InspectableWebContentsView  (WebContentsView 的 view(), index 0)   ← 网页在这
		│   ├── views::WebView          (devtools_web_view_, 默认隐藏)
		│   └── views::WebView          (contents_web_view_, 真正渲染页面)
		└── views::View               (BaseWindow 造的 contentView)      ← win.contentView

macOS:

views::Widget
└── RootViewMac                       (FillLayout, owned_by_client)   ← GetContentsView()
	├── InspectableWebContentsView     (index 0)
	│   ├── views::WebView            (devtools)
	│   └── views::WebView            (contents)
	└── views::View                   (contentView)

两层嵌套值得注意:InspectableWebContentsView 内部还有两个 views::WebView——一个给页面,一个给 DevTools。DevTools 停靠时,Layout() 会按 DevToolsContentsResizingStrategy 把可用空间切成两块:

inspectable_web_contents_view.cc:309-315

// shell/browser/ui/inspectable_web_contents_view.cc:309-336(节选)
void InspectableWebContentsView::Layout(PassKey) {
	if (!devtools_web_view_->GetVisible()) {
	SetContentsViewBounds(GetContentsBounds());
	// Propagate layout call to all children, for example browser views.
	LayoutSuperclass<View>(this);
	return;
	}
	...
	ApplyDevToolsContentsResizingStrategy(
	strategy_, container_bounds, &new_devtools_bounds, &new_contents_bounds);

这也解释了 10.5 会讲的一个细节:WebContentsView::NonClientHitTest 为什么要先把坐标转换到 contents_view 而不是 inspectable_view:

electron_api_web_contents_view.cc:102-112

	// Convert the point to the contents view's coordinate space rather than
	// the InspectableWebContentsView's coordinate space, because the draggable
	// region is relative to the web content area. When DevTools is docked
	// (e.g. to the left), the contents view is offset within the parent,
	// so we need to account for that offset.
	auto* inspectable_view = iwc->GetView();
	if (!inspectable_view)
	return HTNOWHERE;
	auto* contents_view = inspectable_view->GetContentsView();
	gfx::Point local_point(point);
	views::View::ConvertPointFromWidget(contents_view, &local_point);

DevTools 停靠在左边时,页面被推到右边,contents_view 的 origin 不再是 (0,0)。可拖拽区域是相对页面算的,所以必须先减去这个偏移。如果不减,拖拽热区会整体偏移 DevTools 的宽度——一个只在你打开 DevTools 时才复现的 bug。

10.4.4 为什么 BrowserWindow 的 contentView 必须是空的

一个自然的反问:既然 BrowserWindow 已经预装了一个 WebContentsView,为什么不把它当成 contentView?这样 win.contentView 就是网页,语义更直观。

答案藏在 BaseWindow::SetContentView 的类型上:

electron_api_base_window.cc:417

void BaseWindow::SetContentView(gin_helper::Handle<View> view) {

参数是 api::View,而 api::WebContentsView 是 api::View 的子类(10.1.2)。所以类型上完全可以。真正的障碍有三个:

障碍一:contentView 是可替换的。 win.setContentView(new View()) 会把旧的 contentView 从树上摘掉。如果 contentView 就是 WebContentsView,这次调用会顺手把网页从视图树里摘掉——页面还在,WebContents 还活着,但不再被显示。而用户的本意只是"换个背景容器"。这个陷阱太深。

障碍二:contentView 属于 BaseWindow,WebContentsView 属于 BrowserWindow。 前者在 BaseWindow 构造函数里创建(第 155 行),后者在 BrowserWindow 构造函数第 70 行才创建。如果让后者成为前者的替代品,就得在 BrowserWindow 构造完成后回头覆盖 BaseWindow 的 content_view_——而 BaseWindow 的 GetContentView 已经把旧对象存进 v8::Global 了。改起来要动两个类的封装边界。

障碍三(最关键):contentView 的语义在 BaseWindow 和 BrowserWindow 上必须一致。 BaseWindow 里它是"内容",BrowserWindow 里它是"覆盖层"。这个不一致是 PR #41256 的有意选择:

在 BaseWindow 上,你往 contentView 里加的是内容本身(因为没有别的内容)。 在 BrowserWindow 上,网页已经占了内容位,你往 contentView 里加的只能是浮在网页上的东西。

这个语义偏移被写进了注释(第 91-97 行),但没有写进文档。browser-window.md 里没有任何地方说"contentView 里的东西会盖在网页上"。

代价是:一段在 BaseWindow 上正确的代码,搬到 BrowserWindow 上会产生相反的 z-order。

// BaseWindow:背景层
const win = new BaseWindow()
const bg = new View()
bg.setBackgroundColor('#222')
bg.setBounds({ x: 0, y: 0, width: 800, height: 600 })
win.contentView.addChildView(bg)
// 结果:bg 就是整个窗口的内容
// BrowserWindow:完全一样的代码
const win2 = new BrowserWindow()
const bg2 = new View()
bg2.setBackgroundColor('#222')
bg2.setBounds({ x: 0, y: 0, width: 800, height: 600 })
win2.contentView.addChildView(bg2)
// 结果:bg2 盖住了网页(因为 index 在 WebContentsView 之后)

第二段代码的 bg2 是不透明的,所以网页彻底看不见。如果把它当成"设置窗口背景",会得到一个纯色窗口加一个还在跑的渲染进程。

正确的"给 BrowserWindow 设背景"是 backgroundColor 选项或 setBackgroundColor(),它会同时改窗口层和 WebContents 层(10.3.1 阶段 3)。

10.4.5 在 contentView 上能干什么

既然是覆盖层,用途就限定了:

  • 调试层:把需要排查的区域画成半透明矩形盖在页面上。
  • 原生装饰:一个 titleBarStyle: 'hidden' 窗口上放一条 40px 高的原生条(注意它是原生视图,不是 HTML;HTML 标题栏要用 titleBarOverlay)。
  • 多视图的 z-order 管理:真正在用的是它的兄弟关系。

最后一条值得展开。BaseWindow 里放 N 个 WebContentsView,谁在上面由 addChildView 的顺序决定,而"重复添加"不是错误,是重排到末尾:

electron_api_view.cc:261-267

	// If the child is already a child of this view, just reorder it.
	// This matches the behavior of View::AddChildViewAtImpl and
	// otherwise will CHECK if the same view is added multiple times.
	if (child->view()->parent() == view_) {
	ReorderChildView(child, index);
	return;
	}
win.contentView.addChildView(a)
win.contentView.addChildView(b)   // b 在 a 上
win.contentView.addChildView(a)   // a 移到最上

BrowserWindow.setTopBrowserView 就是靠这条语义实现的(browser-window.ts:221-231):重排视图树,同时重排 JS 侧的 _browserViews 数组。两份记账必须同步,这正是 View 要维护 child_views_ 的原因(10.6.2)。

10.4.6 一个反直觉的后果:contentView 的 bounds 设了也没用

contentView 被 main_view_ 的填充布局管理:

root_view.cc:49

	main_view_->SetUseDefaultFillLayout(true);

填充布局意味着孩子的位置和尺寸由父容器决定,每次 Layout() 都会把 contentView 重置成 (0, 0, main_view_ 的尺寸)。所以:

const win = new BaseWindow({ width: 800, height: 600 })
win.contentView.getBounds()                    // { x: 0, y: 0, width: 800, height: 600 }
win.contentView.setBounds({ x: 100, y: 100, width: 10, height: 10 })
win.contentView.getBounds()                    // 立刻读:{ x: 100, y: 100, ... }
// 等下一次布局(窗口 resize、加子视图、show)之后
win.contentView.getBounds()                    // 又变回 { x: 0, y: 0, width: 800, height: 600 }

setBounds 在 contentView 上是"临时生效"的——它会成功写入,然后在下一个布局周期被覆盖。这是一个没有警告的陷阱:代码看起来对,行为在第一次 resize 之后变了。contentView 是容器,不是被布局的对象;要控制它的尺寸,得改窗口尺寸。

第二处容易混淆的是坐标系:

win.getContentBounds()    // { x: 100, y: 100, width: 800, height: 600 } —— 屏幕坐标
win.contentView.getBounds()  // { x: 0, y: 0, width: 800, height: 600 } —— 父容器坐标

BrowserWindow.getContentBounds() 走的是:

native_window_views.cc:936

	return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect();

屏幕坐标。 而 getBounds() 是"相对父容器"(view.md 原文:"The bounds of this View, relative to its parent")。窗口不在屏幕左上角时,两个 x 相差一个窗口位置。尺寸可以比,坐标不能比。

第三处是 View 与窗口的尺寸差异。getContentSize() 走的是另一行:

native_window_views.cc:945

	return content_view() ? content_view()->size() : gfx::Size();

在有菜单栏的平台上,content_view() 已经被 main_view_ 挤出菜单栏的高度,所以 getContentSize() 的高度也含了这次扣减。getSize()(窗口尺寸)与它的差值是"边框 + 菜单栏",不是单纯的边框——第 9 章 9.7 讲的"setBounds 差几个像素"在这里会差得更多。

这一节的实用结论只有一句:contentView 是布局的产物,不是布局的输入。想控制它,改窗口;想在它里面摆东西,用子视图的 setBounds。


10.5 WebContentsView:一个 WebContents 的可摆放形状

WebContentsView 只有 342 行,是本章四个类里最短的。但它做了三件别的类都没做的事:把 WebContents 变成一个可布局的矩形、在入树时自动认领归属窗口、把窗口的 windowControlsOverlay 换算成页面坐标。

10.5.1 构造函数:七个动作

electron_api_web_contents_view.cc:38-53

WebContentsView::WebContentsView(v8::Isolate* isolate,
								gin_helper::Handle<WebContents> web_contents)
	: View(web_contents->inspectable_web_contents()->GetView()),
	web_contents_(isolate, web_contents.ToV8()),
	api_web_contents_(web_contents->GetWeakPtr()) {
	set_delete_view(false);
	// See OnContentsBoundsChanging().
	web_contents->inspectable_web_contents()->GetView()->SetBoundsChangedCallback(
	base::BindRepeating(&WebContentsView::OnContentsBoundsChanging,
						weak_factory_.GetWeakPtr()));
	view()->SetProperty(
	views::kFlexBehaviorKey,
	views::FlexSpecification(views::MinimumFlexSizeRule::kScaleToMinimum,
							views::MaximumFlexSizeRule::kUnbounded));
	Observe(web_contents->web_contents());
}

动作一:View(web_contents->inspectable_web_contents()->GetView())。 基类构造拿到的是 InspectableWebContentsView*——注意不是 views::WebView,而是 InspectableWebContentsView。所以 new WebContentsView().view() 是个 InspectableWebContentsView,里面再包着两个 views::WebView。

这个"多包一层"的选择有明确理由:InspectableWebContentsView 同时管页面和 DevTools,它能按停靠策略分配空间(10.4.3)。如果直接暴露内层的 contents_web_view_,DevTools 就没地方停了。

动作二:web_contents_(isolate, web_contents.ToV8())。 又一个 v8::Global(10.2.3 的模式)。

动作三:api_web_contents_(web_contents->GetWeakPtr())。 弱引用,用来调 API。

动作四:set_delete_view(false)。 这是全章最关键的一行。

基类 View 的析构函数:

electron_api_view.cc:205-211

View::~View() {
	if (!view_)
	return;
	view_->RemoveObserver(this);
	if (delete_view_)
	view_.ClearAndDelete();
}

delete_view_ 默认 true(electron_api_view.h:84)。普通 View 的 view_ 是 new views::View(),归它所有,所以删。而 WebContentsView 的 view_ 是 InspectableWebContentsView,归 InspectableWebContents 所有(构造函数里那个 raw_ptr<InspectableWebContents> inspectable_web_contents_ 是 owner,注释写着"Owns us")。如果这里让基类删了,InspectableWebContents 析构时会二次释放。

一个 bool,划分了两种所有权模型:JS 造的视图归 JS 对象;内嵌 WebContents 的视图归 WebContents。

动作五:SetBoundsChangedCallback。 注册一个"我的 bounds 刚要变"的回调,用来在渲染尺寸更新之前把 windowControlsOverlay 的新矩形推给页面。

动作六:kFlexBehaviorKey。 这个属性被 views::FlexLayout 读。kScaleToMinimum + kUnbounded 的意思是:

  • 最小尺寸:可以缩到最小(不会因为内容而拒绝缩小)
  • 最大尺寸:无上限(可以撑满)

合起来就是"随便多大都行,给我多少我占多少"。因为 main_view_ 用的是 FillLayout(不是 Flex),这个属性在 BrowserWindow 里其实用不上——它只在用户给容器 setLayout({ orientation: 'horizontal' }) 时生效。

动作七:Observe(...)。 成为 content::WebContentsObserver,收 WebContentsDestroyed。

10.5.2 WebContentsDestroyed:视图还在,内容没了

electron_api_web_contents_view.cc:130-132

// :130-133
void WebContentsView::WebContentsDestroyed() {
	api_web_contents_ = nullptr;
	web_contents_.Reset();
}

只清两个引用,不动 view_。

于是出现一个中间态:WebContentsView 的 JS 对象还在,view_(InspectableWebContentsView)还在树上,但 webContents 属性变成 null:

electron_api_web_contents_view.cc:61-65

// :61-67
gin_helper::Handle<WebContents> WebContentsView::GetWebContents(
	v8::Isolate* isolate) {
	if (api_web_contents_)
	return gin_helper::CreateHandle(isolate, api_web_contents_.get());
	else
	return {};
}

返回空 handle → JS 侧得到 null。

base-window.md:81-85

const view = new WebContentsView()
win.contentView.addChildView(view)
view.webContents.close()
view.webContents          // null
view.getBounds()          // 还在,视图还在树上

这个状态是合法的,也是危险的。 合法是因为视图本身仍然可以被布局、被隐藏、被移除;危险是因为任何假设 view.webContents 非空的代码都会崩。

BrowserWindow 的处理是"网页没了就关窗口"(10.3.4),WebContentsView 的处理是"什么都不做"。同一个事件,两种策略,因为一个是"唯一的网页",一个是"可能有很多个的网页之一"。

10.5.3 addChildView 会自动认领窗口

这是 WebContentsView 最"聪明"也最隐晦的行为:

electron_api_web_contents_view.cc:135-142

// :135-152
void WebContentsView::OnViewAddedToWidget(views::View* observed_view) {
	DCHECK_EQ(observed_view, view());
	NativeWindow* native_window = NativeWindow::FromWidget(view()->GetWidget());
	if (!native_window)
	return;
	// We don't need to call SetOwnerWindow(nullptr) in OnViewRemovedFromWidget
	// because that's handled in the WebContents dtor called prior.
	api_web_contents_->SetOwnerWindow(native_window);
	native_window->AddDraggableRegionProvider(this);
	StopObservingWindow();
	observed_window_ = native_window->GetWeakPtr();
	native_window->AddObserver(this);
	ApplyBorderRadius();
	if (HasLivePage())
	ScheduleWindowControlsOverlayUpdate();
}

六个动作,触发时机是"这个视图被加进了一个有 Widget 的树"。也就是说:

view.md:13-17

const win = new BaseWindow()
const view = new WebContentsView()
view.webContents.getOwnerBrowserWindow()   // null(还没入树)
win.contentView.addChildView(view)
view.webContents.getOwnerBrowserWindow()   // 还是一个 BaseWindow,不是 BrowserWindow

用户不需要(也无法)手动指定归属窗口。 只要 addChildView,窗口归属就自动建立。

这条设计的动机是"少一个必填参数"。如果 API 是 new WebContentsView({ window }),就会出现"先造视图再造窗口"的顺序问题(无法支持),以及"窗口变了但视图没跟着变"的一致性问题。用 OnViewAddedToWidget 这个 views 的钩子,归属关系永远等于"当前在谁的树里",天然不会不一致。

NativeWindow::FromWidget 是这条链的起点:

native_window.cc:310-314

NativeWindow* NativeWindow::FromWidget(const views::Widget* widget) {
	DCHECK(widget);
	return static_cast<NativeWindow*>(
	widget->GetNativeWindowProperty(kNativeWindowKey.c_str()));
}

而 kNativeWindowKey 是在两个平台的构造函数里写进去的:

native_window_views.cc:342

	widget()->SetNativeWindowProperty(kNativeWindowKey.c_str(), this);

native_window_mac.mm:196

	widget()->SetNativeWindowProperty(kNativeWindowKey.c_str(), this);

键名是:

native_window.h:506-507

	static inline constexpr base::cstring_view kNativeWindowKey =
	"__ELECTRON_NATIVE_WINDOW__";

一个字符串,把 views::Widget 和 electron::NativeWindow 缝在一起。 views 层不认识 NativeWindow(它是 Chromium 的类),所以只能挂一个 void* 属性。这是跨层通信的最后手段,也是唯一手段。

OnViewRemovedFromWidget 的不对称值得注意:

electron_api_web_contents_view.cc:154-160

// :154-164
void WebContentsView::OnViewRemovedFromWidget(views::View* observed_view) {
	DCHECK_EQ(observed_view, view());
	StopObservingWindow();
	NativeWindow* native_window = NativeWindow::FromWidget(view()->GetWidget());
	if (!native_window)
	return;
	native_window->RemoveDraggableRegionProvider(this);
}

注释(第 142-143 行)解释了为什么这里不 SetOwnerWindow(nullptr):WebContents 析构时会自己摘掉 NativeWindowRelay,所以视图被移除时不需要额外清理。

但这句话有个漏洞:如果视图被移除而 WebContents 还活着(比如 win.contentView.removeChildView(view) 但 view 变量还在作用域里),那么 owner_window_ 就still 指着那个窗口。这段代码不清理它。

这个行为是有意的还是疏忽?从注释看是"有意的假设":移除视图通常意味着要销毁它。但代码允许不销毁。10.7.4 会把这种情况列进"三个答案不一致"的表里。

10.5.4 三个 API 与它们的副作用链

setBackgroundColor:

electron_api_web_contents_view.cc:69-76

// :69-81
void WebContentsView::SetBackgroundColor(std::optional<WrappedSkColor> color) {
	View::SetBackgroundColor(color);
	if (api_web_contents_) {
	api_web_contents_->SetBackgroundColor(color);
	// Also update the web preferences object otherwise the view will be reset
	// on the next load URL call
	auto* web_preferences =
		WebContentsPreferences::From(api_web_contents_->web_contents());
	if (web_preferences) {
	web_preferences->SetBackgroundColor(color);
	}
	}
}

写三处:视图的背景、当前 WebContents 的背景、WebContentsPreferences 里的记录。

注释解释了第三处为什么必须有:"否则下次 loadURL 时视图会被重置"。机制是:每次导航都会从 WebPreferences 重新应用背景色(因为新文档可能是不同 origin,需要重新决定背景)。如果只改了当前值没改偏好记录,导航后颜色就回退了。

这是一个"缓存与真值"的经典问题:WebContentsPreferences 是真值,WebContents 的当前背景是缓存。改缓存不改真值,下次刷新就丢。

同样的问题在 BrowserWindow::SetBackgroundColor 里也存在:

electron_api_browser_window.cc:251-264

void BrowserWindow::SetBackgroundColor(const std::string& color_name) {
	BaseWindow::SetBackgroundColor(color_name);
	SkColor color = ParseCSSColor(color_name).value_or(SK_ColorWHITE);
	if (api_web_contents_) {
	api_web_contents_->SetBackgroundColor(color);
	// Also update the web preferences object otherwise the view will be reset
	// on the next load URL call
	auto* web_preferences =
		WebContentsPreferences::From(api_web_contents_->web_contents());
	if (web_preferences) {
	web_preferences->SetBackgroundColor(color);
	}
	}
}

两处代码几乎一样,注释也一样。这是复制粘贴留下的技术债,也是"BrowserWindow 的 SetBackgroundColor 应该直接转发给它的 WebContentsView"这个重构还没做的证据。

setBorderRadius:

electron_api_web_contents_view.cc:83-89

// :83-93
void WebContentsView::SetBorderRadius(int radius) {
	View::SetBorderRadius(radius);
	ApplyBorderRadius();
}
void WebContentsView::ApplyBorderRadius() {
	if (border_radius().has_value() && api_web_contents_ && view()->GetWidget()) {
	auto* view = api_web_contents_->inspectable_web_contents()->GetView();
	view->SetCornerRadii(gfx::RoundedCornersF(border_radius().value()));
	}
}

这里覆盖了基类的 ApplyBorderRadius,因为基类的实现是"给我自己这个 views::View 设裁剪路径":

electron_api_view.cc:496-503

// shell/browser/api/electron_api_view.cc:496-521(节选)
void View::ApplyBorderRadius() {
	if (!border_radius_.has_value() || !view_)
	return;
	auto size = view_->bounds().size();
	...
	if (radius > 0 && size.width() >= 32 && size.height() >= 32) {
	auto builder = ash::RoundedRectCutoutPathBuilder(gfx::SizeF(size));
	builder.CornerRadius(radius);
	view_->SetClipPath(builder.Build());
	} else {
	view_->SetClipPath(SkPath());
	}
}

SetClipPath 是 CPU 侧的裁剪,对普通视图够用;但对一个承载渲染进程输出的视图,CPU 裁剪会导致合成器每次都多做一步。所以 WebContentsView 走另一条路——把圆角交给 Chromium 的渲染表面:

inspectable_web_contents_view.cc:123-140

void InspectableWebContentsView::SetCornerRadii(
	const gfx::RoundedCornersF& corner_radii) {
	// WebView won't exist for offscreen rendering.
	if (contents_web_view_) {
	contents_web_view_->holder()->SetNativeViewCornerRadii(corner_radii);
#if defined(USE_AURA)
	// Aura calls SetIsFastRoundedCorner(true) which clips each tile separately.
	// This creates a jagged edge at fractional DPI if the view is taller than
	// one tile, so we use the slow method for a smooth edge at the cost of
	// an extra render surface.
	if (auto* native_view = contents_web_view_->holder()->native_view()) {
	if (auto* layer = native_view->layer())
		layer->SetIsFastRoundedCorner(false);
	}
#endif
	}
}

注释里那段是本章最值得记的性能细节之一:Aura 平台的"快速圆角"是逐 tile 裁剪的,视图高度超过一个 tile 且 DPI 是小数时,接缝处会出现锯齿。 Electron 选择关掉快速路径,代价是多一个 render surface。

这是一个"看起来只是设个圆角"的 API 背后的真实权衡:要么快但边缘毛糙,要么慢但干净。Electron 选了后者,因为用户抱怨的是视觉缺陷,不是这一帧多花了 0.2ms。

webContents 是只读属性,10.5.2 已讲。

10.5.5 构造入口的四层校验

WebContentsView::New 比 BaseWindow::New 多做了几道参数检查:

electron_api_web_contents_view.cc:257-264

// :257-311(节选)
gin_helper::WrappableBase* WebContentsView::New(gin::Arguments* const args) {
	v8::Isolate* const isolate = args->isolate();
	gin_helper::Dictionary web_preferences;
	v8::Local<v8::Value> existing_web_contents_value;
	{
	v8::Local<v8::Value> options_value;
	if (args->GetNext(&options_value)) {
	gin_helper::Dictionary options;
	if (!gin::ConvertFromV8(isolate, options_value, &options)) {
		args->ThrowTypeError("options must be an object");
		return nullptr;
	}

它验证了四层:options 是对象 → webPreferences 是对象 → webContents 是 WebContents → 那个 WebContents 还没被别的窗口占用:

electron_api_web_contents_view.cc:286-289

// :286-290
		if (existing_web_contents->owner_window() != nullptr) {
		args->ThrowTypeError(
			"options.webContents is already attached to a window");
		return nullptr;
		}

"一个 WebContents 只能属于一个窗口"是由这道检查保证的,不是由数据结构保证的。owner_window_ 是个裸弱指针,没有唯一性约束——约束在构造函数里。

然后是一个容易被忽略的默认值:

electron_api_web_contents_view.cc:295-298

// :295-298
	if (web_preferences.IsEmpty())
	web_preferences = gin_helper::Dictionary::CreateEmpty(isolate);
	if (!web_preferences.Has(options::kShow))
	web_preferences.Set(options::kShow, false);

new WebContentsView() 的页面默认不显示。 对比 BrowserWindow 的构造(10.3.1 阶段 3)给的是 show: true。

为什么相反?因为 WebContentsView 造出来之后要先 setBounds 再 addChildView,如果一开始就 show: true,Chromium 会用一个默认尺寸(800×600)启动渲染,然后你 setBounds 又要重新布局一次。先不显示、布好局再显示,省一次全量渲染。

而 BrowserWindow 在构造末尾就 InitFromOptions(含 Show),此时尺寸已经定了,所以直接 show: true 合理。

两个类的默认值差异,反映的是"什么时候尺寸确定"这件事。

10.5.6 windowControlsOverlay 的坐标换算

这是 WebContentsView 里唯一一处几何计算,也是最容易写错的:

electron_api_web_contents_view.cc:202-209

// :202-217
void WebContentsView::SendWindowControlsOverlay() {
	window_controls_overlay_update_pending_ = false;
	if (!api_web_contents_ || !observed_window_)
	return;
	const auto bounding_rect = observed_window_->GetWindowControlsOverlayRect();
	if (!bounding_rect)
	return;
	views::View* window_view = observed_window_->GetContentsView();
	if (!window_view || !window_view->Contains(view()))
	return;
	gfx::Rect local_rect =
	views::View::ConvertRectToTarget(window_view, view(), *bounding_rect);
	local_rect.Intersect(view()->GetLocalBounds());
	web_contents()->UpdateWindowControlsOverlay(local_rect);
}

五步:取窗口的 overlay 矩形(窗口坐标系)→ 检查自己在不在树里 → 转到自己的坐标系 → 与自己的 bounds 求交 → 推给页面。

第四步的 Intersect 是关键。env(titlebar-area-*) 这组 CSS 环境变量告诉页面"标题栏按钮占了哪块"。如果一个 WebContentsView 只覆盖窗口的一部分(比如右侧面板),它不该知道整个标题栏的位置——只该知道自己被标题栏遮住的那部分。

electron_api_web_contents_view.cc:213-215

// :213-215
	gfx::Rect local_rect =
	views::View::ConvertRectToTarget(window_view, view(), *bounding_rect);
	local_rect.Intersect(view()->GetLocalBounds());

不求交的话,一个位于 x: 600 的视图会收到一个 x: 0 的 overlay 矩形,页面以为标题栏在自己左边缘——env(titlebar-area-x) 完全错。

这个函数只有 16 行,但它是在多视图窗口里让 titleBarOverlay 正确工作的唯一保证。

再看调度:

electron_api_web_contents_view.cc:190-196

// :190-197
void WebContentsView::ScheduleWindowControlsOverlayUpdate() {
	if (window_controls_overlay_update_pending_)
	return;
	window_controls_overlay_update_pending_ = true;
	base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
	FROM_HERE, base::BindOnce(&WebContentsView::SendWindowControlsOverlay,
								weak_factory_.GetWeakPtr()));
}

去抖 + 延到下一轮任务。理由写在 UpdateWindowControlsOverlay 的注释里:

// :182-188
// NativeWindowObserver. This fires from inside the frame view's layout, before
// the client area (and so this view) has been laid out, so defer until the
// current layout pass has finished to avoid clipping against stale bounds.

"在布局过程中算坐标,用的是旧 bounds" —— 这是所有 UI 框架的通病。解法统一是"延到布局之后"。这里用 PostTask 而不是 PostTaskForCurrentThread,是因为 SequencedTaskRunner 保证顺序但不保证线程,而 views 的很多东西要求 UI 线程。GetCurrentDefault() 在当前线程是 UI 线程时返回的就是 UI 线程的 runner。


10.6 View:容器的最小公倍数

View 是这套体系的地基。它只有 11 个方法,但每一个都藏着一段历史。

10.6.1 十一个方法

electron_api_view.cc:604-619

void View::BuildPrototype(v8::Isolate* isolate,
						v8::Local<v8::FunctionTemplate> prototype) {
	prototype->SetClassName(gin::StringToV8(isolate, "View"));
	gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
	.SetMethod<&View::AddChildViewAt>("addChildView")
	.SetMethod<&View::RemoveChildView>("removeChildView")
	.SetProperty<&View::GetChildren>("children")
	.SetMethod<&View::SetBounds>("setBounds")
	.SetMethod<&View::GetBounds>("getBounds")
	.SetMethod<&View::SetBackgroundColor>("setBackgroundColor")
	.SetMethod<&View::SetBorderRadius>("setBorderRadius")
	.SetMethod<&View::SetBackgroundBlur>("setBackgroundBlur")
	.SetMethod<&View::SetLayout>("setLayout")
	.SetMethod<&View::SetVisible>("setVisible")
	.SetMethod<&View::GetVisible>("getVisible");
}

十一个,其中 children 是属性。

注意 setLayout 在列表里,但不在文档里。 view.md 通篇没有 setLayout,全仓库 grep -rn "setLayout" typings/ docs/ lib/ 只命中三处无关结果(都是 setLayoutZoomLevelLimits)。

原因是 Electron 的 TypeScript 声明是从 docs/api 生成的(script/create-api-json.mjs 解析文档产出 api.json,再由它生成 .d.ts)。文档里没有的方法,类型里也没有。于是 setLayout 成了一个"能用但没人知道、TS 会报错"的方法。

这是一个真实存在的 API 表面不一致。它之所以没被修,大概因为 setLayout 是给 <webview> 内部和 BrowserView 兼容层用的,不是给终端用户的。

10.6.2 child_views_:为什么原生树之外还要记一份

electron_api_view.h:88

	using ChildPair = std::pair<raw_ptr<views::View>, v8::Global<v8::Object>>;
	...
	std::vector<ChildPair> child_views_;

每个孩子存两样:原生指针(弱)+ JS 对象(强)。

为什么两样都要?

原生指针用于 views 层的操作(RemoveChildView、ReorderChildView)。 JS 对象用于两件事:children 属性返回值,以及防止孩子被 GC。

第二件事是重点。考虑:

win.contentView.addChildView(new View())   // 没有保存引用

如果 child_views_ 只存 views::View*,那个临时 View 的 JS 对象立刻就会被 GC。GC 时会走 SecondWeakCallback → delete wrappable → api::View 析构 → view_.ClearAndDelete()(因为 delete_view_ == true)→ 原生视图被删,但 views::View 的父节点还记着它 → 下次布局或绘制时崩。

存 v8::Global 就让 JS 对象的生命周期跟着父视图走。这也是为什么 RemoveChildView 必须先从 child_views_ 里 erase,再调 view_->RemoveChildView:

electron_api_view.cc:287-294

// :287-307
void View::RemoveChildView(gin_helper::Handle<View> child) {
	if (!view_)
	return;
	const auto it =
	std::ranges::find_if(child_views_, [&](const ChildPair& child_view) {
		return child_view.first == child->view();
	});
	if (it != child_views_.end()) {
#if BUILDFLAG(IS_MAC)
	ScopedCAActionDisabler disable_animations;
#endif
	// Remove from child_views first so that OnChildViewRemoved doesn't try to
	// remove it again
	child_views_.erase(it);
	// It's possible for the child's view to be invalid here
	// if the child's webContents was closed or destroyed.
	if (child->view())
	view_->RemoveChildView(child->view());
	}
}

注释直说了:"先从 child_views_ 里移除,这样 OnChildViewRemoved 不会试图再移除一次。"

因为 view_->RemoveChildView 会触发 views::ViewObserver::OnChildViewRemoved,而 View 实现了它:

electron_api_view.cc:558-560

// :558-562
void View::OnChildViewRemoved(views::View* observed_view, views::View* child) {
	std::erase_if(child_views_, [child](const ChildPair& child_view) {
	return child_view.first == child;
	});
}

同一个移除动作,两个入口:JS 主动调 removeChildView,或原生侧(比如 WebContentsView 被析构)自己摘孩子。前者必须先手删再调原生,后者靠观察者回调兜底。如果顺序反了,erase_if 会在 it 已经失效之后再操作一次——虽然 erase_if 是幂等的,但 views::View::RemoveChildView 第二次会对一个已经不在列表里的视图做操作,CHECK 可能失败。

ScopedCAActionDisabler 是 macOS 专有的一段:

#if BUILDFLAG(IS_MAC)
	ScopedCAActionDisabler disable_animations;
#endif

CoreAnimation 给所有 layer 增删加了隐式动画(默认 0.25 秒淡入淡出)。加/删子视图时,那层动画会让新视图"渐显"——对一个本该瞬间出现的 UI 元素,这是明显的瑕疵。同样的处理在 AddChildViewAt 里也有一份(第 272-283 行),注释里还留了个 TODO,说这本该由 remote_cocoa 或 views 处理,Electron 不该自己管。

10.6.3 ReorderChildView 的 rotate

electron_api_view.cc:213-220

// :213-234
void View::ReorderChildView(gin_helper::Handle<View> child, size_t index) {
	view_->ReorderChildView(child->view(), index);
	const auto i =
	std::ranges::find_if(child_views_, [&](const ChildPair& child_view) {
		return child_view.first == child->view();
	});
	DCHECK(i != child_views_.end());
	// If |view| is already at the desired position, there's nothing to do.
	const auto pos = std::next(
	child_views_.begin(),
	static_cast<ptrdiff_t>(std::min(index, child_views_.size() - 1)));
	if (i == pos)
	return;
	if (pos < i) {
	std::rotate(pos, i, std::next(i));
	} else {
	std::rotate(i, std::next(i), std::next(pos));
	}
}

两行 std::rotate,方向相反:

  • pos < i(往前移):把 [pos, i) 整体的最后一个换成 i,等价于"把 i 插到 pos,其余后移"。
  • pos > i(往后移):把 i 移到 pos,中间的往前挪。

std::rotate(first, middle, last) 的语义是"把 [first, last) 旋转,使 middle 成为新的首元素"。第一分支 rotate(pos, i, next(i)) 在 [pos, i+1) 上旋转,让 i 到最前——中间元素整体后移一位。正确。

std::min(index, child_views_.size() - 1) 这行有个隐患:如果 child_views_ 为空,size() - 1 会下溢成 SIZE_MAX,min 返回 index。但进到这里说明 i != end(),也就是至少有一个元素,所以不会走那个分支。

这类"看起来会崩但其实不会"的代码,是 C++ 里最难审的一类。 它依赖一个不明显的调用前提。

10.6.4 setLayout:把 JS 回调当布局管理器

// :427-470(节选)
void View::SetLayout(v8::Isolate* isolate, v8::Local<v8::Object> value) {
	if (!view_)
	return;
	gin_helper::Dictionary dict(isolate, value);
	LayoutCallback calculate_proposed_layout;
	if (dict.Get("calculateProposedLayout", &calculate_proposed_layout)) {
	view_->SetLayoutManager(std::make_unique<JSLayoutManager>(
		std::move(calculate_proposed_layout)));
	} else {
	auto* layout =
		view_->SetLayoutManager(std::make_unique<views::FlexLayout>());
	views::LayoutOrientation orientation;
	if (dict.Get("orientation", &orientation))
	layout->SetOrientation(orientation);

两条路:给一个 JS 函数,或者给一堆 flex 参数。前者对应:

// :180-196
class JSLayoutManager : public views::LayoutManagerBase {
	public:
	explicit JSLayoutManager(LayoutCallback layout_callback)
	: layout_callback_(std::move(layout_callback)) {}
	// views::LayoutManagerBase
	views::ProposedLayout CalculateProposedLayout(
	const views::SizeBounds& size_bounds) const override {
	v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
	v8::HandleScope handle_scope(isolate);
	return layout_callback_.Run(size_bounds);
	}
	private:
	LayoutCallback layout_callback_;
};

在布局过程中调用 JS。 这是整个 View 系统里最危险的一处设计,因为:

  1. CalculateProposedLayout 是 const 的,但 Run() 会执行任意 JS。
  2. 布局可能在一帧里被调用多次(嵌套布局、InvalidateLayout 连锁)。
  3. JS 回调里如果调了 setBounds,会触发新的 InvalidateLayout,形成循环。

Electron 没有防护。它只做了最小限度的隔离:v8::HandleScope。如果回调抛异常,layout_callback_.Run() 会把异常吞掉(base::RepeatingCallback 不传播异常到 C++),返回一个默认构造的 views::ProposedLayout——也就是所有孩子都在 (0,0,0,0)。

结果是"整个容器塌成一个点",没有任何错误日志。 这是 setLayout 只能当内部 API 用的真正原因。

10.6.5 setBounds 的动画与隐藏成本

setBounds 有三个分支:

// :325-419(结构)
	if (!animate) {
	view_->SetBoundsRect(bounds);       // ① 同步,立即生效
	return;
	}
	...
	if (bounds.size() == current_bounds.size()) {
	// ② 只移动:直接对 view_ 做 bounds 动画
	return;
	}
	// ③ 尺寸也变:立即撑到 max_size,再用 layer 的 clip rect 做"逐渐露出"

第 ③ 分支的注释解释了为什么不直接动画 bounds:

// :388-398
	// if the view's size is smaller than the target size, we need to set the
	// view's bounds immediatley to the new size (not position) and set the
	// layer's clip rect to animate from there.
	if (view_->width() < bounds.width() || view_->height() < bounds.height()) {
	view_->SetBoundsRect(max_size);
	if (layer) {
	layer->SetClipRect(
		gfx::Rect(0, 0, current_bounds.width(), current_bounds.height()));
	}
	}

因为 views::View 的 bounds 变化会触发重新布局(孩子位置重算)。每帧改一次 bounds,孩子就跟着抖一次。所以"一次设到最终值、让布局只跑一遍,用 clip rect 做视觉过渡"。

注释最后还说明了 clip 为什么必须单独动画:

// :414-418
	.SetClipRect(
		view_, target_size,
		easing);  // We have to set the clip rect independently of the
					// bounds, because animating the bounds of the layer
					// will not animate the underlying view's bounds.

"动画 layer 的 bounds 不会动画 view 的 bounds"——前者是合成器属性,后者是 C++ 里一个 gfx::Rect。

而这一切的前提是 GetLayer():

// :309-323
ui::Layer* View::GetLayer() {
	if (!view_)
	return nullptr;
	if (view_->layer())
	return view_->layer();
	view_->SetPaintToLayer();
	ui::Layer* layer = view_->layer();
	layer->SetFillsBoundsOpaquely(false);
	return layer;
}

调用它会给视图创建一个独立合成层,并且标记为"非不透明"。 两个后果都是永久的:内存多一份、混合多一遍。所以 setBounds({ animate: true }) 不是一次性开销——一个"偶尔动一下"的视图,从此永久失去了不透明合成路径。

10.6.6 圆角的两个前提

// :496-521
void View::ApplyBorderRadius() {
	if (!border_radius_.has_value() || !view_)
	return;
	auto size = view_->bounds().size();
	// Restrict border radius to the constraints set in the path builder class.
	// If the constraints are exceeded, the builder will crash.
	int radius;
	{
	float r = border_radius_.value() * 1.f;
	r = std::min(r, size.width() / 2.f);
	r = std::min(r, size.height() / 2.f);
	r = std::max(r, 0.f);
	radius = std::floor(r);
	}
	// RoundedRectCutoutPathBuilder has a minimum size of 32 x 32.
	if (radius > 0 && size.width() >= 32 && size.height() >= 32) {
	auto builder = ash::RoundedRectCutoutPathBuilder(gfx::SizeF(size));
	builder.CornerRadius(radius);
	view_->SetClipPath(builder.Build());
	} else {
	view_->SetClipPath(SkPath());
	}
}

两个"不说就会崩"的约束,注释都写了:

  1. 半径必须 ≤ 宽高的一半,否则路径构建器崩。所以有 std::min 两次。
  2. 尺寸必须 ≥ 32×32,否则构建器崩。所以有那个 if。

第二条意味着:一个 100×20 的视图设 setBorderRadius(10) 会静默失败(走 else 分支,清空裁剪路径)。没有警告,没有异常。

而且它是在 OnViewBoundsChanged 里重算的:

// :548-551
void View::OnViewBoundsChanged(views::View* observed_view) {
	ApplyBorderRadius();
	Emit("bounds-changed");
}

所以一个视图被缩到 20px 高时,圆角会自动消失——这解释了"为什么我的圆角在某些布局下不见了"。

Emit("bounds-changed") 在同一行之后。先算圆角再发事件,顺序是刻意的:监听器里如果要读视觉状态,应该读到已经修正过的。

10.6.7 OnViewIsDeleting:view_ 变 null 之后

// :553-556
void View::OnViewIsDeleting(views::View* observed_view) {
	DCHECK_EQ(observed_view, view_);
	view_ = nullptr;
}

当原生视图被销毁(不是被 JS 销毁,而是被原生侧销毁),观察者回调把 view_ 置空。之后所有方法都要检查 if (!view_) return;。

这就是为什么 AddChildViewAt 开头有这么一段:

// :238-243
	// TODO(nornagon): !view_ is only for supporting the weird case of
	// WebContentsView's view being deleted when the underlying WebContents is
	// destroyed (on non-Mac). We should fix that so that WebContentsView always
	// has a View, possibly a wrapper view around the underlying platform View.
	if (!view_)
	return;

这个 TODO 是整章最有价值的一条"未修复缺陷"记录。 它说清楚了:

  • WebContentsView 的 view_ 会在 WebContents 销毁时被删掉(非 macOS 平台)。
  • 删掉之后 WebContentsView 这个 JS 对象仍然存在,但已经不能用了。
  • 正确做法是包一层 wrapper view,让 view_ 永不失效。

这个缺陷的后果是:在非 macOS 平台上,view.webContents.close() 之后,view.setBounds()、view.addChildView()、view.setBackgroundColor() 全部变成静默空操作。

base-window.md:81-85

const view = new WebContentsView()
win.contentView.addChildView(view)
view.webContents.close()
view.setBounds({ x: 0, y: 0, width: 1, height: 1 })   // 什么也没发生
view.getBounds()    // 返回 {}(因为 !view_ 时 GetBounds 返回空矩形)

GetBounds 的空分支:

// :421-425
gfx::Rect View::GetBounds() const {
	if (!view_)
	return {};
	return view_->bounds();
}

返回 {} 而不是抛错。 一个 0×0 的矩形,和"真的被设成 0×0"没法区分。

macOS 上为什么不一样?因为 macOS 的 InspectableWebContentsView 生命周期由 views::Widget 管,WebContents 销毁不会连带删视图。一个跨平台的 bug,在两个平台上表现出两种不同程度的错误,是 Electron 里很常见的一类问题。


10.7 一个 WebContents 属于哪个窗口:三个答案

第 9 章的"尾巴二"在这里收。问题是:给一个 WebContents,怎么知道它在哪个窗口里?

有三个答案,来自三条不同的路径。

10.7.1 答案一:owner_window_(弱指针)

// shell/browser/api/electron_api_web_contents.h(经 grep 确认存在)
	base::WeakPtr<NativeWindow> owner_window_;

写入点是唯一的:

electron_api_web_contents.cc:3061-3081

void WebContents::SetOwnerWindow(content::WebContents* web_contents,
								NativeWindow* owner_window) {
	if (owner_window_) {
	owner_window_->RemoveBackgroundThrottlingSource(this);
	}
	if (owner_window) {
	owner_window_ = owner_window->GetWeakPtr();
	NativeWindowRelay::CreateForWebContents(web_contents,
											owner_window->GetWeakPtr());
	owner_window_->AddBackgroundThrottlingSource(this);
	} else {
	owner_window_ = nullptr;
	web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
	}
	auto* osr_wcv = GetOffScreenWebContentsView();
	if (osr_wcv)
	osr_wcv->SetNativeWindow(owner_window);
}

一次赋值,四个副作用:

  1. 从旧窗口的"后台节流源"集合里摘掉自己。
  2. 存弱指针。
  3. 在 content::WebContents 上挂一个 WebContentsUserData(NativeWindowRelay)。
  4. 加进新窗口的节流源集合。

第 4 条的语义值得展开。AddBackgroundThrottlingSource 把一个 BackgroundThrottlingSource* 加进窗口的集合:

native_window.cc:796-801

void NativeWindow::AddBackgroundThrottlingSource(
	BackgroundThrottlingSource* source) {
	auto result = background_throttling_sources_.insert(source);
	DCHECK(result.second) << "Added already stored BackgroundThrottlingSource.";
	UpdateBackgroundThrottlingState();
}

窗口的"是否允许后台节流"是所有源都允许才允许(第 9 章讲过这个 AND 集合)。所以一个窗口里有 3 个 WebContentsView,只要有 1 个设了 setBackgroundThrottling(false),整个窗口的页面都不节流。

这是"多视图窗口"带来的语义变化:在"一窗口一网页"的时代,节流开关属于窗口;现在它是多个网页的公共决议。

10.7.2 答案二:NativeWindowRelay(WebContentsUserData)

native_window.h:640-658

class NativeWindowRelay
	: public content::WebContentsUserData<NativeWindowRelay> {
	public:
	static void CreateForWebContents(content::WebContents*,
								base::WeakPtr<NativeWindow>);
	~NativeWindowRelay() override;
	NativeWindow* GetNativeWindow() const { return native_window_.get(); }
	WEB_CONTENTS_USER_DATA_KEY_DECL();
	private:
	friend class content::WebContentsUserData<NativeWindow>;
	explicit NativeWindowRelay(content::WebContents* web_contents,
							base::WeakPtr<NativeWindow> window);
	base::WeakPtr<NativeWindow> native_window_;
};

WebContentsUserData<T> 是 Chromium 的机制:往 content::WebContents 上挂一个定制数据,键是类型,值是一个 unique_ptr<T>,跟着 WebContents 一起死。

为什么不直接用 owner_window_? 因为 owner_window_ 存在 api::WebContents 上,而 api::WebContents 是 V8 包装对象,可能被 GC,也可能在 WebContents 还活着的时候就被 Destroy()。而 NativeWindowRelay 挂在底层的 content::WebContents 上,只要 WebContents 活着它就活着。

两条路径的生命周期锚点不同:一条锚在 JS 对象,一条锚在 Chromium 对象。

10.7.3 答案三:getOwnerBrowserWindow()

// :4853-4859
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
	v8::Isolate* isolate) const {
	if (owner_window())
	return BrowserWindow::From(isolate, owner_window());
	else
	return v8::Null(isolate);
}

它基于答案一,然后做一次转换:

electron_api_browser_window.cc:365-373

v8::Local<v8::Value> BrowserWindow::From(v8::Isolate* isolate,
										NativeWindow* native_window) {
	if (native_window != nullptr) {
	if (auto* base = FromWeakMapID(isolate, native_window->base_window_id()))
	return base->GetWrapper();
	}
	return v8::Null(isolate);
}

注意它是从 NativeWindow 的 id 反查 api::BaseWindow,再返回 GetWrapper()。返回的 v8::Local<v8::Value> 可能是 BrowserWindow 也可能是 BaseWindow——函数名说 BrowserWindow,实际不做类型检查。

const win = new BaseWindow()
const view = new WebContentsView()
win.contentView.addChildView(view)
view.webContents.getOwnerBrowserWindow()   // 一个 BaseWindow 实例,不是 null

这是个命名与行为不符的地方。 一个 BaseWindow 里的 WebContents,getOwnerBrowserWindow() 返回那个 BaseWindow。

BrowserWindow.fromWebContents 直接转发给它:

browser-window.ts:99-101

BrowserWindow.fromWebContents = (webContents: WebContents) => {
	return webContents.getOwnerBrowserWindow();
};

所以 BrowserWindow.fromWebContents(win.webContents) 对一个 BaseWindow 里的网页也会返回非 null。类型声明说是 BrowserWindow | null,实际可能是一个 BaseWindow。

10.7.4 三个答案不一致的四种状态

现在可以给出完整性条件了。定义:

  • A = webContents.ownerWindow(答案一,弱指针非空)
  • B = NativeWindowRelay::FromWebContents(...)(答案二,UserData 存在)
  • C = getOwnerBrowserWindow() 返回值非 null(答案三)

理论上 A、B 同生共死(SetOwnerWindow 同时写两者)。实际有四种裂缝:

状态ABC怎么产生
正常✓✓✓addChildView 入树
窗口先死✗✓✗NativeWindow 析构,弱指针失效但 UserData 还在
视图被移除✓✓✓removeChildView(10.5.3 说的"不清理")
包装被 GC—✓—无法观测(api::WebContents 都没了)

第二行是最常见的:窗口关了,owner_window_ 因为弱指针自动变 null,但 content::WebContents 可能还活着(WebContentsView 被别处持有),所以 NativeWindowRelay 还在,GetNativeWindow() 返回 null(因为 relay 里也是弱指针)。

// :4752-4766
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
	if (IsOffScreen() && wc == web_contents()) {
	auto* relay = NativeWindowRelay::FromWebContents(web_contents());
	if (relay) {
	auto* owner_window = relay->GetNativeWindow();
	return owner_window ? owner_window->GetSize() : gfx::Size();
	}
	}
	return {};
}

这段代码演示了正确的用法:先 FromWebContents 拿 relay,再 GetNativeWindow(),再判空。 三步,因为 relay 的存在和窗口的存在是两件事。

第三行是 10.5.3 提到的漏洞:OnViewRemovedFromWidget 不调 SetOwnerWindow(nullptr)。所以视图被移出窗口后,webContents.getOwnerBrowserWindow() 仍然返回那个窗口——一个已经不在它里面显示的窗口。

const win = new BaseWindow()
const view = new WebContentsView()
win.contentView.addChildView(view)
win.contentView.removeChildView(view)
view.webContents.getOwnerBrowserWindow() === win    // true,但它已经不在 win 里了

这个行为对不对?从"归属"的语义看是错的;从"曾经属于"的语义看是对的。Electron 没有为这个状态定义语义,代码和文档都没提。

实际上这个"漏洞"可能是必要的:removeChildView 之后用户通常要 addChildView 到另一个窗口,如果中间把 owner_window_ 清空,会触发一次"移除节流源 + 重加"的抖动。留着不清,等价于"延迟到下一次 SetOwnerWindow 时再切换"。

10.7.5 谁会调 SetOwnerWindow

四个入口,前三个在 C++ 内部,最后一个是给 JS 的:

第一,BrowserWindow 构造时(electron_api_browser_window.cc:87):

	// Associate with BrowserWindow.
	web_contents->SetOwnerWindow(window());

第二,WebContentsView::OnViewAddedToWidget(electron_api_web_contents_view.cc:144):

	api_web_contents_->SetOwnerWindow(native_window);

第三,WebContents::SetEmbedder,<webview> 专用(:4875-4885):

void WebContents::SetEmbedder(const WebContents* embedder) {
	if (embedder) {
	NativeWindow* owner_window = nullptr;
	auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
	if (relay) {
	owner_window = relay->GetNativeWindow();
	}
	if (owner_window)
	SetOwnerWindow(owner_window);

第四,webContents._setOwnerWindow(...),这是唯一暴露给 JS 的入口:

electron_api_web_contents.cc:5936

	.SetMethod<&WebContents::SetOwnerBaseWindow>("_setOwnerWindow");

browser-view.ts:81

	this.webContents._setOwnerWindow(w);

browser-window.ts:188

	browserView.webContents._setOwnerWindow(this);

BrowserView 用它在 ownerWindow setter 里改归属(10.8.1)。这条路径绕过视图树,直接写 owner_window_ 和 relay——所以它能造出 10.7.4 里"不在树里但归属存在"的状态。一个下划线开头的方法,是四个入口里唯一能被用户代码调到的。

BrowserWindow 构造时其实两次设了 owner:

  1. 第 87 行显式 SetOwnerWindow(window())。
  2. 第 98 行 AddChildViewAt → OnViewAddedToWidget → 又一次 SetOwnerWindow(native_window)。

两次指向同一个窗口,第二次是幂等的(先 RemoveBackgroundThrottlingSource 再 Add)。看起来是冗余,实际是必要的:如果不显式设一次,在 AddChildViewAt 之前的那几行(第 87-97 行)就有个窗口为空的窗口期。这段窗口期里 Observe(...) 已经注册,OnPageTitleUpdated 等回调可能触发,而它们会读 owner_window()。

10.7.6 <webview> 的 owner 是"抄"来的

第三点值得单独看:SetEmbedder 不直接拿窗口,而是从 embedder 的 relay 里抄。

	auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
	if (relay) {
	owner_window = relay->GetNativeWindow();
	}

为什么不直接 owner_window = embedder->owner_window()?因为 embedder 是 const WebContents*(api 层),拿 owner_window() 需要非 const 或者 const 访问器。更重要的是:这是从"宿主网页"到"guest 网页"的继承,用 relay 是唯一能穿透 content::WebContents 层的路径。

同样的逻辑在 WebContents 构造里也有一份:

// :1266-1278
	if (is_guest()) {
	NativeWindow* owner_window = nullptr;
	if (embedder_) {
	// New WebContents's owner_window is the embedder's owner_window.
	auto* relay =
		NativeWindowRelay::FromWebContents(embedder_->web_contents());
	if (relay)
		owner_window = relay->GetNativeWindow();
	}
	if (owner_window)
	SetOwnerWindow(owner_window);
	}

guest 天生就属于 embedder 所在的窗口,不需要 addChildView。这是 <webview> 与 WebContentsView 最深的一条差异:前者的归属在构造时就定了,后者在入树时才定。

10.7.7 一致性条件

把上面压成一句可操作的规则:

getOwnerBrowserWindow() 可信,当且仅当 webContents 当前被某个窗口的视图树包含,且那个窗口还活着。

前半句没有公开 API 能直接查。可行的手段只有一个:win.contentView.children 里找 view 的兄弟(因为 WebContentsView 不在 contentView 里,而是在它的父节点上),而父节点拿不到。所以实际能查的只有后半句 win.isDestroyed(),前半句只能靠调用方自己记账——"我记得我把它加进了哪个窗口"。

这是本章所有不一致的根源:归属关系由视图树决定,而视图树不对外暴露。


10.8 迁移路径:BrowserView 是一个纯 JS 类

BrowserView 在 45.x 里已经废弃,但它的代码还在,而且它是理解"为什么要有 WebContentsView"的最佳反面教材。

10.8.1 它内部只有一个 WebContentsView

browser-view.ts:12-33

export default class BrowserView {
	#webContentsView: WebContentsView;
	#ownerWindow: BrowserWindow | null = null;
	#destroyListener: ((e: any) => void) | null = null;
	...
	constructor(options: { webPreferences: WebPreferences; webContents?: WebContents } = { webPreferences: {} }) {
	const { webPreferences = {}, webContents } = options;
	if (webContents) {
	v8Util.setHiddenValue(webPreferences, 'webContents', webContents);
	}
	webPreferences.type = 'browserView';
	this.#webContentsView = new WebContentsView({ webPreferences });
	this.#destroyListener = this.#onDestroy.bind(this);
	this.#webContentsView.webContents.once('destroyed', this.#destroyListener);
	}

171 行,零 C++。 它做的事情全是在 WebContentsView 外面包一层兼容壳:

  • 把 webContents 藏进 webPreferences(v8Util.setHiddenValue,因为 WebContentsView 只认这个通道)。
  • 设 type: 'browserView'。
  • 转发 setBounds / getBounds / setBackgroundColor。
  • 自己实现 setAutoResize(10.8.2)。

注意 type = 'browserView' 的作用:WebContents::Type::kBrowserView 的注释写着"Used by the JS implementation of BrowserView for backwards compatibility. Otherwise identical to kBrowserWindow."(electron_api_web_contents.h:146-148)。一个枚举值,专门为了向后兼容存在。

10.8.2 autoResize 是纯 JS 算的

browser-view.ts:116-130

	if (this.#autoResizeFlags.horizontal && this.#autoHorizontalProportion == null) {
	const viewBounds = this.#webContentsView.getBounds();
	this.#autoHorizontalProportion = {
		width: this.#lastWindowSize.width / viewBounds.width,
		left: this.#lastWindowSize.width / viewBounds.x
	};
	}

left 用 width / x。x === 0 时这是除零,得到 Infinity,随后 newBounds.width / Infinity === 0——恰好"正确地"保持 x: 0。这是一个碰巧能工作的除零。

结构性问题有两个:它依赖 resize 事件,而事件是异步的,拖动窗口时视图会滞后于边缘;它也不处理 DPI 变化(跨显示器移动时 resize 可能不触发,但像素密度变了)。

WebContentsView 干脆不提供 autoResize,因为正确做法是布局管理器:

win.contentView.setLayout({ orientation: 'horizontal' })
view.setBounds({ x: 0, y: 0, width: 0, height: 0 })   // 尺寸交给 flex

这不是功能倒退,是把"手动算比例"换成"声明式布局"。 代价是用户得先学布局系统。

10.8.3 #onDestroy 是补丁而不是设计

browser-view.ts:96-100

	#onDestroy() {
	// Ensure that if #webContentsView's webContents is destroyed,
	// the WebContentsView is removed from the view hierarchy.
	this.#ownerWindow?.contentView.removeChildView(this.webContentsView);
	}

WebContents 销毁时,WebContentsView 不会自动从树里摘掉(10.5.2 讲的中间态)。BrowserView 靠监听 destroyed 事件手动补这一步。

WebContentsView 没这个补丁。 所以用 WebContentsView 的时候,view.webContents.close() 之后你必须在自己的代码里 removeChildView,否则树上会留一个 0×0 的僵尸视图——它不渲染,但会参与布局计算、参与 children 数组、参与 z-order。

10.8.4 迁移对照

BrowserViewWebContentsView 等价写法
new BrowserView({ webPreferences })new WebContentsView({ webPreferences })
win.addBrowserView(bv)win.contentView.addChildView(view)
win.removeBrowserView(bv)win.contentView.removeChildView(view)
bv.setBounds(r)view.setBounds(r)
bv.setAutoResize(opts)container.setLayout({...}) 或手动监听 resize
bv.setBackgroundColor(c)view.setBackgroundColor(c)
bv.webContentsview.webContents
win.getBrowserView()自己维护引用
win.setTopBrowserView(bv)container.addChildView(view)(重排到末尾)
BrowserWindow.fromBrowserView(bv)view.webContents.getOwnerBrowserWindow()

三个不兼容点:

  1. 坐标系不同。BrowserView.setBounds 的坐标相对窗口内容区;WebContentsView.setBounds 的坐标相对父容器。如果把 WebContentsView 加进 contentView,而 contentView 有偏移(10.4.6),所有 y 都要减。
  2. 没有 ownerWindow 属性。BrowserView.ownerWindow 是个公开的 getter(browser-view.ts:70-72),WebContentsView 没有对应物——它只有一个内部的 observed_window_。
  3. z-order 语义反了。addBrowserView 是追加到 contentView 的末尾(在网页之上),contentView.addChildView 取决于你加在哪个容器里。如果迁移时把 win.addBrowserView(bv) 直接替换成 win.contentView.addChildView(view),视图会跑到网页上层——而这恰好是 BrowserView 原本的行为,所以这个替换反而对。 但如果替换成 win.addChildView(不存在)或加到别的地方,就会错。

10.9 <webview>:第三条分支,也是最老的一条

<webview> 是一个 HTML 元素,但它的内容是一个独立的 WebContents,可能在另一个渲染进程里。它是"跨进程视图"这个概念在 Electron 里的第一次实现,比 WebContentsView 早了十年。

10.9.1 guest 是一个 Type::kWebView 的 WebContents

electron_api_web_contents.h:143-152

	enum class Type {
	kBackgroundPage,  // An extension background page.
	kBrowserWindow,   // Used by BrowserWindow.
	kBrowserView,     // Used by the JS implementation of BrowserView for
					// backwards compatibility. Otherwise identical to
					// kBrowserWindow.
	kRemote,          // Thin wrap around an existing WebContents.
	kWebView,         // Used by <webview>.
	kOffScreen,       // Used for offscreen rendering
	};

六个类型,kWebView 是唯一一个"被别人嵌着"的。判据是一行:

electron_api_web_contents.h:350

	[[nodiscard]] bool is_guest() const { return type_ == Type::kWebView; }

is_guest() 在 electron_api_web_contents.cc 里被调了十几次,每次都在改行为:

  • 构造函数里走不同的 SiteInstance(chrome-guest://fake-host)和 WebViewGuestDelegate(:1090-1108)。
  • HandleKeyboardEvent 转发回 embedder(:1852-1854)。
  • 析构时"不归自己所有"(:1391)。

"guest" 这个身份不是一个类,而是一个 spread 在 6000 行里的 if 分支。 这是 WebContents 变得难以维护的主要原因之一。

10.9.2 createGuest 的三个设计点

// lib/browser/guest-view-manager.ts:89-118(节选)
const createGuest = function (
	embedder: Electron.WebContents,
	embedderFrame: Electron.WebFrameMain | null,
	embedderFrameToken: string,
	elementInstanceId: number,
	params: Record<string, any>
) {
	const webPreferences = makeWebPreferences(embedder, params);
	...
	embedder.emit('will-attach-webview', event, webPreferences, params);
	if (event.defaultPrevented) {
	return -1;
	}
	const guest = (webContents as typeof ElectronInternal.WebContents).create({
	...webPreferences,
	type: 'webview',
	embedder
	});

这段有三个设计点:

第一,will-attach-webview 可取消。 宿主页面可以拒绝任何 <webview> 的创建,这是安全边界的一部分(15 章会展开)。

第二,embedder 作为构造参数传下去。 于是 WebContents 的构造函数里能走 is_guest() 分支,并在 :1266-1278 直接把 owner window 抄过来(10.7.6)。

第三,安全选项强制继承。

guest-view-manager.ts:55-70

	// Security options that guest will always inherit from embedder
	const inheritedWebPreferences = new Map([
	['contextIsolation', true],
	['javascript', false],
	['nodeIntegration', false],
	['nodeIntegrationInWorker', false],
	['sandbox', true],
	['nodeIntegrationInSubFrames', false],
	['enableWebSQL', false]
	]);
	// Inherit certain option values from embedder
	const lastWebPreferences = embedder.getLastWebPreferences()!;
	for (const [name, value] of inheritedWebPreferences) {
	if (lastWebPreferences[name as keyof Electron.WebPreferences] === value) {
	(webPreferences as any)[name] = value;
	}
	}

注意逻辑方向:只有当 embedder 的选项等于那个"安全值"时才继承。 也就是说,contextIsolation 只有 embedder 开了,guest 才跟着开;embedder 关了,guest 不会跟着关(它用默认值)。继承是单向的"安全传播",不是双向同步。

10.9.3 guest 是一个跨进程 iframe

guest-view-manager.ts:205

	guest.attachToIframe(embedder, embedderFrameToken);
// shell/browser/api/electron_api_web_contents.cc:4677-4690(节选)
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
								std::string embedder_frame_token) {
	auto token = base::Token::FromString(embedder_frame_token);
	...
	guest_delegate_->AttachToIframe(embedder_web_contents, frame_token);

关键在 WebViewGuestDelegate——它是 Chromium 的 content::GuestDelegate,让一个 WebContents 能寄生在另一个 WebContents 的 frame 里。这是 OOPIF(out-of-process iframe)的一个变体。

所以 <webview> 不是"窗口里的另一个视图",而是"一个跨进程 iframe"。 它的渲染、合成、事件走 Blink 的 frame 树,不走 views 的视图树。

对比 WebContentsView:后者是真的 views::View,参与 views 布局;<webview> 的 guest 只被画进宿主页面的某个矩形区域,位置由 CSS 决定。这解释了它的几个怪毛病:没有 setBounds(只有 resize())、z-order 由 CSS 决定而与 views 层无法比较、contentWindow 是另一个进程的对象。

10.9.4 三条分支的能力对照

能力BrowserViewWebContentsView<webview>
实现层JS(包 WebContentsView)C++ views::View跨进程 iframe
归属窗口的建立时机addBrowserViewOnViewAddedToWidget构造时(抄 embedder)
位置控制setBoundssetBoundsCSS + resize()
参与 views 布局是是否
可被 <div> 遮挡否(永远在页面之上)否是(普通 DOM 元素)
主进程可拿到的对象BrowserViewWebContentsViewguestInstanceId(数字)
渲染进程是否独立是是是(除非 webpreferences 指定)
能否被 contextBridge 保护取决于 webPreferences同强制继承安全项
声明式状态无无有(HTML 属性)

最后一行是 <webview> 唯一的真正优势:它的配置写在 HTML 里,不需要主进程代码。这让"页面自己决定要嵌什么"成为可能——也是它成为安全风险的原因(一个被 XSS 的页面可以自己插一个 <webview>,如果 webviewTag 开着)。

10.9.5 为什么官方一直说它"不稳定"

三个结构性原因:

  1. 它是 OOPIF 的私生子。 Chromium 自己有一套 guest view 机制,但用法与 Electron 不同。每次上游改内部结构,Electron 都要跟着改 WebViewGuestDelegate——patches/chromium/ 里有多个补丁专为此存在。
  2. 它的 API 表面是手工同步的三份清单。 web-view-methods.ts 列出要转发的方法,guest-view-manager.ts 逐条挂 IPC,web-view-events.ts 列事件。加一个方法要改三处,漏改没有编译错误,只有运行时静默失效。
  3. 它的生命周期跨三个进程记账。 宿主页面的 DOM 元素、主进程的 guestInstances Map、渲染进程的 guestInstanceId。任何一份失步就留下"幽灵 guest"——一个还在跑但没人能访问的渲染进程。

10.10 失败模式手册

本章内容对应的症状,按"你看到了什么"索引:

现象原因定位
win.contentView.children.length === 0 但网页在渲染正常,网页在兄弟节点10.4.3
往 contentView 加的不透明 View 盖住了网页预期行为(PR #41256)10.4.4
contentView.setBounds() 下一次布局后被还原填充布局每次重算10.4.6
new WebContentsView() 后页面不显示默认 show: false10.5.5
view.webContents 是 nullWebContents 已销毁10.5.2
view.setBounds() 静默无效view_ 已被删除(非 macOS)10.6.7
圆角不生效或布局变化后消失尺寸 < 32×32 或半径 > 半宽10.6.6
setBounds({ animate: true }) 后变卡GetLayer() 创建了独立合成层10.6.5
getOwnerBrowserWindow() 返回已关闭的窗口removeChildView 不清理归属10.7.4
getOwnerBrowserWindow() 返回 BaseWindow函数名与行为不符10.7.3
setLayout({ calculateProposedLayout }) 后容器塌成一个点JS 回调抛异常被吞10.6.4
webContents.close() 后视图还在缺 removeChildView10.8.3
<webview> 的 guestInstanceId 失效三份状态失步10.9.5

三条最值得记的:

"contentView.setBounds 临时生效" 最隐蔽:写完立刻读是对的,第一次 resize 之后就回退,看起来像某处有 bug,而不是"这里根本不该设"。

"view.webContents 是 null 但视图还在" 会让 if (view.webContents) 这类检查在不可预期的时刻翻转。正确写法是每次重新读,不缓存。

"setLayout 容器塌陷" 只能靠给回调包 try/catch 诊断——异常不会打到控制台:

view.setLayout({
	calculateProposedLayout: (bounds) => {
	try { return compute(bounds) } catch (e) { console.error(e); return { size: bounds, layouts: [] } }
	}
})

10.11 性能账本

操作量级主要成本
new BaseWindow()8–20 msviews::Widget::Init + 空 View 的 V8 对象
new BrowserWindow()同 BaseWindow + 一次 WebContentsView 构造多了渲染进程启动(40–120 ms 到首帧)
new WebContentsView()30–90 ms一个新的渲染进程
view.addChildView(v)< 0.1 ms视图树插入 + JS 记账
addChildView 首次入树0.1–1 msOnViewAddedToWidget 的六个动作 + 布局失效
setBounds({ animate: true })每帧一次合成新建 layer,永久失去不透明优化
setBorderRadius< 0.1 ms路径重建(仅在 bounds 变化时)

两条推论:

一、BaseWindow 比 BrowserWindow 便宜,但只便宜在"没有内容"。 窗口本身的成本(views::Widget)一样。所以"一个 BaseWindow + N 个 WebContentsView"相比"N 个 BrowserWindow",省的是窗口(每个 8–20ms),不是渲染进程(每个 30–90ms)。

二、addChildView 便宜,贵的是它触发的连带效应。 首次入树要注册观察者、应用圆角、调度 overlay 坐标推送;如果此时页面已加载完,还会真推一次。批量加视图时,先把它们加完再 loadURL,能省掉中间几次推送。


10.12 练习题

10.1(入门) 在一个 BrowserWindow 上执行 win.contentView.children.length,再比较 win.contentView.getBounds() 与 win.getContentBounds() 的 x,解释为什么窗口移到别处后两个值不同(10.4.6)。

10.2(入门) 在 browser-window-created 事件里读 win.contentView.children.length,解释为什么是 0(10.1.3)。再在 ready-to-show 里读一次,结果是否变化?

10.3(初级) 写一个 BaseWindow + 两个并排的 WebContentsView,用 setBounds 手动分割。然后改成 contentView.setLayout({ orientation: 'horizontal' }) + flex 属性,比较两种写法在窗口缩放时的行为差异(10.6.4)。

10.4(初级) 验证 win.contentView.addChildView(v) 在两个不同的时刻调用 v.getBounds():addChildView 之前和之后(不加 setBounds)。解释为什么第二次的尺寸等于容器尺寸(10.4.2 的 SetUseDefaultFillLayout)。

10.5(进阶) 给一个 WebContentsView 设 setBorderRadius(20),然后把它缩到 30×30,观察圆角是否还在。解释 ApplyBorderRadius 里的两个 if 条件(10.6.6)。

10.6(进阶) 复现 10.6.7 的"view_ 变 null":非 macOS 上 view.webContents.close() 之后调 setBounds,用 console.log 确认没有生效。然后加一行 win.contentView.removeChildView(view),观察是否恢复(不会恢复——view_ 已经没了)。

10.7(进阶) 构造一个 BaseWindow + WebContentsView,调 view.webContents.getOwnerBrowserWindow(),打印 constructor.name。解释为什么不是 null 也不是 BrowserWindow(10.7.3)。

10.8(深入) 在 WebContentsView::OnViewAddedToWidget 的六个动作里,逐个注释掉,观察哪个会导致窗口归属丢失、哪个会导致拖拽失效、哪个会导致 overlay 坐标错(10.5.3)。

10.9(深入) 把 BrowserWindow 构造函数的 AddChildViewAt(..., 0) 改成 AddChildViewAt(..., 1)(或去掉 index),用 contentView 加一个半透明覆盖层,观察它是否可见。解释 PR #41256 修的是什么(10.3.3、10.4.4)。

10.10(挑战) 给 View 实现一个 removeAllChildViews():要求同时清理原生树和 child_views_,且不触发重复的 OnChildViewRemoved。提示:参考 RemoveChildView 的顺序约束(10.6.2)。

10.11(挑战) 阅读 guest-view-manager.ts 的 detachGuest,列出它在清理时漏掉的状态。对照 10.9.5 说的"三份状态",判断哪一份最容易失步(10.9.5)。


10.13 下一章预告

第 11 章《WebContents 解剖:6184 行的中枢》接住本章留下的三条线。

线一:10.5.2 说 WebContentsView 在 WebContents 销毁后变成一个"视图还在、内容没了"的空壳。第 11 章会讲 WebContents 的销毁协议:Destroy() / Close() / WebContentsDestroyed() / is_safe_to_delete_ 四者如何配合,以及为什么 guest 的析构路径与其他类型完全不同(析构函数在 :1343,guest 分支在 :1391-1399)。

线二:10.7 的三个答案背后是三条生命周期。第 11 章会把 api::WebContents 的 6184 行按"职责"切开:导航、生命周期、输入、渲染、IPC、DevTools、脚本注入,每一块各自的入口和状态机。

线三:10.9 说 guest 的身份是"spread 在 6000 行里的 if 分支"。第 11 章会数一遍 is_guest() 的全部调用点,并解释为什么这个设计在 45.x 已经接近它的维护极限。

一句话预告第 11 章的立论:WebContents 不是一个类,是一个把七个不相关的子系统塞进同一个对象的容器——它之所以长成这样,是因为 Chromium 的 content::WebContents 本来就是这么长的,而 Electron 选择在它外面再包一层,而不是拆开。

10.14 本章源码落点索引

下列位置全部来自本仓库源码树,按实现层归集;每个 路径:行号 指向该文件中与本章论述对应的声明或实现行,可逐条复核。

  • API 文档与类型:web-contents-view.md:5 web-contents.md:5
  • 浏览器进程 C++ 层:inspectable_web_contents_view.h:18 inspectable_web_contents_view_delegate.cc:10 inspectable_web_contents_view_delegate.h:15 electron_api_base_window_mac.mm:15 native_window_mac.h:22 native_window_mac_remote.h:25 native_window_mac_remote.mm:46 native_window_observer.h:19
  •  native_window_views.h:33 native_window_views_win.cc:49 osr_web_contents_view.cc:18 osr_web_contents_view.h:20 osr_web_contents_view_mac.mm:9 electron_api_web_contents_impl.cc:19 electron_api_web_contents_mac.mm:16 electron_api_web_view_manager.cc:19
  •  child_web_contents_tracker.cc:13 child_web_contents_tracker.h:16
  • shell 其余实现:native_window_converter.h:14
  • JS 门面与运行时:web-contents.ts:20