Electron 是否有标准的方法来杀死无用的渲染器进程?

Does Electron have a standard way of killing a useless renderer process?

我的应用创建了一个 window 本地页面,需要启用节点集成。

单击此页面上的按钮后,我被导航到第三方页面。

因为我想在这个第三方页面中禁用节点,而且我不能在 BrowserWindow 中切换节点集成,所以我在沙盒 BrowserView 中加载这个第三方页面嵌入 window 内部并拉伸以适合整个屏幕。

现在执行此操作可导航嵌入式视图,但 BrowserWindow 卡住指向不再相关的旧本地页面。

为了防止这个额外的页面在后台停留,我将我的 BrowserWindow 导航到 "about:blank" 以有效地清除它并为 BrowserView.[=26 腾出空间=]

我现在意识到,虽然这个 "clears" 在旧页面之外,但它使与其关联的呈现器进程保持活动状态。来自 here:

Chromium creates a renderer process for each instance of a site the user visits

可以理解,导航到 "about:blank" 不会向 Electron 发出它应该终止其他进程的信号。

我想摆脱这个渲染器进程,这样它就不会在我与 window.

交互时不必要地闲置并使用 CPU 和内存

有两件事奏效了:

我删除了指向 "about:blank" 的额外导航,因为我们现在正在终止进程并且:

1) 当我的渲染器中的按钮向主进程发送一条消息,告诉它创建一个 BrowserView 并导航到新站点时,我执行了一个 process.exit();。我想我的一部分人对进程退出干扰为 main 排队的消息感到紧张,尽管它似乎工作正常。

2) 我没有从渲染器中终止进程,而是创建并导航了我的 BrowserView 然后 运行 一点点 browserWindow.webContents.executeJavascript("process.exit()");。我觉得这更丑陋,尽管它确实减轻了上面 #1 中的担忧。

没有 webcontents.destroy() 类型的方法,我不知道有什么方法可以向 Electron 发出信号,告知它需要销毁这个不必要的进程。

我想我可能有一个非常独特的案例,但是有没有比显式执行 process.exit() 更好(或更标准的方法)来处理这个问题?

现在有一个WebContents::forcefullyCrashRenderer() API that accomplishes this (introduced by this PR):

Forcefully terminates the renderer process that is currently hosting this webContents. This will cause the render-process-gone event to be emitted with the reason=killed || reason=crashed. Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well.

截至目前(2021 年 7 月,Electron v13)- 还有一个未记录的 webContents.destroy()

https://github.com/electron/electron/issues/10096

如文档所述,一些 webContents 共享渲染器进程,如果您使用 webContents.forcefullyCrashRenderer(),您也可以终止它们。

我不确定 webContents.destroy() 是如何处理它的,但从名称上看,它的范围似乎更窄。如果 webContents 是唯一附加到它的 webContents(我测试过这个),我会假设它会杀死渲染器,如果其他 webContents 正在使用它(需要确认),它会保留渲染器。