<webview> 标签
🌐 <webview> Tag
警告
🌐 Warning
Electron 的 webview 版本基于 Chromium 的 webview,而 Chromium 的 webview 正在进行重大架构变更。这会影响 webviews 的稳定性,包括渲染、导航和事件路由。我们目前建议不要使用 webview 版本,并考虑替代方案,例如 iframe、WebContentsView 或完全避免嵌入内容的架构。
🌐 Electron's webview tag is based on Chromium's webview, which
is undergoing dramatic architectural changes. This impacts the stability of webviews,
including rendering, navigation, and event routing. We currently recommend to
not use the webview tag and to consider alternatives, like iframe, a
WebContentsView, or an architecture that avoids
embedded content altogether.
启用
🌐 Enabling
默认情况下,Electron >= 5 中的 webview 标签是禁用的。你需要在构建 BrowserWindow 时通过设置 webviewTag webPreferences 选项来启用该标签。更多信息请参阅 BrowserWindow 构造函数文档。
🌐 By default the webview tag is disabled in Electron >= 5. You need to enable the tag by
setting the webviewTag webPreferences option when constructing your BrowserWindow. For
more information see the BrowserWindow constructor docs.
概述
🌐 Overview
在隔离的框架和进程中显示外部网页内容。
进程: 渲染器
此类未从 'electron' 模块导出。它仅作为 Electron API 中其他方法的返回值提供。
使用 webview 标签在你的 Electron 应用中嵌入“访客”内容(例如网页)。访客内容包含在 webview 容器中。应用中的嵌入页面控制访客内容的布局和渲染方式。
🌐 Use the webview tag to embed 'guest' content (such as web pages) in your
Electron app. The guest content is contained within the webview container.
An embedded page within your app controls how the guest content is laid out and
rendered.
与 iframe 不同,webview 在与你的应用分开的进程中运行。它没有你的网页相同的权限,并且你应用与嵌入内容之间的所有交互都是异步的。这可以保护你的应用免受嵌入内容的影响。
🌐 Unlike an iframe, the webview runs in a separate process than your
app. It doesn't have the same permissions as your web page and all interactions
between your app and embedded content will be asynchronous. This keeps your app
safe from the embedded content.
从主机页面调用 WebView 的大多数方法都需要同步调用主进程。
示例
🌐 Example
要在你的应用中嵌入网页,请将 webview 标签添加到应用的嵌入页面(这是将显示来宾内容的应用页面)。在最简单的形式中,webview 标签包含网页的 src 和控制 webview 容器外观的 CSS 样式:
🌐 To embed a web page in your app, add the webview tag to your app's embedder
page (this is the app page that will display the guest content). In its simplest
form, the webview tag includes the src of the web page and css styles that
control the appearance of the webview container:
<webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview>
如果你想以任何方式控制访客内容,你可以编写 JavaScript 来监听 webview 事件,并使用 webview 方法响应这些事件。下面是包含两个事件监听器的示例代码:一个用于监听网页开始加载,另一个用于监听网页停止加载,并在加载期间显示“正在加载...”的消息:
🌐 If you want to control the guest content in any way, you can write JavaScript
that listens for webview events and responds to those events using the
webview methods. Here's sample code with two event listeners: one that listens
for the web page to start loading, the other for the web page to stop loading,
and displays a "loading..." message during the load time:
<script>
onload = () => {
const webview = document.querySelector('webview')
const indicator = document.querySelector('.indicator')
const loadstart = () => {
indicator.innerText = 'loading...'
}
const loadstop = () => {
indicator.innerText = ''
}
webview.addEventListener('did-start-loading', loadstart)
webview.addEventListener('did-stop-loading', loadstop)
}
</script>
内部实现
🌐 Internal implementation
在底层,webview 是使用 Out-of-Process iframes (OOPIFs) 实现的。
webview 标签本质上是一个自定义元素,使用 Shadow DOM 将一个 iframe 元素封装其中。
🌐 Under the hood webview is implemented with Out-of-Process iframes (OOPIFs).
The webview tag is essentially a custom element using shadow DOM to wrap an
iframe element inside it.
所以 webview 的行为与跨域 iframe 非常相似,例如:
🌐 So the behavior of webview is very similar to a cross-domain iframe, as
examples:
- 当点击
webview时,页面焦点将从嵌入框架移到webview。 - 你不能向
webview添加键盘、鼠标和滚动事件监听器。 - 嵌入框架与
webview之间的所有反应都是异步的。
CSS 样式注释
🌐 CSS Styling Notes
请注意,webview 标签的样式内部使用 display:flex;,以确保子元素 iframe 在传统和弹性布局中能够填充其 webview 容器的全部高度和宽度。请不要覆盖默认的 display:flex; CSS 属性,除非为内联布局指定 display:inline-flex;。
🌐 Please note that the webview tag's style uses display:flex; internally to
ensure the child iframe element fills the full height and width of its webview
container when used with traditional and flexbox layouts. Please do not
overwrite the default display:flex; CSS property, unless specifying
display:inline-flex; for inline layout.
标签属性
🌐 Tag Attributes
webview 标签具有以下属性:
🌐 The webview tag has the following attributes:
src
<webview src="https://www.github.com/"></webview>
string 表示可见的 URL。写入此属性会启动顶层导航。
🌐 A string representing the visible URL. Writing to this attribute initiates top-level
navigation.
将 src 分配为其自身的值将会重新加载当前页面。
🌐 Assigning src its own value will reload the current page.
src 属性也可以接受数据 URL,例如 data:text/plain,Hello, world!。
🌐 The src attribute can also accept data URLs, such as
data:text/plain,Hello, world!.
nodeintegration
<webview src="https://www.google.com/" nodeintegration></webview>
一个 boolean。当存在此属性时,webview 中的访客页面将具有节点集成,并可以使用节点 API,如 require 和 process,来访问底层系统资源。访客页面默认情况下禁用节点集成。
🌐 A boolean. When this attribute is present the guest page in webview will have node
integration and can use node APIs like require and process to access low
level system resources. Node integration is disabled by default in the guest
page.
nodeintegrationinsubframes
<webview src="https://www.google.com/" nodeintegrationinsubframes></webview>
在 webview 内的子框架(如 iframe)中启用 NodeJS 支持的实验性选项的 boolean。你所有的预加载都会在每个 iframe 中加载,你可以使用 process.isMainFrame 来判断是否处于主框架中。此选项在访客页面中默认是禁用的。
🌐 A boolean for the experimental option for enabling NodeJS support in sub-frames such as iframes
inside the webview. All your preloads will load for every iframe, you can
use process.isMainFrame to determine if you are in the main frame or not.
This option is disabled by default in the guest page.
plugins
<webview src="https://www.github.com/" plugins></webview>
一个 boolean。当此属性存在时,webview 中的访客页面将能够使用浏览器插件。插件默认情况下是禁用的。
🌐 A boolean. When this attribute is present the guest page in webview will be able to use
browser plugins. Plugins are disabled by default.
preload
<!-- from a file -->
<webview src="https://www.github.com/" preload="./test.js"></webview>
<!-- or if you want to load from an asar archive -->
<webview src="https://www.github.com/" preload="./app.asar/test.js"></webview>
一个 string,用于指定将在访客页面的其他脚本运行之前加载的脚本。脚本 URL 的协议必须是 file:(即使使用 asar: 存档),因为它将在底层由 Node 的 require 加载,而 Node 将 asar: 存档视为虚拟目录。
🌐 A string that specifies a script that will be loaded before other scripts run in the guest
page. The protocol of script's URL must be file: (even when using asar: archives) because
it will be loaded by Node's require under the hood, which treats asar: archives as virtual
directories.
当来宾页面没有节点集成时,该脚本仍然可以访问所有 Node API,但在此脚本执行完毕后,由 Node 注入的全局对象将被删除。
🌐 When the guest page doesn't have node integration this script will still have access to all Node APIs, but global objects injected by Node will be deleted after this script has finished executing.
httpreferrer
<webview src="https://www.github.com/" httpreferrer="https://example.com/"></webview>
一个 string,用于设置访客页面的来源 URL。
🌐 A string that sets the referrer URL for the guest page.
useragent
<webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>
一个 string,用于在导航到页面之前为访客页面设置用户代理。一旦页面加载完成,请使用 setUserAgent 方法更改用户代理。
🌐 A string that sets the user agent for the guest page before the page is navigated to. Once the
page is loaded, use the setUserAgent method to change the user agent.
disablewebsecurity
<webview src="https://www.github.com/" disablewebsecurity></webview>
一个 boolean。当存在此属性时,来宾页面将禁用网页安全性。网页安全性默认是启用的。
🌐 A boolean. When this attribute is present the guest page will have web security disabled.
Web security is enabled by default.
该值只能在第一次导航之前修改。
🌐 This value can only be modified before the first navigation.
partition
<webview src="https://github.com" partition="persist:github"></webview>
<webview src="https://electron.nodejs.cn" partition="electron"></webview>
一个 string,用于设置页面使用的会话。如果 partition 以 persist: 开头,页面将使用对应用中所有具有相同 partition 的页面可用的持久会话。如果没有 persist: 前缀,页面将使用内存中的会话。通过分配相同的 partition,多个页面可以共享同一个会话。如果未设置 partition,则将使用应用的默认会话。
🌐 A string that sets the session used by the page. If partition starts with persist:, the
page will use a persistent session available to all pages in the app with the
same partition. if there is no persist: prefix, the page will use an
in-memory session. By assigning the same partition, multiple pages can share
the same session. If the partition is unset then default session of the app
will be used.
这个值只能在第一次导航之前修改,因为活动渲染器进程的会话无法更改。之后尝试修改该值将会导致 DOM 异常失败。
🌐 This value can only be modified before the first navigation, since the session of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception.
allowpopups
<webview src="https://www.github.com/" allowpopups></webview>
一个 boolean。当此属性存在时,来宾页面将被允许打开新窗口。弹出窗口默认是禁用的。
🌐 A boolean. When this attribute is present the guest page will be allowed to open new
windows. Popups are disabled by default.
webpreferences
<webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview>
string 是一个由逗号分隔的字符串列表,用于指定要在 webview 上设置的网页偏好。完整的支持偏好字符串列表可以在 BrowserWindow 中找到。
🌐 A string which is a comma separated list of strings which specifies the web preferences to be set on the webview.
The full list of supported preference strings can be found in BrowserWindow.
该字符串遵循与 window.open 中功能字符串相同的格式。
单独的名称被赋予 true 布尔值。
可以通过包含一个 =,然后跟随该值,将首选项设置为其他值。
特殊值 yes 和 1 被解释为 true,而 no 和 0 被解释为 false。
🌐 The string follows the same format as the features string in window.open.
A name by itself is given a true boolean value.
A preference can be set to another value by including an =, followed by the value.
Special values yes and 1 are interpreted as true, while no and 0 are interpreted as false.
enableblinkfeatures
<webview src="https://www.github.com/" enableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
string 是一个字符串列表,用于指定要启用的 Blink 功能,各功能之间用 , 分隔。完整的支持功能字符串列表可以在 RuntimeEnabledFeatures.json5 文件中找到。
🌐 A string which is a list of strings which specifies the blink features to be enabled separated by ,.
The full list of supported feature strings can be found in the
RuntimeEnabledFeatures.json5 file.
disableblinkfeatures
<webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
string 是一个字符串列表,用于指定要禁用的 Blink 功能,各功能之间用 , 分隔。完整的支持功能字符串列表可以在 RuntimeEnabledFeatures.json5 文件中找到。
🌐 A string which is a list of strings which specifies the blink features to be disabled separated by ,.
The full list of supported feature strings can be found in the
RuntimeEnabledFeatures.json5 file.
方法
🌐 Methods
webview 标签具有以下方法:
🌐 The webview tag has the following methods:
在使用这些方法之前,必须先加载 webview 元素。
示例
const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', () => {
webview.openDevTools()
})
<webview>.loadURL(url[, options])
url网址
返回 Promise<void> - 当页面加载完成时,Promise 将会解决(参见 did-finish-load),如果页面加载失败,则会被拒绝(参见 did-fail-load)。
🌐 Returns Promise<void> - The promise will resolve when the page has finished loading
(see did-finish-load), and rejects
if the page fails to load (see
did-fail-load).
在 webview 中加载 url,url 必须包含协议前缀,例如 http:// 或 file://。
🌐 Loads the url in the webview, the url must contain the protocol prefix,
e.g. the http:// or file://.
<webview>.downloadURL(url[, options])
url字符串
在不导航的情况下,启动对 url 资源的下载。
🌐 Initiates a download of the resource at url without navigating.
<webview>.getURL()
返回 string - 客人页面的 URL。
🌐 Returns string - The URL of guest page.
<webview>.getTitle()
返回 string - 客人页面的标题。
🌐 Returns string - The title of guest page.
<webview>.isLoading()
返回 boolean - 客户页面是否仍在加载资源。
🌐 Returns boolean - Whether guest page is still loading resources.
<webview>.isLoadingMainFrame()
返回 boolean - 指示主框架(而不仅仅是其中的 iframe 或子框架)是否仍在加载。
🌐 Returns boolean - Whether the main frame (and not just iframes or frames within it) is
still loading.
<webview>.isWaitingForResponse()
返回 boolean - 指示访客页面是否正在等待页面主资源的首次响应。
🌐 Returns boolean - Whether the guest page is waiting for a first-response for the
main resource of the page.
<webview>.stop()
停止任何挂起的导航。
🌐 Stops any pending navigation.
<webview>.reload()
重新加载访客页面。
🌐 Reloads the guest page.
<webview>.reloadIgnoringCache()
重新加载访客页面并忽略缓存。
🌐 Reloads the guest page and ignores cache.
<webview>.canGoBack()
返回 boolean - 客户页面是否可以返回。
🌐 Returns boolean - Whether the guest page can go back.
<webview>.canGoForward()
返回 boolean - 客户页面是否可以前进。
🌐 Returns boolean - Whether the guest page can go forward.
<webview>.canGoToOffset(offset)
offset整数
返回 boolean - 指示访客页面是否可以跳转到 offset。
🌐 Returns boolean - Whether the guest page can go to offset.
<webview>.clearHistory()
清除导航历史记录。
🌐 Clears the navigation history.
<webview>.goBack()
使访客页面返回。
🌐 Makes the guest page go back.
<webview>.goForward()
使访客页面前进。
🌐 Makes the guest page go forward.
<webview>.goToIndex(index)
index整数
导航到指定的绝对索引。
🌐 Navigates to the specified absolute index.
<webview>.goToOffset(offset)
offset整数
导航到“当前条目”的指定偏移位置。
🌐 Navigates to the specified offset from the "current entry".
<webview>.isCrashed()
返回 boolean - 渲染器进程是否已崩溃。
🌐 Returns boolean - Whether the renderer process has crashed.
<webview>.setUserAgent(userAgent)
userAgent字符串
覆盖访客页面的用户代理。
🌐 Overrides the user agent for the guest page.
<webview>.getUserAgent()
返回 string - 来宾页面的用户代理。
🌐 Returns string - The user agent for guest page.
<webview>.insertCSS(css)
css字符串
返回 Promise<string> - 一个承诺(Promise),该承诺会解析为插入的 CSS 的键,之后可以通过 <webview>.removeInsertedCSS(key) 来移除该 CSS。
🌐 Returns Promise<string> - A promise that resolves with a key for the inserted
CSS that can later be used to remove the CSS via
<webview>.removeInsertedCSS(key).
将 CSS 注入当前网页,并返回插入样式表的唯一键。
🌐 Injects CSS into the current web page and returns a unique key for the inserted stylesheet.
<webview>.removeInsertedCSS(key)
key字符串
返回 Promise<void> - 如果移除成功,则解析。
🌐 Returns Promise<void> - Resolves if the removal was successful.
从当前网页中移除已插入的 CSS。样式表通过其键来识别,该键由 <webview>.insertCSS(css) 返回。
🌐 Removes the inserted CSS from the current web page. The stylesheet is identified
by its key, which is returned from <webview>.insertCSS(css).
<webview>.executeJavaScript(code[, userGesture])
code字符串userGesture布尔值(可选)- 默认false。
返回 Promise<any> - 一个 Promise,如果代码执行成功则会以执行结果解析,如果代码结果是被拒绝的 Promise,则会被拒绝。
🌐 Returns Promise<any> - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
在页面中评估 code。如果设置了 userGesture,它将在页面中创建用户手势上下文。像 requestFullScreen 这样的 HTML API 需要用户操作,可以利用此选项进行自动化。
🌐 Evaluates code in page. If userGesture is set, it will create the user
gesture context in the page. HTML APIs like requestFullScreen, which require
user action, can take advantage of this option for automation.
<webview>.openDevTools()
打开访客页面的 DevTools 窗口。
🌐 Opens a DevTools window for guest page.
<webview>.closeDevTools()
关闭访客页面的 DevTools 窗口。
🌐 Closes the DevTools window of guest page.
<webview>.isDevToolsOpened()
返回 boolean - 客户页面是否附有 DevTools 窗口。
🌐 Returns boolean - Whether guest page has a DevTools window attached.
<webview>.isDevToolsFocused()
返回 boolean - 客户页面的开发者工具窗口是否处于焦点状态。
🌐 Returns boolean - Whether DevTools window of guest page is focused.
<webview>.inspectElement(x, y)
x整数y整数
开始检查访客页面上位置 (x, y) 的元素。
🌐 Starts inspecting element at position (x, y) of guest page.
<webview>.inspectSharedWorker()
打开来宾页面中存在的共享工作线程上下文的开发工具。
🌐 Opens the DevTools for the shared worker context present in the guest page.
<webview>.inspectServiceWorker()
打开来宾页面中存在的服务工作线程上下文的 DevTools。
🌐 Opens the DevTools for the service worker context present in the guest page.
<webview>.setAudioMuted(muted)
muted布尔值
将访客页面设置为静音。
🌐 Set guest page muted.
<webview>.isAudioMuted()
返回 boolean - 来宾页面是否已被静音。
🌐 Returns boolean - Whether guest page has been muted.
<webview>.isCurrentlyAudible()
返回 boolean - 音频当前是否正在播放。
🌐 Returns boolean - Whether audio is currently playing.
<webview>.undo()
在页面中执行编辑命令 undo。
🌐 Executes editing command undo in page.
<webview>.redo()
在页面中执行编辑命令 redo。
🌐 Executes editing command redo in page.
<webview>.cut()
在页面中执行编辑命令 cut。
🌐 Executes editing command cut in page.
<webview>.copy()
在页面中执行编辑命令 copy。
🌐 Executes editing command copy in page.
<webview>.centerSelection()
将当前文本选择在页面中居中。
🌐 Centers the current text selection in page.
<webview>.paste()
在页面中执行编辑命令 paste。
🌐 Executes editing command paste in page.
<webview>.pasteAndMatchStyle()
在页面中执行编辑命令 pasteAndMatchStyle。
🌐 Executes editing command pasteAndMatchStyle in page.
<webview>.delete()
在页面中执行编辑命令 delete。
🌐 Executes editing command delete in page.
<webview>.selectAll()
在页面中执行编辑命令 selectAll。
🌐 Executes editing command selectAll in page.
<webview>.unselect()
在页面中执行编辑命令 unselect。
🌐 Executes editing command unselect in page.
<webview>.scrollToTop()
滚动到当前 <webview> 的顶部。
🌐 Scrolls to the top of the current <webview>.
<webview>.scrollToBottom()
滚动到当前 <webview> 的底部。
🌐 Scrolls to the bottom of the current <webview>.
<webview>.adjustSelection(options)
按给定的数量调整焦点框中当前文本选择的起始和结束位置。负数会将选择移动到文档的开头,正数会将选择移动到文档的末尾。
🌐 Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document.
请参见 webContents.adjustSelection 了解示例。
🌐 See webContents.adjustSelection for
examples.
<webview>.replace(text)
text字符串
在页面中执行编辑命令 replace。
🌐 Executes editing command replace in page.
<webview>.replaceMisspelling(text)
text字符串
在页面中执行编辑命令 replaceMisspelling。
🌐 Executes editing command replaceMisspelling in page.
<webview>.insertText(text)
text字符串
返回 Promise<void>
🌐 Returns Promise<void>
将 text 插入到当前焦点元素。
🌐 Inserts text to the focused element.
<webview>.findInPage(text[, options])
text字符串 - 要搜索的内容,不能为空。
返回 Integer - 请求使用的请求ID。
🌐 Returns Integer - The request id used for the request.
启动请求以查找网页中 text 的所有匹配项。请求的结果可以通过订阅 found-in-page 事件来获取。
🌐 Starts a request to find all matches for the text in the web page. The result of the request
can be obtained by subscribing to found-in-page event.
<webview>.stopFindInPage(action)
action字符串 - 指定在结束<webview>.findInPage请求时要执行的操作。clearSelection- 清除选择。keepSelection- 将选择转换为正常选择。activateSelection- 聚焦并单击选择节点。
阻止对 webview 发出的任何 findInPage 请求,使用提供的 action。
🌐 Stops any findInPage request for the webview with the provided action.
<webview>.print([options])
返回 Promise<void>
🌐 Returns Promise<void>
打印 webview 的网页。与 webContents.print([options]) 相同。
🌐 Prints webview's web page. Same as webContents.print([options]).
<webview>.printToPDF(options)
返回 Promise<Uint8Array> - 解析为生成的 PDF 数据。
🌐 Returns Promise<Uint8Array> - Resolves with the generated PDF data.
将 webview 的网页打印为 PDF,与 webContents.printToPDF(options) 相同。
🌐 Prints webview's web page as PDF, Same as webContents.printToPDF(options).
<webview>.capturePage([rect])
rect矩形(可选)- 要捕获的页面区域。
返回 Promise<NativeImage> - 解析为一个 NativeImage
🌐 Returns Promise<NativeImage> - Resolves with a NativeImage
在 rect 中捕获页面的快照。省略 rect 将捕获整个可见页面。
🌐 Captures a snapshot of the page within rect. Omitting rect will capture the whole visible page.
<webview>.send(channel, ...args)
channel字符串...argsany[]
返回 Promise<void>
🌐 Returns Promise<void>
通过 channel 向渲染进程发送异步消息,你还可以发送任意参数。渲染进程可以通过 ipcRenderer 模块监听 channel 事件来处理该消息。
🌐 Send an asynchronous message to renderer process via channel, you can also
send arbitrary arguments. The renderer process can handle the message by
listening to the channel event with the ipcRenderer module.
请参见 webContents.send 示例。
🌐 See webContents.send for examples.
<webview>.sendToFrame(frameId, channel, ...args)
- 'frameId' [数字,数字] - '[processId, frameId]'
channel字符串...argsany[]
返回 Promise<void>
🌐 Returns Promise<void>
通过 channel 向渲染进程发送异步消息,你还可以发送任意参数。渲染进程可以通过 ipcRenderer 模块监听 channel 事件来处理该消息。
🌐 Send an asynchronous message to renderer process via channel, you can also
send arbitrary arguments. The renderer process can handle the message by
listening to the channel event with the ipcRenderer module.
请参见 webContents.sendToFrame 了解示例。
🌐 See webContents.sendToFrame for examples.
<webview>.sendInputEvent(event)
返回 Promise<void>
🌐 Returns Promise<void>
将输入 event 发送到页面。
🌐 Sends an input event to the page.
请参阅 webContents.sendInputEvent 以获取 event 对象的详细描述。
🌐 See webContents.sendInputEvent
for detailed description of event object.
<webview>.setZoomFactor(factor)
factor数字 - 缩放因子。
将缩放因子更改为指定的因子。缩放因子是缩放百分比除以100,因此300% = 3.0。
🌐 Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0.
<webview>.setZoomLevel(level)
level数字 - 缩放级别。
将缩放级别更改为指定级别。原始大小为0,每增加或减少一个增量表示缩放为原始大小的120%或80%,默认限制分别为原始大小的300%和50%。其公式为 scale := 1.2 ^ level。
🌐 Changes the zoom level to the specified level. The original size is 0 and each
increment above or below represents zooming 20% larger or smaller to default
limits of 300% and 50% of original size, respectively. The formula for this is
scale := 1.2 ^ level.
Chromium级别的缩放策略是同源策略,这意味着特定域的缩放等级会在所有具有相同域的窗口实例之间传播。区分窗口的URL将使缩放在每个窗口上单独生效。
<webview>.getZoomFactor()
返回 number - 当前的缩放因子。
🌐 Returns number - the current zoom factor.
<webview>.getZoomLevel()
返回 number - 当前的缩放级别。
🌐 Returns number - the current zoom level.
<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevel号码maximumLevel号码
返回 Promise<void>
🌐 Returns Promise<void>
设置最大和最小捏合缩放级别。
🌐 Sets the maximum and minimum pinch-to-zoom level.
<webview>.showDefinitionForSelection() macOS
显示搜索页面上所选单词的弹出词典。
🌐 Shows pop-up dictionary that searches the selected word on the page.
<webview>.getWebContentsId()
返回 number - 此 webview 的 WebContents ID。
🌐 Returns number - The WebContents ID of this webview.
DOM 事件
🌐 DOM Events
webview 标签可用的以下 DOM 事件:
🌐 The following DOM events are available to the webview tag:
Event: 'load-commit'
返回:
🌐 Returns:
url字符串isMainFrame布尔值
在加载完成时触发。这包括当前文档内的导航以及子框架的文档级加载,但不包括异步资源加载。
🌐 Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads.
Event: 'did-finish-load'
当导航完成时触发,即标签页的加载动画将停止,并且会发送 onload 事件。
🌐 Fired when the navigation is done, i.e. the spinner of the tab will stop
spinning, and the onload event is dispatched.
Event: 'did-fail-load'
返回:
🌐 Returns:
errorCode整数errorDescription字符串validatedURL字符串isMainFrame布尔值
这个事件类似于 did-finish-load,但在加载失败或被取消时触发,例如会调用 window.stop()。
🌐 This event is like did-finish-load, but fired when the load failed or was
cancelled, e.g. window.stop() is invoked.
Event: 'did-frame-finish-load'
返回:
🌐 Returns:
isMainFrame布尔值
当框架完成导航时触发。
🌐 Fired when a frame has done navigation.
Event: 'did-start-loading'
对应于选项卡的旋转器开始旋转的时间点。
🌐 Corresponds to the points in time when the spinner of the tab starts spinning.
Event: 'did-stop-loading'
对应于选项卡的旋转器停止旋转的时间点。
🌐 Corresponds to the points in time when the spinner of the tab stops spinning.
Event: 'did-attach'
当附加到嵌入器 Web 内容时触发。
🌐 Fired when attached to the embedder web contents.
Event: 'dom-ready'
加载给定框架中的文档时触发。
🌐 Fired when document in the given frame is loaded.
Event: 'page-title-updated'
返回:
🌐 Returns:
title字符串explicitSet布尔值
在导航进程中设置页面标题时触发。当标题由文件 URL 合成时,explicitSet 为 false。
🌐 Fired when page title is set during navigation. explicitSet is false when
title is synthesized from file url.
Event: 'page-favicon-updated'
返回:
🌐 Returns:
faviconsstring[] - URL 数组。
当页面收到 favicon url 时触发。
🌐 Fired when page receives favicon urls.
Event: 'enter-html-full-screen'
当页面由 HTML API 触发进入全屏时触发。
🌐 Fired when page enters fullscreen triggered by HTML API.
Event: 'leave-html-full-screen'
当页面离开全屏时由 HTML API 触发。
🌐 Fired when page leaves fullscreen triggered by HTML API.
Event: 'console-message'
返回:
🌐 Returns:
level整数 - 日志级别,从 0 到 3。它依次对应verbose、info、warning和error。message字符串 - 实际的控制台消息line整数 - 触发此控制台消息的源代码行号sourceId字符串
当来宾窗口记录控制台消息时触发。
🌐 Fired when the guest window logs a console message.
以下示例代码会将所有日志消息转发到嵌入者的控制台,而不考虑日志级别或其他属性。
🌐 The following example code forwards all log messages to the embedder's console without regard for log level or other properties.
const webview = document.querySelector('webview')
webview.addEventListener('console-message', (e) => {
console.log('Guest page logged a message:', e.message)
})
Event: 'found-in-page'
返回:
🌐 Returns:
result对象requestId整数activeMatchOrdinal整数 - 活动匹配的位置。matches整数 - 比赛数量。selectionArea矩形 - 第一个匹配区域的坐标。finalUpdate布尔值
在webview.findInPage请求有结果可用时触发。
🌐 Fired when a result is available for
webview.findInPage request.
const webview = document.querySelector('webview')
webview.addEventListener('found-in-page', (e) => {
webview.stopFindInPage('keepSelection')
})
const requestId = webview.findInPage('test')
console.log(requestId)
Event: 'will-navigate'
返回:
🌐 Returns:
url字符串
当用户或页面想要开始导航时会触发。当 window.location 对象发生变化或用户点击页面中的链接时,都可能发生此情况。
🌐 Emitted when a user or the page wants to start navigation. It can happen when
the window.location object is changed or a user clicks a link in the page.
当使用像 <webview>.loadURL 和 <webview>.back 这样的 API 编程方式启动导航时,该事件不会触发。
🌐 This event will not emit when the navigation is started programmatically with
APIs like <webview>.loadURL and <webview>.back.
它在页内导航时也不会触发,例如点击锚点链接或更新 window.location.hash。请使用 did-navigate-in-page 事件来实现此功能。
🌐 It is also not emitted during in-page navigation, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
调用 event.preventDefault() 不会产生任何效果。
🌐 Calling event.preventDefault() does NOT have any effect.
Event: 'will-frame-navigate'
返回:
🌐 Returns:
url字符串isMainFrame布尔值frameProcessId整数frameRoutingId整数
当用户或页面想要在 <webview> 或任何嵌入的框架中开始导航时,会触发此事件。当 window.location 对象发生更改或用户点击页面中的链接时,也可能发生。
🌐 Emitted when a user or the page wants to start navigation anywhere in the <webview>
or any frames embedded within. It can happen when the window.location object is
changed or a user clicks a link in the page.
当使用像 <webview>.loadURL 和 <webview>.back 这样的 API 编程方式启动导航时,该事件不会触发。
🌐 This event will not emit when the navigation is started programmatically with
APIs like <webview>.loadURL and <webview>.back.
它在页内导航时也不会触发,例如点击锚点链接或更新 window.location.hash。请使用 did-navigate-in-page 事件来实现此功能。
🌐 It is also not emitted during in-page navigation, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
调用 event.preventDefault() 不会产生任何效果。
🌐 Calling event.preventDefault() does NOT have any effect.
Event: 'did-start-navigation'
返回:
🌐 Returns:
url字符串isInPlace布尔值isMainFrame布尔值frameProcessId整数frameRoutingId整数
当任何帧(包括主帧)开始导航时触发。对于页内导航,isInPlace 将是 true。
🌐 Emitted when any frame (including main) starts navigating. isInPlace will be
true for in-page navigations.
Event: 'did-redirect-navigation'
返回:
🌐 Returns:
url字符串isInPlace布尔值isMainFrame布尔值frameProcessId整数frameRoutingId整数
在导航进程中发生服务器端重定向时触发。例如,302重定向。
🌐 Emitted after a server side redirect occurs during navigation. For example a 302 redirect.
Event: 'did-navigate'
返回:
🌐 Returns:
url字符串
导航完成时发出。
🌐 Emitted when a navigation is done.
此事件不会在页面内导航时触发,例如点击锚点链接或更新 window.location.hash。请使用 did-navigate-in-page 事件来实现此目的。
🌐 This event is not emitted for in-page navigations, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
Event: 'did-frame-navigate'
返回:
🌐 Returns:
url字符串httpResponseCode整数 - 对于非 HTTP 导航为 -1httpStatusText字符串 - 对于非 HTTP 导航为空,isMainFrame布尔值frameProcessId整数frameRoutingId整数
当任何帧导航完成时发出。
🌐 Emitted when any frame navigation is done.
此事件不会在页面内导航时触发,例如点击锚点链接或更新 window.location.hash。请使用 did-navigate-in-page 事件来实现此目的。
🌐 This event is not emitted for in-page navigations, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
Event: 'did-navigate-in-page'
返回:
🌐 Returns:
isMainFrame布尔值url字符串
当页内导航发生时发出。
🌐 Emitted when an in-page navigation happened.
当页面内导航发生时,页面 URL 会发生变化,但不会导致页面外的导航。这种情况的例子包括点击锚点链接或触发 DOM hashchange 事件时。
🌐 When in-page navigation happens, the page URL changes but does not cause
navigation outside of the page. Examples of this occurring are when anchor links
are clicked or when the DOM hashchange event is triggered.
Event: 'close'
当访客页面尝试自行关闭时触发。
🌐 Fired when the guest page attempts to close itself.
下面的示例代码在宿主尝试关闭自身时,将 webview 导航到 about:blank。
🌐 The following example code navigates the webview to about:blank when the
guest attempts to close itself.
const webview = document.querySelector('webview')
webview.addEventListener('close', () => {
webview.src = 'about:blank'
})
Event: 'ipc-message'
返回:
🌐 Returns:
- “frameId” [数字,数字] - 一对“[processId, frameId]”。
channel字符串argsany[]
当访客页面向嵌入器页面发送异步消息时触发。
🌐 Fired when the guest page has sent an asynchronous message to embedder page.
使用 sendToHost 方法和 ipc-message 事件,你可以在来宾页面和嵌入页面之间进行通信:
🌐 With sendToHost method and ipc-message event you can communicate
between guest page and embedder page:
// In embedder page.
const webview = document.querySelector('webview')
webview.addEventListener('ipc-message', (event) => {
console.log(event.channel)
// Prints "pong"
})
webview.send('ping')
// In guest page.
const { ipcRenderer } = require('electron')
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong')
})
Event: 'render-process-gone'
返回:
🌐 Returns:
detailsRenderProcessGoneDetails
当渲染进程意外消失时触发。这通常是因为它崩溃或被终止。
🌐 Fired when the renderer process unexpectedly disappears. This is normally because it was crashed or killed.
Event: 'destroyed'
当 WebContents 被销毁时触发。
🌐 Fired when the WebContents is destroyed.
Event: 'media-started-playing'
当媒体开始播放时发出。
🌐 Emitted when media starts playing.
Event: 'media-paused'
当媒体暂停或播放完毕时发出。
🌐 Emitted when media is paused or done playing.
Event: 'did-change-theme-color'
返回:
🌐 Returns:
themeColor字符串
当页面的主题颜色发生变化时触发。通常是由于遇到 meta 标签导致的:
🌐 Emitted when a page's theme color changes. This is usually due to encountering a meta tag:
<meta name='theme-color' content='#ff0000'>
Event: 'update-target-url'
返回:
🌐 Returns:
url字符串
当鼠标移动到链接上或键盘将焦点移动到链接时发出。
🌐 Emitted when mouse moves over a link or the keyboard moves the focus to a link.
Event: 'devtools-open-url'
返回:
🌐 Returns:
url字符串 - 被点击或选择的链接的 URL。
当在开发者工具中点击链接或在其上下文菜单中选择“在新标签页中打开”时触发。
🌐 Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu.
Event: 'devtools-search-query'
返回:
🌐 Returns:
event活动query字符串 - 要查询的文本。
当在其右键菜单中为文本选择“搜索”时触发。
🌐 Emitted when 'Search' is selected for text in its context menu.
Event: 'devtools-opened'
打开 DevTools 时发出。
🌐 Emitted when DevTools is opened.
Event: 'devtools-closed'
当 DevTools 关闭时发出。
🌐 Emitted when DevTools is closed.
Event: 'devtools-focused'
当 DevTools 聚焦/打开时发出。
🌐 Emitted when DevTools is focused / opened.
Event: 'context-menu'
返回:
🌐 Returns:
params对象x整数 - x 坐标。y整数 - y 坐标。linkURL字符串 - 包含触发上下文菜单节点的链接的 URL。linkText字符串 - 与链接相关的文本。如果链接内容是图片,该字符串可能为空。pageURL字符串 - 调用上下文菜单的顶层页面的 URL。frameURL字符串 - 调用上下文菜单的子框架的 URL。srcURL字符串 - 调用上下文菜单时该元素的源 URL。具有源 URL 的元素包括图片、音频和视频。mediaType字符串 - 上下文菜单被调用时节点的类型。可以是none、image、audio、video、canvas、file或plugin。hasImageContents布尔值 - 上下文菜单是否在具有非空内容的图片上被调用。isEditable布尔值 - 上下文是否可编辑。selectionText字符串 - 调用上下文菜单时所选文本的内容。titleText字符串 - 调用上下文菜单的所选项的标题文本。altText字符串 - 调用上下文菜单的所选项的替代文本。suggestedFilename字符串 - 建议的文件名,用于通过右键菜单的“另存为”选项保存文件时使用。selectionRect矩形 - 表示文档空间中选区坐标的矩形。selectionStartOffset编号 - 选中文本的起始位置。referrerPolicy引用来源 - 调用菜单的框架的引用来源策略。misspelledWord字符串 - 光标下的拼写错误单词(如果有)。dictionarySuggestionsstring[] - 一个建议词数组,用于向用户显示以替换misspelledWord。仅在存在拼写错误且启用了拼写检查器时可用。frameCharset字符串 - 调用菜单的帧的字符编码。formControlType字符串 - 调用上下文菜单的源。可能的值包括none、button-button、field-set、input-button、input-checkbox、input-color、input-date、input-datetime-local、input-email、input-file、input-hidden、input-image、input-month、input-number、input-password、input-radio、input-range、input-reset、input-search、input-submit、input-telephone、input-text、input-time、input-url、input-week、output、reset-button、select-list、select-list、select-multiple、select-one、submit-button和text-area。spellcheckEnabled布尔值 - 如果上下文是可编辑的,是否启用拼写检查。menuSourceType字符串 - 调用上下文菜单的输入来源。可以是none、mouse、keyboard、touch、touchMenu、longPress、longTap、touchHandle、stylus、adjustSelection或adjustSelectionReset。mediaFlags对象 - 调用上下文菜单的媒体元素的标志。inError布尔值 - 媒体元素是否已崩溃。isPaused布尔值 - 媒体元素是否已暂停。isMuted布尔值 - 媒体元素是否被静音。hasAudio布尔值 - 媒体元素是否有音频。isLooping布尔值 - 媒体元素是否循环播放。isControlsVisible布尔值 - 媒体元素的控件是否可见。canToggleControls布尔值 - 媒体元素的控件是否可切换。canPrint布尔值 - 媒体元素是否可以打印。canSave布尔值 - 表示媒体元素是否可以被下载。canShowPictureInPicture布尔值 - 媒体元素是否可以显示画中画。isShowingPictureInPicture布尔值 - 指示媒体元素当前是否正在显示画中画模式。canRotate布尔值 - 媒体元素是否可以旋转。canLoop布尔值 - 媒体元素是否可以循环播放。
editFlags对象 - 这些标志表示渲染器是否认为能够执行相应的操作。canUndo布尔值 - 渲染器认为它是否可以撤销。canRedo布尔值 - 渲染器认为它是否可以重做。canCut布尔值 - 渲染器认为它是否可以剪切。canCopy布尔值 - 渲染器认为它是否可以复制。canPaste布尔值 - 渲染器认为它是否可以粘贴。canDelete布尔值 - 渲染器认为它是否可以删除。canSelectAll布尔值 - 渲染器是否认为它可以选择全部。canEditRichly布尔值 - 渲染器是否认为它可以进行富文本编辑。
当有需要处理的新上下文菜单时发出。
🌐 Emitted when there is a new context menu that needs to be handled.