Skip to main content

<webview> 标签

¥<webview> Tag

警告

¥Warning

Electron 的 webview 标签基于 Chromium 的 webview,后者正在经历巨大的架构变化。这会影响 webviews 的稳定性,包括渲染、导航和事件路由。目前,我们建议不要使用 webview 标签,并考虑替代方案,例如 iframeWebContentsView 或完全避免嵌入内容的架构。

¥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

默认情况下,webview 标签在 Electron >= 5 中被禁用。你需要在构建 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

在隔离的框架和进程中显示外部 Web 内容。

¥Display external web content in an isolated frame and process.

进程:渲染器
该类不是从 'electron' 模块导出的。它仅可用作 Electron API 中其他方法的返回值。

¥Process: Renderer
This class is not exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.

使用 webview 标签在你的 Electron 应用中嵌入 'guest' 内容(例如网页)。访客内容包含在 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 在与你的应用不同的进程中运行。它没有与你的网页相同的权限,并且你的应用和嵌入内容之间的所有交互都将是异步的。这可以确保你的应用免受嵌入内容的影响。注意:从主机页面调用 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. Note: Most methods called on the webview from the host page require a synchronous call to the main process.

示例

¥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 是通过 进程外 iframe (OOPIF) 实现的。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

    ¥When clicking into a webview, the page focus will move from the embedder frame to webview.

  • 你无法向 webview 添加键盘、鼠标和滚动事件监听器。

    ¥You can not add keyboard, mouse, and scroll event listeners to webview.

  • 嵌入器框架和 webview 之间的所有反应都是异步的。

    ¥All reactions between the embedder frame and webview are asynchronous.

CSS 样式注释

¥CSS Styling Notes

请注意,webview 标签的样式在内部使用 display:flex;,以确保在与传统布局和 Flexbox 布局一起使用时,子 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>

代表可见 URL 的 string。写入此属性会启动顶层导航。

¥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 中的访客页面将具有节点集成,并且可以使用 requireprocess 等 Node API 来访问底层系统资源。默认情况下,访客页面中禁用节点集成。

¥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>

boolean 用于在子框架(例如 webview 内的 iframe)中启用 NodeJS 支持的实验选项。你的所有预加载将为每个 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 在后台加载,后者将 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,用于设置访客页面的引荐来源网址。

¥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。如果 partitionpersist: 开头,则页面将使用可用于应用中具有相同 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 是逗号分隔的字符串列表,指定要在 Web 视图上设置的 Web 首选项。支持的首选项字符串的完整列表可以在 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 布尔值。通过包含 = 后跟该值,可以将首选项设置为另一个值。特殊值 yes1 被解释为 true,而 no0 被解释为 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 是一个字符串列表,指定要启用的闪烁功能,以 , 分隔。支持的功能字符串的完整列表可以在 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 是一个字符串列表,指定由 , 分隔的要禁用的闪烁功能。支持的功能字符串的完整列表可以在 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 元素。

¥Note: The webview element must be loaded before using the methods.

示例

¥Example

const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', () => {
webview.openDevTools()
})

<webview>.loadURL(url[, options])

  • url URL

  • options 对象(可选)

    ¥options Object (optional)

    • httpReferrer(字符串 | 推荐人)(可选) - HTTP 引用网址。

      ¥httpReferrer (string | Referrer) (optional) - An HTTP Referrer url.

    • userAgent 字符串(可选) - 发起请求的用户代理。

      ¥userAgent string (optional) - A user agent originating the request.

    • extraHeaders 字符串(可选) - 由 "\n" 分隔的额外标头

      ¥extraHeaders string (optional) - Extra headers separated by "\n"

    • postData (上传原始数据 | UploadFile)[](可选)

      ¥postData (UploadRawData | UploadFile)[] (optional)

    • baseURLForDataURL 字符串(可选) - 数据 url 加载的文件的基本 url(带有尾随路径分隔符)。仅当指定的 url 是数据 url 并且需要加载其他文件时才需要这样做。

      ¥baseURLForDataURL string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified url is a data url and needs to load other files.

返回 Promise<void> - 当页面加载完成时,该 Promise 将会解析(参见 did-finish-load);如果页面加载失败,该 Promise 将被拒绝(参见 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).

在 web 视图中加载 urlurl 必须包含协议前缀,例如 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 string

  • options 对象(可选)

    ¥options Object (optional)

    • headers 记录<字符串,字符串>(可选) - HTTP 请求标头。

      ¥headers Record<string, string> (optional) - HTTP request headers.

