<webview>
Tag
Warning警告
Electron's Electron的webview
tag is based on Chromium's webview
, which is undergoing dramatic architectural changes. webview
标签基于Chromium的webview
,后者正在经历巨大的架构变化。This impacts the stability of 这会影响webviews
, including rendering, navigation, and event routing. webviews
的稳定性,包括渲染、导航和事件路由。We currently recommend to not use the 我们目前建议不要使用webview
tag and to consider alternatives, like iframe
, Electron's BrowserView
, or an architecture that avoids embedded content altogether.webview
标签,而是考虑其他选择,如iframe
、Electron的BrowserView
或完全避免嵌入内容的架构。
Enabling启用
By default the 默认情况下,在Electron>=5中禁用webview
tag is disabled in Electron >= 5. webview
标记。You need to enable the tag by setting the 在构建webviewTag
webPreferences option when constructing your BrowserWindow
. BrowserWindow
时,您需要通过设置webviewTag
webPreferences选项来启用标记。For more information see the BrowserWindow constructor docs.有关详细信息,请参阅BrowserWindow构造函数文档。
Overview概述
Display external web content in an isolated frame and process.在独立的框架和进程中显示外部web内容。
Process:进程:Renderer
This class is not exported from the 此类不是从'electron'
module. 'electron'
模块导出的。It is only available as a return value of other methods in the Electron API.它只能作为Electron API中其他方法的返回值使用。
Use the 使用webview
tag to embed 'guest' content (such as web pages) in your Electron app. webview
标签在您的Electron应用程序中嵌入“访客”内容(如网页)。The guest content is contained within the 来宾内容包含在webview
container. webview
容器中。An embedded page within your app controls how the guest content is laid out and rendered.应用程序中的嵌入式页面控制访客内容的布局和呈现方式。
Unlike an 与iframe
, the webview
runs in a separate process than your app. iframe
不同,webview
在一个独立于应用程序的进程中运行。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.从主页面在web视图上调用的大多数方法都需要对主进程进行同步调用。
Example实例
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). webview
标记添加到应用程序的嵌入程序页面(这是将显示访客内容的应用程序页面)。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
标记包括网页的src
和控制webview
容器外观的css样式:
<webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview>
If you want to control the guest content in any way, you can write JavaScript that listens for 如果您想以任何方式控制来宾内容,您可以编写JavaScript来侦听webview
events and responds to those events using the webview
methods. webview
事件,并使用webview
方法响应这些事件。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:以下是带有两个事件侦听器的示例代码:一个侦听网页开始加载,另一个侦听web页面停止加载,并在加载期间显示“loading…”消息:
<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内部实施
Under the hood 后台webview
is implemented with Out-of-Process iframes (OOPIFs). webview
是用进程外iframes(OOPIF)实现的。The webview
tag is essentially a custom element using shadow DOM to wrap an iframe
element inside it.webview
标记本质上是一个自定义元素,使用shadow DOM将iframe
元素封装在其中。
So the behavior of 因此,webview
is very similar to a cross-domain iframe
, as examples:webview
的行为与跨域iframe
非常相似,例如:
When clicking into a当点击进入webview
, the page focus will move from the embedder frame towebview
.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.webview
之间的所有反应都是异步的。
CSS Styling NotesCSS样式注释
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. webview
标记的样式在内部使用display:flex;
,以确保子iframe
元素在与传统和flexbox布局一起使用时填充其webview
容器的全部高度和宽度。Please do not overwrite the default 请不要覆盖默认display:flex;
CSS property, unless specifying display:inline-flex;
for inline layout.display:flex;
CSS属性,除非指定display:inline-flex;
用于内联布局。
Tag Attributes标记属性
The webview
tag has the following attributes:webview
标记具有以下属性:
src
<webview src="https://www.github.com/"></webview>
A 表示可见URL的string
representing the visible URL. string
。Writing to this attribute initiates top-level navigation.写入此属性将启动顶级导航。
Assigning 将src
its own value will reload the current page.src
指定为自己的值将重新加载当前页面。
The src
attribute can also accept data URLs, such as data:text/plain,Hello, world!
.src
属性还可以接受数据URL,例如data:text/plain,Hello, world!
。
nodeintegration
<webview src="http://www.google.com/" nodeintegration></webview>
A 一个boolean
. 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. webview
中的guest页面将具有节点集成,并且可以使用节点API(如require
和process
)来访问低级别系统资源。Node integration is disabled by default in the guest page.默认情况下,在来宾页面中禁用节点集成。
nodeintegrationinsubframes
<webview src="http://www.google.com/" nodeintegrationinsubframes></webview>
A 一个boolean
for the experimental option for enabling NodeJS support in sub-frames such as iframes inside the webview
. boolean
,用于在webview
中的子框架(如iframe)中启用NodeJS支持的实验选项。All your preloads will load for every iframe, you can use 所有预加载都将为每个iframe加载,您可以使用process.isMainFrame
to determine if you are in the main frame or not. process.isMainFrame
来确定您是否在主框架中。This option is disabled by default in the guest page.默认情况下,此选项在来宾页面中被禁用。
plugins
<webview src="https://www.github.com/" plugins></webview>
A 一个boolean
. boolean
。When this attribute is present the guest page in 当该属性存在时,webview
will be able to use browser plugins. webview
中的访客页面将能够使用浏览器插件。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>
A 一个string
that specifies a script that will be loaded before other scripts run in the guest page. string
,用于指定将在来宾页面中运行其他脚本之前加载的脚本。The protocol of script's URL must be 脚本URL的协议必须是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.file:
(即使在使用asar:archives时也是如此),因为它将由Node的require
在后台加载,后者将asar:
存档视为虚拟目录。
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.当访客页面没有节点集成时,此脚本仍然可以访问所有节点API,但在此脚本执行完成后,节点注入的全局对象将被删除。
httpreferrer
<webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview>
A 一个string
that sets the referrer URL for the guest page.string
,用于设置来宾页面的引用URL。
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>
A 一个string
that sets the user agent for the guest page before the page is navigated to. string
,用于在导航到guest页面之前为该页面设置用户代理。Once the page is loaded, use the 加载页面后,使用setUserAgent
method to change the user agent.setUserAgent
方法更改用户代理。
disablewebsecurity
<webview src="https://www.github.com/" disablewebsecurity></webview>
A 一个boolean
. boolean
。When this attribute is present the guest page will have web security disabled. 当此属性存在时,来宾页面将禁用web安全。Web security is enabled by default.默认情况下启用Web安全。
partition
<webview src="https://github.com" partition="persist:github"></webview>
<webview src="https://electronjs.org" partition="electron"></webview>
A 一个string
that sets the session used by the page. string
,用于设置页面使用的会话。If 如果partition
starts with persist:
, the page will use a persistent session available to all pages in the app with the same partition
. partition
以persistent:
开头,则页面将使用可用于应用程序中具有相同分区的所有页面的持久会话。if there is no 如果没有persist:
prefix, the page will use an in-memory session. persist:
前缀,页面将使用内存中的会话。By assigning the same 通过分配相同的partition
, multiple pages can share the same session. partition
,多个页面可以共享同一会话。If the 如果partition
is unset then default session of the app will be used.partition
未设置,则将使用应用程序的默认会话。
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.随后修改该值的尝试将失败,并出现DOM异常。
allowpopups
<webview src="https://www.github.com/" allowpopups></webview>
A 一个boolean
. 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>
A 一个string
which is a comma separated list of strings which specifies the web preferences to be set on the webview. string
,它是一个逗号分隔的字符串列表,用于指定要在web视图上设置的web首选项。The full list of supported preference strings can be found in BrowserWindow.支持的首选项字符串的完整列表可以在BrowserWindow中找到。
The string follows the same format as the features string in 该字符串的格式与window.open
. window.open
中的features字符串的格式相同。A name by itself is given a 名称本身被赋予一个true
boolean value. true
布尔值。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
.yes
和1
被解释为true
,而no
和0
被解释为false
。
enableblinkfeatures
<webview src="https://www.github.com/" enableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
A 一个string
which is a list of strings which specifies the blink features to be enabled separated by ,
. string
,它是指定要启用的闪烁功能的字符串列表,以,
分隔,。The full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.支持的功能字符串的完整列表可以在RuntimeEnabledFeatures.json5文件中找到。
disableblinkfeatures
<webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>
A 一个string
which is a list of strings which specifies the blink features to be disabled separated by ,
. string
,它是指定要禁用的闪烁功能的字符串列表,以,
分隔,。The full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.支持的功能字符串的完整列表可以在RuntimeEnabledFeatures.json5文件中找到。
Methods方法
The webview
tag has the following methods:webview
标记具有以下方法:
Note: The webview element must be loaded before using the methods.在使用方法之前,必须加载webview元素。
Example示例
const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', () => {
webview.openDevTools()
})
<webview>.loadURL(url[, options])
url
URL
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).promise将在页面加载完成时解析(请参阅did-finish-load),如果页面加载失败则拒绝(请参阅did-fail-load)。
Loads the 在webview中加载url
in the webview, the url
must contain the protocol prefix, e.g. the http://
or file://
.url
,url
必须包含协议前缀,例如http://
或file://
。
<webview>.downloadURL(url)
url
string
Initiates a download of the resource at 在url
without navigating.url
处启动资源下载,而不进行导航。
<webview>.getURL()
Returns返回string
- The URL of guest page.来宾页面的URL。
<webview>.getTitle()
Returns返回string
- The title of guest page.来宾页面的标题。
<webview>.isLoading()
Returns返回boolean
- Whether guest page is still loading resources.来宾页面是否仍在加载资源。
<webview>.isLoadingMainFrame()
Returns返回boolean
- Whether the main frame (and not just iframes or frames within it) is still loading.主框架(而不仅仅是iframe或其中的框架)是否仍在加载。
<webview>.isWaitingForResponse()
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()
Returns返回boolean
- Whether the guest page can go back.来宾页面是否可以返回。
<webview>.canGoForward()
Returns返回boolean
- Whether the guest page can go forward.访客页面是否可以继续。
<webview>.canGoToOffset(offset)
offset
Integer
Returns返回boolean
- Whether the guest page can go to 来宾页面是否可以进行offset
.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
Integer
Navigates to the specified absolute index.导航到指定的绝对索引。
<webview>.goToOffset(offset)
offset
Integer
Navigates to the specified offset from the "current entry".从“当前条目”导航到指定的偏移量。
<webview>.isCrashed()
Returns返回boolean
- Whether the renderer process has crashed.渲染器进程是否已崩溃。
<webview>.setUserAgent(userAgent)
userAgent
string
Overrides the user agent for the guest page.覆盖来宾页面的用户代理。
<webview>.getUserAgent()
Returns返回string
- The user agent for guest page.来宾页面的用户代理。
<webview>.insertCSS(css)
css
string
Returns返回Promise<string>
- A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via 一个承诺,它用插入的CSS的键解析,以后可以通过<webview>.removeInsertedCSS(key)
.<webview>.removeInsertedCSS(key)
来删除CSS。
Injects CSS into the current web page and returns a unique key for the inserted stylesheet.将CSS注入当前网页,并为插入的样式表返回一个唯一的键。
<webview>.removeInsertedCSS(key)
key
string
Returns返回Promise<void>
- Resolves if the removal was successful.解决删除是否成功。
Removes the inserted CSS from the current web page. 从当前网页中删除插入的CSS。The stylesheet is identified by its key, which is returned from 样式表由其键标识,该键从<webview>.insertCSS(css)
.<webview>.insertCSS(css)
返回。
<webview>.executeJavaScript(code[, userGesture])
code
stringuserGesture
boolean (optional) -Default默认值为false
.false
。
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.用执行的代码的结果解析的承诺,或者如果代码的结果是被拒绝的承诺,则被拒绝。
Evaluates 评估页面中的code
in page. code
。If 如果设置了userGesture
is set, it will create the user gesture context in the page. userGesture
,它将在页面中创建用户手势上下文。HTML APIs like 像requestFullScreen
, which require user action, can take advantage of this option for automation.requestFullScreen
这样需要用户操作的HTML API可以利用这个选项实现自动化。
<webview>.openDevTools()
Opens a DevTools window for guest page.为来宾页面打开DevTools窗口。
<webview>.closeDevTools()
Closes the DevTools window of guest page.关闭来宾页面的DevTools窗口。
<webview>.isDevToolsOpened()
Returns返回boolean
- Whether guest page has a DevTools window attached.访客页面是否附有DevTools窗口。
<webview>.isDevToolsFocused()
Returns返回boolean
- Whether DevTools window of guest page is focused.访客页面的DevTools窗口是否聚焦。
<webview>.inspectElement(x, y)
x
Integery
Integer
Starts inspecting element at position (开始检查来宾页面的位置x
, y
) of guest page.(x, y)
处的元素。
<webview>.inspectSharedWorker()
Opens the DevTools for the shared worker context present in the guest page.为来宾页面中的共享工作程序上下文打开DevTools。
<webview>.inspectServiceWorker()
Opens the DevTools for the service worker context present in the guest page.为来宾页面中的服务工作者上下文打开DevTools。
<webview>.setAudioMuted(muted)
muted
boolean
Set guest page muted.将来宾页面设置为静音。
<webview>.isAudioMuted()
Returns返回boolean
- Whether guest page has been muted.来宾页面是否已静音。
<webview>.isCurrentlyAudible()
Returns返回boolean
- Whether audio is currently playing.当前是否正在播放音频。
<webview>.undo()
Executes editing command 在页面中执行编辑命令undo
in page.undo
。
<webview>.redo()
Executes editing command 在页面中执行编辑命令redo
in page.redo
。
<webview>.cut()
Executes editing command 在页面中执行编辑命令cut
in page.cut
。
<webview>.copy()
Executes editing command 在页面中执行编辑命令copy
in page.copy
。
<webview>.paste()
Executes editing command 在页面中执行编辑命令paste
in page.paste
。
<webview>.pasteAndMatchStyle()
Executes editing command 在页面中执行编辑命令pasteAndMatchStyle
in page.pasteAndMatchStyle
。
<webview>.delete()
Executes editing command 在页面中执行编辑命令delete
in page.delete
。
<webview>.selectAll()
Executes editing command 在页面中执行编辑命令selectAll
in page.selectAll
。
<webview>.unselect()
Executes editing command 在页面中执行编辑命令unselect
in page.unselect
。
<webview>.replace(text)
text
string
Executes editing command 在页面中执行编辑命令replace
in page.replace
。
<webview>.replaceMisspelling(text)
text
string
Executes editing command 在页面中执行编辑命令replaceMisspelling
in page.replaceMisspelling
。
<webview>.insertText(text)
text
string
Returns返回Promise<void>
Inserts 在焦点元素中插入text
to the focused element.text
。
<webview>.findInPage(text[, options])
text
string -Content to be searched, must not be empty.要搜索的内容不能为空。
Returns返回Integer
- The request id used for the request.用于请求的请求id。
Starts a request to find all matches for the 启动一个请求,以查找网页中text
in the web page. text
的所有匹配项。The result of the request can be obtained by subscribing to found-in-page event.请求的结果可以通过订阅found-in-page事件来获得。
<webview>.stopFindInPage(action)
action
string -Specifies the action to take place when ending <webview>.findInPage request.指定在结束<webview>.findInPage请求时要执行的操作。clearSelection
-Clear the selection.清除所选内容。keepSelection
-Translate the selection into a normal selection.将所选内容转换为法线选择。activateSelection
-Focus and click the selection node.聚焦并单击选择节点。
Stops any 使用提供的findInPage
request for the webview
with the provided action
.action
停止对webview
的任何findInPage
请求。
<webview>.print([options])
Returns返回Promise<void>
Prints 打印webview
's web page. webview
的网页。Same as 与webContents.print([options])
.webContents.print([options])
相同。
<webview>.printToPDF(options)
Returns返回Promise<Uint8Array>
- Resolves with the generated PDF data.使用生成的PDF数据进行解析。
Prints webview
's web page as PDF, Same as webContents.printToPDF(options)
.webview
的网页打印为PDF,与webContents.printToPDF(options)
相同。
<webview>.capturePage([rect])
rect
Rectangle (optional) -The area of the page to be captured.要捕获的页面区域。
Returns返回Promise<NativeImage>
- Resolves with a NativeImage使用NativeImage进行解析
Captures a snapshot of the page within 在rect
. rect
中捕获页面的快照。Omitting 省略rect
will capture the whole visible page.rect
将捕获整个可见页面。
<webview>.send(channel, ...args)
channel
string...args
any[]
Returns返回Promise<void>
Send an asynchronous message to renderer process via 通过channel
, you can also send arbitrary arguments. channel
向渲染器进程发送异步消息,您也可以发送任意参数。The renderer process can handle the message by listening to the 渲染器进程可以通过ipcRenderer模块监听channel
event with the ipcRenderer module.channel
事件来处理消息。
See webContents.send for examples.有关示例,请参阅webContents.send。
<webview>.sendToFrame(frameId, channel, ...args)
frameId
[number, number] -[processId, frameId]
channel
string...args
any[]
Returns返回Promise<void>
Send an asynchronous message to renderer process via 通过channel
, you can also send arbitrary arguments. channel
向渲染器进程发送异步消息,您也可以发送任意参数。The renderer process can handle the message by listening to the 渲染器进程可以通过ipcRenderer模块监听channel
event with the ipcRenderer module.channel
事件来处理消息。
See webContents.sendToFrame for examples.有关示例,请参阅webContents.sendToFrame。
<webview>.sendInputEvent(event)
Returns返回Promise<void>
Sends an input 将输入event
to the page.event
发送到页面。
See webContents.sendInputEvent for detailed description of 有关event
object.event
对象的详细描述,请参阅webContents.sendInputEvent。
<webview>.setZoomFactor(factor)
factor
number -Zoom factor.缩放因子。
Changes the zoom factor to the specified factor. 将缩放因子更改为指定的因子。Zoom factor is zoom percent divided by 100, so 300% = 3.0.缩放因子是缩放百分比除以100,因此300%=3.0。
<webview>.setZoomLevel(level)
level
number -Zoom 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. 原始大小为0,每个高于或低于的增量表示放大或缩小20%,分别达到原始大小的300%和50%的默认限制。The formula for this is 这个公式是scale := 1.2 ^ level
.scale := 1.2 ^ level
。
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.:Chromium级别的缩放策略是同源的,这意味着特定域的缩放级别在具有相同域的所有窗口实例中传播。Differentiating the window URLs will make zoom work per-window.区分窗口URL将使每个窗口都能进行缩放。
<webview>.getZoomFactor()
Returns返回number
- the current zoom factor.当前缩放因子。
<webview>.getZoomLevel()
Returns返回number
- the current zoom level.当前缩放级别。
<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevel
numbermaximumLevel
number
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()
Returns返回number
- The WebContents ID of this 此webview
.webview
的WebContents ID。
DOM EventsDOM事件
The following DOM events are available to the 以下DOM事件可用于webview
tag:webview
标记:
Event: 'load-commit'
Returns:返回:
url
stringisMainFrame
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.这包括当前文档中的导航以及子帧文档级加载,但不包括异步资源加载。
Event: 'did-finish-load'
Fired when the navigation is done, i.e. the spinner of the tab will stop spinning, and the 导航完成后激发,即选项卡的微调器将停止旋转,并调度onload
event is dispatched.onload
事件。
Event: 'did-fail-load'
Returns:返回:
errorCode
IntegererrorDescription
stringvalidatedURL
stringisMainFrame
boolean
This event is like 此事件类似于did-finish-load
, but fired when the load failed or was cancelled, e.g. window.stop()
is invoked.did-finish-load
,但在加载失败或被取消时,例如调用window.stop()
时激发。
Event: 'did-frame-finish-load'
Returns:返回:
isMainFrame
boolean
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'
Fired when attached to the embedder web contents.附加到嵌入程序web内容时激发。
Event: 'dom-ready'
Fired when document in the given frame is loaded.加载给定框架中的文档时激发。
Event: 'page-title-updated'
Returns:返回:
title
stringexplicitSet
boolean
Fired when page title is set during navigation. 在导航过程中设置页面标题时激发。当标题是从文件url合成时,explicitSet
is false when title is synthesized from file url.explicitSet
为false
。
Event: 'page-favicon-updated'
Returns:返回:
favicons
string[] -Array of URLs.URL数组。
Fired when page receives favicon urls.当页面接收到集合夹URL时激发。
Event: 'enter-html-full-screen'
Fired when page enters fullscreen triggered by HTML API.当页面由HTML API触发进入全屏时激发。
Event: 'leave-html-full-screen'
Fired when page leaves fullscreen triggered by HTML API.当HTML API触发页面离开全屏时激发。
Event: 'console-message'
Returns:返回:
level
Integer -The log level, from 0 to 3.日志级别,从0到3。In order it matches按照顺序,它匹配verbose
,info
,warning
anderror
.verbose
、info
、warning
和error
。message
string -The actual console message实际控制台消息line
Integer -The line number of the source that triggered this console message触发此控制台消息的源的行号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)
})
Event: 'found-in-page'
Returns:返回:
result
ObjectrequestId
IntegeractiveMatchOrdinal
Integer -Position of the active match.活动匹配的位置。matches
Integer -Number of Matches.匹配数量。selectionArea
Rectangle -Coordinates of first match region.第一个匹配区域的坐标。finalUpdate
boolean
Fired when a result is available for webview.findInPage request.当结果可用于webview.findInPage请求时激发。
const webview = document.querySelector('webview')
webview.addEventListener('found-in-page', (e) => {
webview.stopFindInPage('keepSelection')
})
const requestId = webview.findInPage('test')
console.log(requestId)
Event: 'new-window'
Returns:返回:
url
stringframeName
stringdisposition
string -Can be可以是default
,foreground-tab
,background-tab
,new-window
,save-to-disk
andother
.default
,foreground-tab
、background-tab
、new-window
、save-to-disk
和other
。
Fired when the guest page attempts to open a new browser window.当来宾页面尝试打开新的浏览器窗口时激发。
The following example code opens the new url in system's default browser.下面的示例代码在系统的默认浏览器中打开新的url。
const { shell } = require('electron')
const webview = document.querySelector('webview')
webview.addEventListener('new-window', async (e) => {
const protocol = (new URL(e.url)).protocol
if (protocol === 'http:' || protocol === 'https:') {
await shell.openExternal(e.url)
}
})
Event: 'will-navigate'
Returns:返回:
url
string
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.window.location
对象更改或用户单击页面中的链接时,可能会发生这种情况。
This event will not emit when the navigation is started programmatically with APIs like 当使用<webview>.loadURL
and <webview>.back
.<webview>.loadURL
和<webview>.back
等API以编程方式启动导航时,此事件将不会发出。
It is also not emitted during in-page navigation, such as clicking anchor links or updating the 它也不会在页面内导航期间发出,例如单击锚链接或更新window.location.hash
. window.location.hash
。Use 为此,使用did-navigate-in-page
event for this purpose.did-navigate-in-page
事件。
Calling 调用event.preventDefault()
does NOT have any effect.event.preventDefault()
没有任何效果。
Event: 'did-start-navigation'
Returns:返回:
url
stringisInPlace
booleanisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
Emitted when any frame (including main) starts navigating. 当任何帧(包括主帧)开始导航时发出。对于页面内导航,isInPlace
will be true
for in-page navigations.isInPlace
将为true
。
Event: 'did-redirect-navigation'
Returns:返回:
url
stringisInPlace
booleanisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
Emitted after a server side redirect occurs during navigation. For example a 302 redirect.在导航过程中发生服务器端重定向后发出。例如302重定向。
Event: 'did-navigate'
Returns:返回:
url
string
Emitted when a navigation is done.导航完成时发出。
This event is not emitted for in-page navigations, such as clicking anchor links or updating the 对于页内导航(如单击锚链接或更新window.location.hash
. window.location.hash
),不会发出此事件。Use 为此,使用did-navigate-in-page
event for this purpose.did-navigate-in-page
事件。
Event: 'did-frame-navigate'
Returns:返回:
url
stringhttpResponseCode
Integer --1 for non HTTP navigations-1
用于非HTTP导航httpStatusText
string -empty for non HTTP navigations,对于非HTTP导航为空,isMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
Emitted when any frame navigation is done.在完成任何帧导航时发出。
This event is not emitted for in-page navigations, such as clicking anchor links or updating the 对于页内导航(如单击锚链接或更新window.location.hash
. window.location.hash
),不会发出此事件。Use 为此,使用did-navigate-in-page
event for this purpose.did-navigate-in-page
事件。
Event: 'did-navigate-in-page'
Returns:返回:
isMainFrame
booleanurl
string
Emitted when an in-page navigation happened.发生页内导航时发出。
When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. 当进行页面内导航时,页面URL会发生更改,但不会导致页面外的导航。Examples of this occurring are when anchor links are clicked or when the DOM 发生这种情况的例子是当点击锚链接或触发DOM hashchange
event is triggered.hashchange
事件时。
Event: 'close'
Fired when the guest page attempts to close itself.当来宾页面试图自行关闭时激发。
The following example code navigates the 以下示例代码在访客试图关闭自己时将webview
to about:blank
when the guest attempts to close itself.webview
导航到about:black
。
const webview = document.querySelector('webview')
webview.addEventListener('close', () => {
webview.src = 'about:blank'
})
Event: 'ipc-message'
Returns:返回:
frameId
[number, number] -pair of成对的[processId, frameId]
.[processId, frameId]
channel
stringargs
any[]
Fired when the guest page has sent an asynchronous message to embedder page.当来宾页面已向嵌入程序页面发送异步消息时激发。
With 通过sendToHost
method and ipc-message
event you can communicate between guest page and embedder page:sendToHost
方法和ipc-message
事件,您可以在guest页面和embedder页面之间进行通信:
// 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: 'crashed'
Fired when the renderer process is crashed.渲染器进程崩溃时激发。
Event: 'plugin-crashed'
Returns:返回:
name
stringversion
string
Fired when a plugin process is crashed.插件进程崩溃时激发。
Event: 'destroyed'
Fired when the WebContents is destroyed.当WebContents被销毁时激发。
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
string
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
string
Emitted when mouse moves over a link or the keyboard moves the focus to a link.当鼠标在链接上移动或键盘将焦点移动到链接时发出。
Event: 'devtools-opened'
Emitted when DevTools is opened.打开DevTools时发出。
Event: 'devtools-closed'
Emitted when DevTools is closed.关闭DevTools时发出。
Event: 'devtools-focused'
Emitted when DevTools is focused / opened.当DevTools被聚焦/打开时发出。
Event: 'context-menu'
Returns:返回:
params
Objectx
Integer -x coordinate.x坐标。y
Integer -y coordinate.y坐标。linkURL
string -URL of the link that encloses the node the context menu was invoked on.包含调用上下文菜单的节点的链接的URL。linkText
string -Text associated with the link. May be an empty string if the contents of the link are an image.与链接关联的文本。如果链接的内容是图像,则可能是一个空字符串。pageURL
string -URL of the top level page that the context menu was invoked on.调用上下文菜单的顶层页面的URL。frameURL
string -URL of the subframe that the context menu was invoked on.调用上下文菜单的子帧的URL。srcURL
string -Source URL for the element that the context menu was invoked on.对其调用上下文菜单的元素的源URL。Elements with source URLs are images, audio and video.具有源URL的元素是图像、音频和视频。mediaType
string -Type of the node the context menu was invoked on.对其调用上下文菜单的节点的类型。Can benone
,image
,audio
,video
,canvas
,file
orplugin
.hasImageContents
boolean -Whether the context menu was invoked on an image which has non-empty contents.是否在具有非空内容的图像上调用了上下文菜单。isEditable
boolean -Whether the context is editable.上下文是否可编辑。selectionText
string -Text of the selection that the context menu was invoked on.对其调用上下文菜单的所选内容的文本。titleText
string -Title text of the selection that the context menu was invoked on.调用上下文菜单的所选内容的标题文本。altText
string -Alt text of the selection that the context menu was invoked on.调用上下文菜单时所选内容的Alt文本。suggestedFilename
string -Suggested filename to be used when saving file through 'Save Link As' option of context menu.通过上下文菜单的“链接另存为”选项保存文件时使用的建议文件名。selectionRect
Rectangle -Rect representing the coordinates in the document space of the selection.矩形,表示所选内容在文档空间中的坐标。selectionStartOffset
number -Start position of the selection text.选择文本的起始位置。referrerPolicy
Referrer -The referrer policy of the frame on which the menu is invoked.调用菜单的框架的引用策略。misspelledWord
string -The misspelled word under the cursor, if any.游标下拼写错误的单词(如果有的话)。dictionarySuggestions
string[] -An array of suggested words to show the user to replace the一组建议的单词,向用户显示如何替换misspelledWord
.misspelledWord
。Only available if there is a misspelled word and spellchecker is enabled.只有当有拼写错误的单词并且启用了拼写检查器时才可用。frameCharset
string -The character encoding of the frame on which the menu was invoked.调用菜单的帧的字符编码。inputFieldType
string -If the context menu was invoked on an input field, the type of that field.如果上下文菜单是在输入字段上调用的,则为该字段的类型。Possible values are可能的值有none
,plainText
,password
,other
.none
、plainText
、password
和other
。spellcheckEnabled
boolean -If the context is editable, whether or not spellchecking is enabled.如果上下文是可编辑的,则无论是否启用拼写检查。menuSourceType
string -Input source that invoked the context menu.调用上下文菜单的输入源。Can be可以是none
,mouse
,keyboard
,touch
,touchMenu
,longPress
,longTap
,touchHandle
,stylus
,adjustSelection
, oradjustSelectionReset
.none
、mouse
、keyboard
、touch
、touchMenu
、longPress
、longTap
、touchHandle
、stylus
、adjustSelection
或adjustSelectionReset
。mediaFlags
Object -The flags for the media element the context menu was invoked on.对其调用上下文菜单的媒体元素的标志。inError
boolean -Whether the media element has crashed.媒体元素是否已崩溃。isPaused
boolean -Whether the media element is paused.媒体元素是否已暂停。isMuted
boolean -Whether the media element is muted.媒体元素是否已静音。hasAudio
boolean -Whether the media element has audio.媒体元素是否有音频。isLooping
boolean -Whether the media element is looping.媒体元素是否正在循环。isControlsVisible
boolean -Whether the media element's controls are visible.媒体元素的控件是否可见。canToggleControls
boolean -Whether the media element's controls are toggleable.媒体元素的控件是否可切换。canPrint
boolean -Whether the media element can be printed.是否可以打印介质元素。canSave
boolean -Whether or not the media element can be downloaded.是否可以下载媒体元素。canShowPictureInPicture
boolean -Whether the media element can show picture-in-picture.媒体元素是否可以画中画。isShowingPictureInPicture
boolean -Whether the media element is currently showing picture-in-picture.媒体元素当前是否显示画中画。canRotate
boolean -Whether the media element can be rotated.媒体元素是否可以旋转。canLoop
boolean -Whether the media element can be looped.媒体元素是否可以循环。
editFlags
Object -These flags indicate whether the renderer believes it is able to perform the corresponding action.这些标志指示渲染器是否相信它能够执行相应的操作。canUndo
boolean -Whether the renderer believes it can undo.渲染器是否认为可以撤消。canRedo
boolean -Whether the renderer believes it can redo.渲染器是否认为可以重做。canCut
boolean -Whether the renderer believes it can cut.渲染器是否认为它可以剪切。canCopy
boolean -Whether the renderer believes it can copy.渲染器是否认为它可以复制。canPaste
boolean -Whether the renderer believes it can paste.渲染器是否认为它可以粘贴。canDelete
boolean -Whether the renderer believes it can delete.渲染器是否认为可以删除。canSelectAll
boolean -Whether the renderer believes it can select all.渲染器是否认为可以选择全部。canEditRichly
boolean -Whether the renderer believes it can edit text richly.渲染器是否相信它可以丰富地编辑文本。
Emitted when there is a new context menu that needs to be handled.当存在需要处理的新上下文菜单时发出。