Skip to main content

<webview> Tag

Warning警告

Electron's webview tag is based on Chromium's webview, which is undergoing dramatic architectural changes. Electron的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标签,而是考虑其他选择,如iframeElectron的BrowserView或完全避免嵌入内容的架构。

Enabling启用

By default the webview tag is disabled in Electron >= 5. 默认情况下,在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 webview events and responds to those events using the webview methods. 如果您想以任何方式控制来宾内容,您可以编写JavaScript来侦听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 to webview.当点击进入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 string representing the visible URL. 表示可见URL的stringWriting 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. 一个booleanWhen 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(如requireprocess)来访问低级别系统资源。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 process.isMainFrame to determine if you are in the main frame or not. 所有预加载都将为每个iframe加载,您可以使用process.isMainFrame来确定您是否在主框架中。This option is disabled by default in the guest page.默认情况下,此选项在来宾页面中被禁用。

plugins

<webview src="https://www.github.com/" plugins></webview>

A boolean. 一个booleanWhen 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 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.脚本URL的协议必须是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. 一个booleanWhen 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. 如果partitionpersistent:开头,则页面将使用可用于应用程序中具有相同分区的所有页面的持久会话。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. 一个booleanWhen 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.特殊值yes1被解释为true,而no0被解释为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
  • options Object (optional)
    • httpReferrer (string | Referrer) (optional) - An HTTP Referrer url.HTTP回溯url。
    • userAgent string (optional) - A user agent originating the request.发起请求的用户代理。
    • extraHeaders string (optional) - Extra headers separated by "\n"用“\n”分隔的额外标头
    • postData (UploadRawData | UploadFile)[] (optional)
    • baseURLForDataURL string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. 要由数据url加载的文件的基本url(带尾随路径分隔符)。This is needed only if the specified url is a data url and needs to load other files.只有当指定的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 url in the webview, the url must contain the protocol prefix, e.g. the http:// or file://.在webview中加载urlurl必须包含协议前缀,例如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 <webview>.removeInsertedCSS(key).一个承诺,它用插入的CSS的键解析,以后可以通过<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 string
  • userGesture 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. 评估页面中的codeIf 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 Integer
  • y 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.要搜索的内容不能为空。
  • options Object (optional)
    • forward boolean (optional) - Whether to search forward or backward, defaults to true.是向前搜索还是向后搜索,默认为true
    • 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. 对于初始请求应为true,对于后续请求应为falseDefaults to false.默认为false
    • matchCase boolean (optional) - Whether search should be case-sensitive, defaults to false.搜索是否应区分大小写,默认为false

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

  • options Object (optional)
    • silent boolean (optional) - Don't ask user for print settings. 不要向用户询问打印设置。Default is false.默认值为false
    • printBackground boolean (optional) - Prints the background color and image of the web page. 打印网页的背景色和图像。Default is false.默认值为false
    • 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'.必须是系统定义的名称,而不是“友好”名称,例如“Brother_QL_820NWB”和“Brother QL-820NWB”。
    • color boolean (optional) - Set whether the printed web page will be in color or grayscale. 设置打印的网页是彩色还是灰度。Default is true.默认值为true
    • margins Object (optional)
      • marginType string (optional) - Can be default, none, printableArea, or custom. 可以是defaultnoneprintableAreacustomIf custom is chosen, you will also need to specify top, bottom, left, and right.如果选择了custom,你将需要指定topbottomleftright
      • top number (optional) - The top margin of the printed web page, in pixels.打印的网页的上边距,以像素为单位。
      • bottom number (optional) - The bottom margin of the printed web page, in pixels.打印的网页的下边距,以像素为单位。
      • left number (optional) - The left margin of the printed web page, in pixels.打印的网页的左边距,以像素为单位。
      • right number (optional) - The right margin of the printed web page, in pixels.打印的网页的右边距,以像素为单位。
    • landscape boolean (optional) - Whether the web page should be printed in landscape mode. 是否应以横向模式打印网页。Default is false.默认值为false
    • scaleFactor number (optional) - The scale factor of the web page.网页的比例因子。
    • pagesPerSheet number (optional) - The number of pages to print per page sheet.每页工作表要打印的页数。
    • collate boolean (optional) - Whether the web page should be collated.是否应对网页进行整理。
    • copies number (optional) - The number of copies of the web page to print.要打印的网页的副本数。
    • pageRanges Object[] (optional) - The page range to print.要打印的页面范围。
      • from number - Index of the first page to print (0-based).要打印的第一页的索引(基于0)。
      • to number - Index of the last page to print (inclusive) (0-based).要打印的最后一页的索引(包括在内)(从0开始)。
    • duplexMode string (optional) - Set the duplex mode of the printed web page. 设置打印网页的双面打印模式。Can be simplex, shortEdge, or longEdge.可以是simplexshortEdgelongEdge
    • dpi Record<string, number> (optional)
      • horizontal number (optional) - The horizontal dpi.水平dpi。
      • vertical number (optional) - The vertical dpi.垂直dpi。
    • header string (optional) - string to be printed as page header.要打印为页眉的字符串。
    • footer string (optional) - string to be printed as page footer.要打印为页脚的字符串。
    • 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.可以是A3A4A5LegalLetterTabloid或包含了height的对象(单位为微米)。