无需导航即可启动 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 整数

    ¥offset Integer

返回 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 整数

    ¥index Integer

导航到指定的绝对索引。

¥Navigates to the specified absolute index.

<webview>.goToOffset(offset)

  • offset 整数

    ¥offset Integer

导航到距 "当前条目" 的指定偏移量。

¥Navigates to the specified offset from the "current entry".

<webview>.isCrashed()

返回 boolean - 渲染器进程是否崩溃。

¥Returns boolean - Whether the renderer process has crashed.

<webview>.setUserAgent(userAgent)

  • userAgent 字符串

    ¥userAgent string

覆盖访客页面的用户代理。

¥Overrides the user agent for the guest page.

<webview>.getUserAgent()

返回 string - 访客页面的用户代理。

¥Returns string - The user agent for guest page.

<webview>.insertCSS(css)

  • css 字符串

    ¥css string

返回 Promise<string> - 一个使用插入 CSS 的密钥进行解析的 promise,稍后可以使用该密钥通过 <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 字符串

    ¥key string

返回 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 字符串

    ¥code string

  • userGesture 布尔值(可选) - 默认 false

    ¥userGesture boolean (optional) - Default 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 - 访客页面的 DevTools 窗口是否聚焦。

¥Returns boolean - Whether DevTools window of guest page is focused.

<webview>.inspectElement(x, y)

  • x 整数

    ¥x Integer

  • y 整数

    ¥y Integer

开始检查访客页面位置 (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 布尔值

    ¥muted boolean

将访客页面设置为静音。

¥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)

  • options 对象

    ¥options Object

    • start 数量(可选) - 移动当前选择的起始索引的量。

      ¥start Number (optional) - Amount to shift the start index of the current selection.

    • end 数量(可选) - 移动当前选择的结束索引的量。

      ¥end Number (optional) - Amount to shift the end index of the current selection.

将焦点框中当前文本选择的起点和终点调整给定的量。负值会将所选内容移向文档的开头,正值会将所选内容移向文档的末尾。

¥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 字符串

    ¥text string

执行页面中的编辑命令 replace

¥Executes editing command replace in page.

<webview>.replaceMisspelling(text)

  • text 字符串

    ¥text string

执行页面中的编辑命令 replaceMisspelling

¥Executes editing command replaceMisspelling in page.

<webview>.insertText(text)

  • text 字符串

    ¥text string

返回 Promise<void>

¥Returns Promise<void>

text 插入到焦点元素中。

¥Inserts text to the focused element.

<webview>.findInPage(text[, options])

  • text 字符串 - 要搜索的内容,不能为空。

    ¥text string - Content to be searched, must not be empty.

  • options 对象(可选)

    ¥options Object (optional)

    • forward 布尔值(可选) - 向前或向后搜索,默认为 true

      ¥forward boolean (optional) - Whether to search forward or backward, defaults to true.

    • findNext 布尔值(可选) - 是否使用此请求开始新的文本查找会话。对于初始请求应为 true,对于后续请求应为 false。默认为 false

      ¥findNext boolean (optional) - Whether to begin a new text finding session with this request. Should be true for initial requests, and false for follow-up requests. Defaults to false.

    • matchCase 布尔值(可选) - 搜索是否区分大小写,默认为 false

      ¥matchCase boolean (optional) - Whether search should be case-sensitive, defaults to false.

返回 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 请求时要执行的操作。

    ¥action string - Specifies the action to take place when ending <webview>.findInPage request.

    • clearSelection - 清除选择。

      ¥clearSelection - Clear the selection.

    • keepSelection - 将选择转换为正常选择。

      ¥keepSelection - Translate the selection into a normal selection.

    • activateSelection - 聚焦并单击选择节点。

      ¥activateSelection - Focus and click the selection node.

使用提供的 action 停止对 webview 的任何 findInPage 请求。

¥Stops any findInPage request for the webview with the provided action.

