跳转到主内容

Web 嵌入

概览

有三种方式可以让你在Electron的BrowserWindow里集成(第三方)web内容,<iframe> 和, <webview>BrowserViews 每个功能都略有不同,适用于不同的情况。 为了帮助您在这些选择之间进行选择,本指南将解释他们之间的差异和功能。

Iframes

Iframe 在 Electron 中的行为与普通浏览器中类似。 在宿主页面的 Content Security Policy 允许范围内,一个 <iframe> 元素能在页面上显示外部网页。 要限制 <iframe> 标签中站点的功能数量,建议 使用 sandbox 属性 并且只允许您想要支持的功能。

WebView

重要提示: 我们不建议您使用 WebView,因为这个标签会发生剧烈的结构变化,可能会影响您应用程序的稳定性。 考虑切换到其他选择,如 iframe 和Electron的 BrowserView,或避免嵌入式内容 设计的架构。

WebViews基于 Chromium 的 WebView,不被 Electron 明确支持。 我们不能保证WebView API 在未来版本的 Electron 中仍然可用。 这就是为什么如果您想要使用<webview>标签,您需要在BrowserWindowwebPreferences 中设置 webviewTagtrue

WebView是一个自定义元素 (<webview>),仅在 Electron 内工作。 它们以 "进程外 iframe" 实现。 这意味着所有与 <webview> 的通信都是异步使用 IPC 进行的。 <webview>元素有许多自定义方法和事件,类似于webContents,使您能够更多地控制内容。

<iframe><webview> 相比往往稍慢,但在加载和与第三方内容通信以及处理各种事件方面提供了更大的控制。

WebContentsView

WebContentsViews are not a part of the DOM—instead, they are created, controlled, positioned, and sized by your Main process. Using WebContentsView, you can combine and layer many pages together in the same BaseWindow.

WebContentsViews offer the greatest control over their contents, since they implement the webContents similarly to how BrowserWindow does it. However, as WebContentsViews are not elements inside the DOM, positioning them accurately with respect to DOM content requires coordination between the Main and Renderer processes.