Returns返回Promise<void>

Prints webview's web page. 打印webview的网页。Same as webContents.print([options]).webContents.print([options])相同。

<webview>.printToPDF(options)

  • options Object
    • headerFooter Record<string, string> (optional) - the header and footer for the PDF.PDF的页眉和页脚。
      • title string - The title for the PDF header.PDF标题的标题。
      • url string - the url for the PDF footer.PDF页脚的url。
    • landscape boolean (optional) - true for landscape, false for portrait.对横向是true,对竖向是false
    • marginsType Integer (optional) - Specifies the type of margins to use. 指定要使用的页边距类型。Uses 0 for default margin, 1 for no margin, and 2 for minimum margin. 使用0表示默认边距,使用1表示无边距,使用2表示最小边距。and width in microns.width以微米为单位。
    • scaleFactor number (optional) - The scale factor of the web page. 网页的比例因子。Can range from 0 to 100.可以在0到100之间。
    • pageRanges Record<string, number> (optional) - The page range to print. 要打印的页面范围。On macOS, only the first range is honored.在macOS上,只有第一个范围受到尊重。
      • from number - Index of the first page to print (0-based).要打印的第一页的索引(基于0)。
      • to number - Index of the last page to print (inclusive) (0-based).要打印的最后一页的索引(包括在内)(从0开始)。
    • pageSize string | Size (optional) - Specify page size of the generated PDF. 指定生成的PDF的页面大小。Can be A3, A4, A5, Legal, Letter, Tabloid or an Object containing height可以是A3A4A5LegalLetterTabloid或包含height的对象
    • printBackground boolean (optional) - Whether to print CSS backgrounds.是否打印CSS背景。
    • printSelectionOnly boolean (optional) - Whether to print selection only.是否只打印所选内容。

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 channel event with the ipcRenderer module.渲染器进程可以通过ipcRenderer模块监听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 channel event with the ipcRenderer module.渲染器进程可以通过ipcRenderer模块监听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 number
  • maximumLevel 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 webview tag:以下DOM事件可用于webview标记:

Event: 'load-commit'

Returns:返回:

  • url string
  • 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.这包括当前文档中的导航以及子帧文档级加载,但不包括异步资源加载。

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 Integer
  • errorDescription string
  • validatedURL string
  • isMainFrame 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 string
  • explicitSet boolean

Fired when page title is set during navigation. 在导航过程中设置页面标题时激发。explicitSet is false when title is synthesized from file url.当标题是从文件url合成时,explicitSetfalse

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 and error.按照顺序,它匹配verboseinfowarningerror
  • 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 Object
    • requestId Integer
    • activeMatchOrdinal 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 string
  • frameName string
  • disposition string - Can be default, foreground-tab, background-tab, new-window, save-to-disk and other.可以是default, foreground-tabbackground-tabnew-windowsave-to-diskother
  • options BrowserWindowConstructorOptions - The options which should be used for creating the new BrowserWindow.应用于创建新BrowserWindow的选项。

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.hashUse 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 string
  • isInPlace boolean
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId 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 string
  • isInPlace boolean
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId 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 string
  • httpResponseCode Integer - -1 for non HTTP navigations-1用于非HTTP导航
  • httpStatusText string - empty for non HTTP navigations,对于非HTTP导航为空,
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId 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 boolean
  • url 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 hashchange event is triggered.发生这种情况的例子是当点击锚链接或触发DOM 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 string
  • args 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 string
  • version 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 Object
    • x 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 be none, image, audio, video, canvas, file or plugin.
    • 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. 一组建议的单词,向用户显示如何替换misspelledWordOnly 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.可能的值有noneplainTextpasswordother
    • 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, or adjustSelectionReset.可以是nonemousekeyboardtouchtouchMenulongPresslongTaptouchHandlestylusadjustSelectionadjustSelectionReset
    • 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.当存在需要处理的新上下文菜单时发出。