<webview>.print([options])

  • options 对象(可选)

    ¥options Object (optional)

    • silent 布尔值(可选) - 不要询问用户打印设置。默认为 false

      ¥silent boolean (optional) - Don't ask user for print settings. Default is false.

    • printBackground 布尔值(可选) - 打印网页的背景颜色和图片。默认为 false

      ¥printBackground boolean (optional) - Prints the background color and image of the web page. Default is false.

    • deviceName 字符串(可选) - 设置要使用的打印机设备名称。必须是系统定义的名称,而不是 'friendly' 名称,例如 'Brother_QL_820NWB' 而不是 'Brother QL-820NWB'。

      ¥deviceName string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'.

    • color 布尔值(可选) - 设置打印的网页是彩色还是灰度。默认为 true

      ¥color boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is true.

    • margins 对象(可选)

      ¥margins Object (optional)

      • marginType 字符串(可选) - 可以是 defaultnoneprintableAreacustom。如果选择 custom,你还需要指定 topbottomleftright

        ¥marginType string (optional) - Can be default, none, printableArea, or custom. If custom is chosen, you will also need to specify top, bottom, left, and right.

      • top 号码(可选) - 打印网页的上边距(以像素为单位)。

        ¥top number (optional) - The top margin of the printed web page, in pixels.

      • bottom 号码(可选) - 打印网页的下边距,以像素为单位。

        ¥bottom number (optional) - The bottom margin of the printed web page, in pixels.

      • left 号码(可选) - 打印网页的左边距,以像素为单位。

        ¥left number (optional) - The left margin of the printed web page, in pixels.

      • right 号码(可选) - 打印网页的右边距,以像素为单位。

        ¥right number (optional) - The right margin of the printed web page, in pixels.

    • landscape 布尔值(可选) - 网页是否应以横向模式打印。默认为 false

      ¥landscape boolean (optional) - Whether the web page should be printed in landscape mode. Default is false.

    • scaleFactor 号码(可选) - 网页的比例因子。

      ¥scaleFactor number (optional) - The scale factor of the web page.

    • pagesPerSheet 号码(可选) - 每页要打印的页数。

      ¥pagesPerSheet number (optional) - The number of pages to print per page sheet.

    • collate 布尔值(可选) - 网页是否需要整理。

      ¥collate boolean (optional) - Whether the web page should be collated.

    • copies 号码(可选) - 要打印的网页份数。

      ¥copies number (optional) - The number of copies of the web page to print.

    • pageRanges Object[] (optional) - 要打印的页面范围。

      ¥pageRanges Object[] (optional) - The page range to print.

      • from 数字 - 要打印的第一页的索引(从 0 开始)。

        ¥from number - Index of the first page to print (0-based).

      • to 数字 - 要打印的最后一页的索引(包含)(从 0 开始)。

        ¥to number - Index of the last page to print (inclusive) (0-based).

    • duplexMode 字符串(可选) - 设置打印网页的双面模式。可以是 simplexshortEdgelongEdge

      ¥duplexMode string (optional) - Set the duplex mode of the printed web page. Can be simplex, shortEdge, or longEdge.

    • dpi 记录<字符串,数字>(可选)

      ¥dpi Record<string, number> (optional)

      • horizontal 号码(可选) - 水平 dpi。

        ¥horizontal number (optional) - The horizontal dpi.

      • vertical 号码(可选) - 垂直 dpi。

        ¥vertical number (optional) - The vertical dpi.

    • header 字符串(可选) - 要打印为页眉的字符串。

      ¥header string (optional) - string to be printed as page header.

    • footer 字符串(可选) - 要打印为页脚的字符串。

      ¥footer string (optional) - string to be printed as page footer.

    • pageSize 字符串 | 尺寸(可选) - 指定打印文档的页面尺寸。可以是 A3A4A5LegalLetterTabloid 或包含 height(以微米为单位)的对象。

      ¥pageSize string | Size (optional) - Specify page size of the printed document. Can be A3, A4, A5, Legal, Letter, Tabloid or an Object containing height in microns.

返回 Promise<void>

¥Returns Promise<void>

打印 webview 的网页。与 webContents.print([options]) 相同。

¥Prints webview's web page. Same as webContents.print([options]).

