Skip to main content

网络嵌入

🌐 Web Embeds

概述

🌐 Overview

如果你想在 Electron BrowserWindow 中嵌入(第三方)网页内容,你有三种选项:<iframe> 标签、<webview> 标签和 WebContentsView。每一种都提供略微不同的功能,并在不同情况下有其用途。为帮助你在这些选项之间进行选择,本指南解释了每个选项的区别和功能。

🌐 If you want to embed (third-party) web content in an Electron BrowserWindow, there are three options available to you: <iframe> tags, <webview> tags, and WebContentsView. Each one offers slightly different functionality and is useful in different situations. To help you choose between these, this guide explains the differences and capabilities of each option.

Iframes

Electron 中的 iframe 的行为类似于普通浏览器中的 iframe。页面中的 <iframe> 元素可以显示外部网页,前提是它们的 内容安全策略 允许这样做。为了限制 <iframe> 标签中某个站点的功能数量,建议使用 sandbox 属性,并仅允许你希望支持的功能。

🌐 Iframes in Electron behave like iframes in regular browsers. An <iframe> element in your page can show external web pages, provided that their Content Security Policy allows it. To limit the number of capabilities of a site in an <iframe> tag, it is recommended to use the sandbox attribute and only allow the capabilities you want to support.

WebViews

info

我们不建议你使用 WebViews, 因为该标签正在经历重大架构变更,可能会影响你应用的稳定性。 建议考虑使用替代方案,例如 iframe 和 Electron 的 WebContentsView,或采用一种设计上避免嵌入内容的架构。

WebViews 基于 Chromium 的 WebViews,并未得到 Electron 的明确支持。我们不保证 WebView API 在未来版本的 Electron 中仍然可用。要使用 <webview> 标签,你需要在你的 BrowserWindowwebPreferences 中将 webviewTag 设置为 true

WebView 是一个自定义元素(<webview>),只能在 Electron 内部使用。它们被实现为“进程外的 iframe”。这意味着与 <webview> 的所有通信都是通过 IPC 异步进行的。<webview> 元素有许多自定义方法和事件,类似于 webContents,为你提供了对内容的更大控制权。

🌐 WebView is a custom element (<webview>) that will only work inside Electron. They are implemented as an "out-of-process iframe". This means that all communication with the <webview> is done asynchronously using IPC. The <webview> element has many custom methods and events, similar to webContents, that provide you with greater control over the content.

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

🌐 Compared to an <iframe>, <webview> tends to be slightly slower but offers much greater control in loading and communicating with the third-party content and handling various events.

WebContentsView

WebContentsView 不是 DOM 的一部分——相反,它们由你的主进程创建、控制、定位和调整大小。使用 WebContentsView,你可以在同一个 BaseWindow 中组合和分层多个页面。

WebContentsView 对其内容提供了最大的控制,因为它们实现了 webContents,方式类似于 BrowserWindow。然而,由于 WebContentsView 并不是 DOM 内的元素,因此要相对于 DOM 内容准确定位它们,需要在主进程和渲染进程之间进行协调。