<webview>.printToPDF(options)

  • options 对象

    ¥options Object

    • landscape 布尔值(可选) - 纸张方向。true 为横向,false 为纵向。默认为 false。

      ¥landscape boolean (optional) - Paper orientation.true for landscape, false for portrait. Defaults to false.

    • displayHeaderFooter 布尔值(可选) - 是否显示页眉和页脚。默认为 false。

      ¥displayHeaderFooter boolean (optional) - Whether to display header and footer. Defaults to false.

    • printBackground 布尔值(可选) - 是否打印背景图形。默认为 false。

      ¥printBackground boolean (optional) - Whether to print background graphics. Defaults to false.

    • scale 号(可选) - 网页渲染的比例。默认为 1。

      ¥scale number(optional) - Scale of the webpage rendering. Defaults to 1.

    • pageSize 字符串 | 尺寸(可选) - 指定生成的 PDF 的页面大小。可以是 A0A1A2A3A4A5A6LegalLetterTabloidLedger 或包含 heightwidth(以英寸为单位)的对象。默认为 Letter

      ¥pageSize string | Size (optional) - Specify page size of the generated PDF. Can be A0, A1, A2, A3, A4, A5, A6, Legal, Letter, Tabloid, Ledger, or an Object containing height and width in inches. Defaults to Letter.

    • margins 对象(可选)

      ¥margins Object (optional)

      • top 号码(可选) - 上边距(以英寸为单位)。默认为 1 厘米(~0.4 英寸)。

        ¥top number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches).

      • bottom 号码(可选) - Bottom margin in inches.默认为 1 厘米(~0.4 英寸)。

        ¥bottom number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches).

      • left 号码(可选) - 左边距以英寸为单位。默认为 1 厘米(~0.4 英寸)。

        ¥left number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches).

      • right 号码(可选) - 右边距以英寸为单位。默认为 1 厘米(~0.4 英寸)。

        ¥right number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches).

    • pageRanges 字符串(可选) - 要打印的页面范围,例如 '1-5, 8, 11-13'。默认为空字符串,表示打印所有页面。

      ¥pageRanges string (optional) - Page ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.

    • headerTemplate 字符串(可选) - 打印标题的 HTML 模板。应该是有效的 HTML 标记,具有以下用于将打印值注入其中的类:date(格式化打印日期)、title(文档标题)、url(文档位置)、pageNumber(当前页码)和 totalPages(文档中的总页数)。例如,<span class=title></span> 将生成包含标题的范围。

      ¥headerTemplate string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: date (formatted print date), title (document title), url (document location), pageNumber (current page number) and totalPages (total pages in the document). For example, <span class=title></span> would generate span containing the title.

    • footerTemplate 字符串(可选) - 打印页脚的 HTML 模板。应使用与 headerTemplate 相同的格式。

      ¥footerTemplate string (optional) - HTML template for the print footer. Should use the same format as the headerTemplate.

    • preferCSSPageSize 布尔值(可选) - 是否首选 css 定义的页面大小。默认为 false,在这种情况下,内容将缩放以适合纸张尺寸。

      ¥preferCSSPageSize boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.

    • generateTaggedPDF 布尔值(可选)实验 - 是否生成带标签的(可访问的)PDF。默认为 false。由于此属性是实验性的,生成的 PDF 可能不完全符合 PDF/UA 和 WCAG 标准。

      ¥generateTaggedPDF boolean (optional) Experimental - Whether or not to generate a tagged (accessible) PDF. Defaults to false. As this property is experimental, the generated PDF may not adhere fully to PDF/UA and WCAG standards.

    • generateDocumentOutline 布尔值(可选)实验 - 是否从内容标题生成 PDF 文档大纲。默认为 false。

      ¥generateDocumentOutline boolean (optional) Experimental - Whether or not to generate a PDF document outline from content headers. Defaults to false.

返回 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 长方形(可选) - 要捕获的页面区域。

    ¥rect Rectangle (optional) - The area of the page to be captured.

返回 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 字符串

    ¥channel string

  • ...args 任何[]

    ¥...args any[]

返回 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]

    ¥frameId [number, number] - [processId, frameId]

  • channel 字符串

    ¥channel string

  • ...args 任何[]

    ¥...args any[]

返回 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.

有关 event 对象的详细说明,请参阅 webContents.sendInputEvent

¥See webContents.sendInputEvent for detailed description of event object.

<webview>.setZoomFactor(factor)

  • factor 数字 - 缩放系数。

    ¥factor number - Zoom 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 数字 - 缩放级别。

    ¥level number - Zoom level.

将缩放级别更改为指定级别。原始大小为 0,上方或下方的每个增量表示放大或缩小 20%,分别达到原始大小的 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 将使缩放针对每个窗口起作用。

¥NOTE: The zoom policy at the Chromium level is same-origin, meaning that the zoom level for a specific domain propagates across all instances of windows with the same domain. Differentiating the window URLs will make zoom work per-window.

<webview>.getZoomFactor()

返回 number - 当前的缩放系数。

¥Returns number - the current zoom factor.

<webview>.getZoomLevel()

返回 number - 当前的缩放级别。

¥Returns number - the current zoom level.

<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)

  • minimumLevel 数字

    ¥minimumLevel number

  • maximumLevel 数字

    ¥maximumLevel number

返回 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

以下 DOM 事件可用于 webview 标签:

¥The following DOM events are available to the webview tag:

事件:'load-commit'

¥Event: 'load-commit'

返回:

¥Returns:

  • url 字符串

    ¥url string

  • isMainFrame 布尔值

    ¥isMainFrame boolean

当负载已提交时触发。这包括当前文档内的导航以及子框架文档级加载,但不包括异步资源加载。

¥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.

事件:'did-finish-load'

¥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.

事件:'did-fail-load'

¥Event: 'did-fail-load'

返回:

¥Returns:

  • errorCode 整数

    ¥errorCode Integer

  • errorDescription 字符串

    ¥errorDescription string

  • validatedURL 字符串

    ¥validatedURL string

  • isMainFrame 布尔值

    ¥isMainFrame boolean

此事件类似于 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.

事件:'did-frame-finish-load'

¥Event: 'did-frame-finish-load'

返回:

¥Returns:

  • isMainFrame 布尔值

    ¥isMainFrame boolean

当框架完成导航时触发。

¥Fired when a frame has done navigation.

事件:'did-start-loading'

¥Event: 'did-start-loading'

对应于选项卡的旋转器开始旋转的时间点。

¥Corresponds to the points in time when the spinner of the tab starts spinning.

事件:'did-stop-loading'

¥Event: 'did-stop-loading'

对应于选项卡的旋转器停止旋转的时间点。

¥Corresponds to the points in time when the spinner of the tab stops spinning.

事件:'did-attach'

¥Event: 'did-attach'

当附加到嵌入器 Web 内容时触发。

¥Fired when attached to the embedder web contents.

事件:'dom-ready'

¥Event: 'dom-ready'

加载给定框架中的文档时触发。

¥Fired when document in the given frame is loaded.

事件:'page-title-updated'

¥Event: 'page-title-updated'

返回:

¥Returns:

  • title 字符串

    ¥title string

  • explicitSet 布尔值

    ¥explicitSet boolean

在导航期间设置页面标题时触发。当标题是从文件 url 合成时,explicitSet 为 false。

¥Fired when page title is set during navigation. explicitSet is false when title is synthesized from file url.

事件:'page-favicon-updated'

¥Event: 'page-favicon-updated'

返回:

¥Returns:

  • favicons 字符串[] - URL 数组。

    ¥favicons string[] - Array of URLs.

当页面收到 favicon url 时触发。

¥Fired when page receives favicon urls.

事件:'enter-html-full-screen'

¥Event: 'enter-html-full-screen'

当页面由 HTML API 触发进入全屏时触发。

¥Fired when page enters fullscreen triggered by HTML API.

事件:'leave-html-full-screen'

¥Event: 'leave-html-full-screen'

当页面离开全屏时由 HTML API 触发。

¥Fired when page leaves fullscreen triggered by HTML API.

事件:'console-message'

¥Event: 'console-message'

返回:

¥Returns:

  • level 整数 - 日志级别,从 0 到 3。按照顺序,它匹配 verboseinfowarningerror

    ¥level Integer - The log level, from 0 to 3. In order it matches verbose, info, warning and error.

  • message 字符串 - 实际的控制台消息

    ¥message string - The actual console message

  • line 整数 - 触发此控制台消息的源的行号

    ¥line Integer - The line number of the source that triggered this console message

  • sourceId 字符串

    ¥sourceId string

当来宾窗口记录控制台消息时触发。

¥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)
})

事件:'found-in-page'

¥Event: 'found-in-page'

返回:

¥Returns:

  • result 对象

    ¥result Object

    • requestId 整数

      ¥requestId Integer

    • activeMatchOrdinal 整数 - 当前比赛的位置。

      ¥activeMatchOrdinal Integer - Position of the active match.

    • matches 整数 - 比赛次数。

      ¥matches Integer - Number of Matches.

    • selectionArea 长方形 - 第一个匹配区域的坐标。

      ¥selectionArea Rectangle - Coordinates of first match region.

    • finalUpdate 布尔值

      ¥finalUpdate boolean

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)

事件:'will-navigate'

¥Event: 'will-navigate'

返回:

¥Returns:

  • url 字符串

    ¥url string

当用户或页面想要开始导航时发出。当 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.

事件:'will-frame-navigate'

¥Event: 'will-frame-navigate'

返回:

¥Returns:

  • url 字符串

    ¥url string

  • isMainFrame 布尔值

    ¥isMainFrame boolean

  • frameProcessId 整数

    ¥frameProcessId Integer

  • frameRoutingId 整数

    ¥frameRoutingId Integer

当用户或页面想要在 <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.

事件:'did-start-navigation'

¥Event: 'did-start-navigation'

返回:

¥Returns:

  • url 字符串

    ¥url string

  • isInPlace 布尔值

    ¥isInPlace boolean

  • isMainFrame 布尔值

    ¥isMainFrame boolean

  • frameProcessId 整数

    ¥frameProcessId Integer

  • frameRoutingId 整数

    ¥frameRoutingId Integer

当任何框架(包括主框架)开始导航时发出。对于页内导航,isInPlace 将是 true

¥Emitted when any frame (including main) starts navigating. isInPlace will be true for in-page navigations.

事件:'did-redirect-navigation'

¥Event: 'did-redirect-navigation'

返回:

¥Returns:

  • url 字符串

    ¥url string

  • isInPlace 布尔值

    ¥isInPlace boolean

  • isMainFrame 布尔值

    ¥isMainFrame boolean

  • frameProcessId 整数

    ¥frameProcessId Integer

  • frameRoutingId 整数

    ¥frameRoutingId Integer

在导航期间发生服务器端重定向后发出。例如 302 重定向。

¥Emitted after a server side redirect occurs during navigation. For example a 302 redirect.

事件:'did-navigate'

¥Event: 'did-navigate'

返回:

¥Returns:

  • url 字符串

    ¥url string

导航完成时发出。

¥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.

事件:'did-frame-navigate'

¥Event: 'did-frame-navigate'

返回:

¥Returns:

  • url 字符串

    ¥url string

  • httpResponseCode 整数 - -1 表示非 HTTP 导航

    ¥httpResponseCode Integer - -1 for non HTTP navigations

  • httpStatusText 字符串 - 对于非 HTTP 导航为空,

    ¥httpStatusText string - empty for non HTTP navigations,

  • isMainFrame 布尔值

    ¥isMainFrame boolean

  • frameProcessId 整数

    ¥frameProcessId Integer

  • frameRoutingId 整数

    ¥frameRoutingId Integer

当任何帧导航完成时发出。

¥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.

事件:'did-navigate-in-page'

¥Event: 'did-navigate-in-page'

返回:

¥Returns:

  • isMainFrame 布尔值

    ¥isMainFrame boolean

  • url 字符串

    ¥url string

当页内导航发生时发出。

¥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.

事件:'close'

¥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'
})

事件:'ipc-message'

¥Event: 'ipc-message'

返回:

¥Returns:

  • frameId [数字,数字] - 一对 [processId, frameId]

    ¥frameId [number, number] - pair of [processId, frameId].

  • channel 字符串

    ¥channel string

  • args 任何[]

    ¥args any[]

当访客页面向嵌入器页面发送异步消息时触发。

¥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')
})

事件:'render-process-gone'

¥Event: 'render-process-gone'

返回:

¥Returns:

当渲染器进程意外消失时触发。这通常是因为它坠毁或死亡。

¥Fired when the renderer process unexpectedly disappears. This is normally because it was crashed or killed.

事件:'plugin-crashed'

¥Event: 'plugin-crashed'

返回:

¥Returns:

  • name 字符串

    ¥name string

  • version 字符串

    ¥version string

当插件进程崩溃时触发。

¥Fired when a plugin process is crashed.

事件:'destroyed'

¥Event: 'destroyed'

当 WebContents 被销毁时触发。

¥Fired when the WebContents is destroyed.

事件:'media-started-playing'

¥Event: 'media-started-playing'

当媒体开始播放时发出。

¥Emitted when media starts playing.

事件:'media-paused'

¥Event: 'media-paused'

当媒体暂停或播放完毕时发出。

¥Emitted when media is paused or done playing.

事件:'did-change-theme-color'

¥Event: 'did-change-theme-color'

返回:

¥Returns:

  • themeColor 字符串

    ¥themeColor string

当页面的主题颜色更改时发出。这通常是由于遇到元标记:

¥Emitted when a page's theme color changes. This is usually due to encountering a meta tag:

<meta name='theme-color' content='#ff0000'>

事件:'update-target-url'

¥Event: 'update-target-url'

返回:

¥Returns:

  • url 字符串

    ¥url string

当鼠标移动到链接上或键盘将焦点移动到链接时发出。

¥Emitted when mouse moves over a link or the keyboard moves the focus to a link.

事件:'devtools-open-url'

¥Event: 'devtools-open-url'

返回:

¥Returns:

  • url 字符串 - 单击或选择的链接的 URL。

    ¥url string - URL of the link that was clicked or selected.

在 DevTools 中单击链接或在其上下文菜单中为链接选择 '在新选项卡中打开' 时发出。

¥Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu.

事件:'devtools-search-query'

¥Event: 'devtools-search-query'

返回:

¥Returns:

  • event 事件

    ¥event Event

  • query 字符串 - 要查询的文本。

    ¥query string - text to query for.

当在上下文菜单中选择 '搜索' 作为文本时发出。

¥Emitted when 'Search' is selected for text in its context menu.

事件:'devtools-opened'

¥Event: 'devtools-opened'

打开 DevTools 时发出。

¥Emitted when DevTools is opened.

事件:'devtools-closed'

¥Event: 'devtools-closed'

当 DevTools 关闭时发出。

¥Emitted when DevTools is closed.

事件:'devtools-focused'

¥Event: 'devtools-focused'

当 DevTools 聚焦/打开时发出。

¥Emitted when DevTools is focused / opened.

事件:'context-menu'

¥Event: 'context-menu'

返回:

¥Returns:

  • params 对象

    ¥params Object

    • x 整数 - x 坐标。

      ¥x Integer - x coordinate.

    • y 整数 - y 坐标。

      ¥y Integer - y coordinate.

    • linkURL 字符串 - 包含调用上下文菜单的节点的链接的 URL。

      ¥linkURL string - URL of the link that encloses the node the context menu was invoked on.

    • linkText 字符串 - 与链接关联的文本。如果链接的内容是图片,则可能是空字符串。

      ¥linkText string - Text associated with the link. May be an empty string if the contents of the link are an image.

    • pageURL 字符串 - 调用上下文菜单的顶层页面的 URL。

      ¥pageURL string - URL of the top level page that the context menu was invoked on.

    • frameURL 字符串 - 调用上下文菜单的子框架的 URL。

      ¥frameURL string - URL of the subframe that the context menu was invoked on.

    • srcURL 字符串 - 调用上下文菜单的元素的源 URL。具有源 URL 的元素是图片、音频和视频。

      ¥srcURL string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video.

    • mediaType 字符串 - 调用上下文菜单的节点的类型。可以是 noneimageaudiovideocanvasfileplugin

      ¥mediaType string - Type of the node the context menu was invoked on. Can be none, image, audio, video, canvas, file or plugin.

    • hasImageContents 布尔值 - 是否在具有非空内容的图片上调用上下文菜单。

      ¥hasImageContents boolean - Whether the context menu was invoked on an image which has non-empty contents.

    • isEditable 布尔值 - 上下文是否可编辑。

      ¥isEditable boolean - Whether the context is editable.

    • selectionText 字符串 - 调用上下文菜单的选择文本。

      ¥selectionText string - Text of the selection that the context menu was invoked on.

    • titleText 字符串 - 调用上下文菜单的选项的标题文本。

      ¥titleText string - Title text of the selection that the context menu was invoked on.

    • altText 字符串 - 调用上下文菜单的选项的替代文本。

      ¥altText string - Alt text of the selection that the context menu was invoked on.

    • suggestedFilename 字符串 - 通过上下文菜单的 '保存链接为' 选项保存文件时建议使用的文件名。

      ¥suggestedFilename string - Suggested filename to be used when saving file through 'Save Link As' option of context menu.

    • selectionRect 长方形 - 表示所选内容在文档空间中的坐标的矩形。

      ¥selectionRect Rectangle - Rect representing the coordinates in the document space of the selection.

    • selectionStartOffset 数字 - 选择文本的起始位置。

      ¥selectionStartOffset number - Start position of the selection text.

    • referrerPolicy 推荐人 - 调用菜单的框架的引用策略。

      ¥referrerPolicy Referrer - The referrer policy of the frame on which the menu is invoked.

    • misspelledWord 字符串 - 光标下拼写错误的单词(如果有)。

      ¥misspelledWord string - The misspelled word under the cursor, if any.

    • dictionarySuggestions 字符串[] - 一系列建议单词,以显示用户替换 misspelledWord。仅当存在拼写错误的单词并且启用了拼写检查器时才可用。

      ¥dictionarySuggestions string[] - An array of suggested words to show the user to replace the misspelledWord. Only available if there is a misspelled word and spellchecker is enabled.

    • frameCharset 字符串 - 调用菜单的帧的字符编码。

      ¥frameCharset string - The character encoding of the frame on which the menu was invoked.

    • formControlType 字符串 - 调用上下文菜单的源。可能的值包括 nonebutton-buttonfield-setinput-buttoninput-checkboxinput-colorinput-dateinput-datetime-localinput-emailinput-fileinput-hiddeninput-imageinput-monthinput-numberinput-passwordinput-radioinput-rangeinput-resetinput-searchinput-submitinput-telephoneinput-textinput-timeinput-urlinput-weekoutputreset-buttonselect-listselect-listselect-multipleselect-onesubmit-buttontext-area

      ¥formControlType string - The source that the context menu was invoked on. Possible values include 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, and text-area,

    • spellcheckEnabled 布尔值 - 如果上下文可编辑,则无论是否启用拼写检查。

      ¥spellcheckEnabled boolean - If the context is editable, whether or not spellchecking is enabled.

    • menuSourceType 字符串 - 调用上下文菜单的输入源。可以是 nonemousekeyboardtouchtouchMenulongPresslongTaptouchHandlestylusadjustSelectionadjustSelectionReset

      ¥menuSourceType string - Input source that invoked the context menu. Can be none, mouse, keyboard, touch, touchMenu, longPress, longTap, touchHandle, stylus, adjustSelection, or adjustSelectionReset.

    • mediaFlags 对象 - 调用上下文菜单的媒体元素的标志。

      ¥mediaFlags Object - The flags for the media element the context menu was invoked on.

      • inError 布尔值 - 媒体元素是否崩溃。

        ¥inError boolean - Whether the media element has crashed.

      • isPaused 布尔值 - 媒体元素是否暂停。

        ¥isPaused boolean - Whether the media element is paused.

      • isMuted 布尔值 - 媒体元素是否静音。

        ¥isMuted boolean - Whether the media element is muted.

      • hasAudio 布尔值 - 媒体元素是否有音频。

        ¥hasAudio boolean - Whether the media element has audio.

      • isLooping 布尔值 - 媒体元素是否循环。

        ¥isLooping boolean - Whether the media element is looping.

      • isControlsVisible 布尔值 - 媒体元素的控件是否可见。

        ¥isControlsVisible boolean - Whether the media element's controls are visible.

      • canToggleControls 布尔值 - 媒体元素的控件是否可切换。

        ¥canToggleControls boolean - Whether the media element's controls are toggleable.

      • canPrint 布尔值 - 是否可以打印媒体元素。

        ¥canPrint boolean - Whether the media element can be printed.

      • canSave 布尔值 - 媒体元素是否可以下载。

        ¥canSave boolean - Whether or not the media element can be downloaded.

      • canShowPictureInPicture 布尔值 - 媒体元素是否可以显示画中画。

        ¥canShowPictureInPicture boolean - Whether the media element can show picture-in-picture.

      • isShowingPictureInPicture 布尔值 - 媒体元素当前是否显示画中画。

        ¥isShowingPictureInPicture boolean - Whether the media element is currently showing picture-in-picture.

      • canRotate 布尔值 - 媒体元素是否可以旋转。

        ¥canRotate boolean - Whether the media element can be rotated.

      • canLoop 布尔值 - 媒体元素是否可以循环播放。

        ¥canLoop boolean - Whether the media element can be looped.

    • editFlags 对象 - 这些标志指示渲染器是否认为它能够执行相应的操作。

      ¥editFlags Object - These flags indicate whether the renderer believes it is able to perform the corresponding action.

      • canUndo 布尔值 - 渲染器是否相信它可以撤消。

        ¥canUndo boolean - Whether the renderer believes it can undo.

      • canRedo 布尔值 - 渲染器是否相信它可以重做。

        ¥canRedo boolean - Whether the renderer believes it can redo.

      • canCut 布尔值 - 渲染器是否相信它可以剪切。

        ¥canCut boolean - Whether the renderer believes it can cut.

      • canCopy 布尔值 - 渲染器是否相信它可以复制。

        ¥canCopy boolean - Whether the renderer believes it can copy.

      • canPaste 布尔值 - 渲染器是否认为可以粘贴。

        ¥canPaste boolean - Whether the renderer believes it can paste.

      • canDelete 布尔值 - 渲染器是否相信它可以删除。

        ¥canDelete boolean - Whether the renderer believes it can delete.

      • canSelectAll 布尔值 - 渲染器是否相信它可以选择全部。

        ¥canSelectAll boolean - Whether the renderer believes it can select all.

      • canEditRichly 布尔值 - 渲染器是否相信它可以丰富地编辑文本。

        ¥canEditRichly boolean - Whether the renderer believes it can edit text richly.

当有需要处理的新上下文菜单时发出。

¥Emitted when there is a new context menu that needs to be handled.