[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
跳转到主内容

<webview>标签

警告

Electron的 webview 标签基于 Chromium webview ,后者正在经历巨大的架构变化。 这将影响 webview 的稳定性,包括呈现、导航和事件路由。 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.

启用

默认情况下,Electron >= 5禁用 webview 标签。 在构造 BrowserWindow 时,需要通过设置 webviewTag webPreferences选项来启用标签。 For more information see the BrowserWindow constructor docs.

概览

在一个独立的 frame 和进程里显示外部 web 内容。

Process: Renderer
This class is not exported from the 'electron' module. 它只能作为 Electron API 中其他方法的返回值。

使用 webview 标签将'guest'内容 (例如网页) 嵌入到您的 Electron 应用中。 Guest 内容包含在 webview 容器内。 应用中的嵌入页面可以控制外来内容的布局和重绘。

iframe不同, webview 独立于您的应用程序运行。 它拥有和你的页面不一样的权限并且所嵌入的内容和你应用之间的交互都将是异步的。 这将保证你的应用对于嵌入的内容的安全性。 ** 注意: **从宿主页上调用 webview 的方法大多数都需要对主进程进行同步调用。

示例

若要在应用程序中嵌入网页, 请将 webview 标签添加到应用程序的被嵌入页面中 (这是将显示外来内容的应用程序页)。 在最简单的例子中, webview 标签包括网页的 src 和控制 webview 容器外观的 css 样式:

<webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview>

如果要以任何方式控制外来内容, 则可以写用于侦听 webview 事件的 JavaScript, 并使用 webview 方法响应这些事件。 下面是包含两个事件侦听器的示例代码: 一个侦听网页开始加载, 另一个用于网页停止加载, 并在加载时显示 "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>

内部实现

在内部 webview过程外 iframes(OOPIF)一起实施。 webview 标签本质上是一个自定义元素,使用 shadow DOM 将 iframe 元素包裹在里面。

因此, webview 的行为与跨域 iframe 非常相似,例如:

  • webview 中单击时,页面焦点将从嵌入器移动到 webview
  • 您无法将键盘、鼠标和滚动事件侦听器添加到 webview
  • 嵌入器框架和 webview 之间的所有反应都是异步的。

CSS 样式说明

请注意,webview 标签的样式使用 display:flex; 来确保 iframe在传统和 flex 布局一起使用的情况下填充其 webview 容器的全部高度和宽度。 除非指定内联布局的 display:inline-flex; ,否则请不要 覆盖默认 display:flex; CSS属性。

标签属性

webview 标签具有以下属性:

src

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

表示可见网址的 string 。 写入此属性将启动顶级跳转

更改 src 的值将重新加载当前页面。

src 属性还可以接受数据 URL, 如 data:text/plain, Hello, world!

nodeintegration

<webview src="https://www.google.com/" nodeintegration></webview>

一个 boolean。 当有此属性时, webview 中的访客页(guest page)将具有Node集成, 并且可以使用像 requireprocess 这样的node APIs 去访问低层系统资源。 Node 集成在访客页中默认是禁用的。

nodeintegrationinsubframes

<webview src="https://www.google.com/" nodeintegrationinsubframes></webview>

boolean 是一个实验选项,用于启动 NodeJS 中的 sub-frames 功能,比如在 webview 中的 iframes All your preloads will load for every iframe, you can use process.isMainFrame to determine if you are in the main frame or not. Node 集成在访客页中默认是禁用的。

plugins

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

一个 boolean。 When this attribute is present the guest page in webview will be able to use browser plugins. 插件默认为禁用状态。

preload

<!-- 来自文件 -->
<webview src="https://www.github.com/" preload="./test.js"></webview>
<!-- 或从asar归档文件中加载 -->
<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. 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 integration ,这个脚本仍然有能力去访问所有的 Node APIs, 但是当这个脚本执行执行完成之后,通过Node 注入的全局对象(global objects)将会被删除。

httpreferrer

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

为访客页面设置 referrer URL 的 string

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. Once the page is loaded, use the setUserAgent method to change the user agent.

disablewebsecurity

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

一个 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://electronjs.org" partition="electron"></webview>

设置页面使用的会话的 string。 如果 partitionpersist:开头, 该页面将使用持续的 session,并在所有页面生效,且使用同一个partition. 如果没有 persist: 前缀, 页面将使用 in-memory session. 通过分配相同的 partition, 多个页可以共享同一会话。 如果没有设置partition,app 将会使用默认的session。

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。 如果该属性存在,访客页面将允许打开新窗口。 Popup 默认是禁用状态。

webpreferences

<webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview>

string 是一个由逗号分割的字符串列表,其中指定了要设置在 webview 上的 Web 首选项。 The full list of supported preference strings can be found in BrowserWindow.

该字符串的格式与 window.open 中的功能字符串( the features string )相同。 只有自己名字的将被赋予 true 布尔值。 可以通过 = 来赋予其他值。 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 ,. 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>

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.

方法

webview 标签具有以下方法:

** 注意: **使用方法之前 webview 元素必须已被加载。

示例

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

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

  • url URL
  • options Object (可选)
    • httpReferrer (string | Referrer) (optional) - An HTTP Referrer url.
    • userAgent string (可选) - 发起请求的 userAgent.
    • extraHeaders string (可选) - 用 "\n" 分割的额外标题
    • postData (UploadRawData | UploadFile)[] (optional)
    • baseURLForDataURL string (可选) - 要加载的数据文件的根 url(带有路径分隔符). 只有当指定的 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).

webview 中加载目标 url,url 地址必须包含协议前缀,例如:http://file://

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

  • url string
  • options Object (可选)
    • headers Record<string, string> (optional) - HTTP request headers.

Initiates a download of the resource at url without navigating.

<webview>.getURL()

返回 string - 访客页的URL。

<webview>.getTitle()

返回 string - 访客页的标题。

<webview>.isLoading()

返回 boolean - 访客页是否仍然在加载资源。

<webview>.isLoadingMainFrame()

Returns boolean - Whether the main frame (and not just iframes or frames within it) is still loading.

<webview>.isWaitingForResponse()

返回 boolean - 访客页面是否正在等待页面主资源的第一响应。

<webview>.stop()

停止任何待处理的导航。

<webview>.reload()

刷新访客页。

<webview>.reloadIgnoringCache()

刷新访客页并忽略缓存。

<webview>.canGoBack()

返回 boolean - 访客页能否后退。

<webview>.canGoForward()

返回 boolean - 访客页能否前进。

<webview>.canGoToOffset(offset)

  • offset Integer

返回 boolean - 访客页能否前进到 offset

<webview>.clearHistory()

清除浏览器导航历史记录

<webview>.goBack()

使访客页后退。

<webview>.goForward()

使访客页前进。

<webview>.goToIndex(index)

  • index Integer

定位到指定的绝对索引。

<webview>.goToOffset(offset)

  • offset Integer

定位到相对于“当前入口”的指定的偏移。

<webview>.isCrashed()

Returns boolean - Whether the renderer process has crashed.

<webview>.setUserAgent(userAgent)

  • userAgent string

覆盖访客页的用户代理。

<webview>.getUserAgent()

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

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

Injects CSS into the current web page and returns a unique key for the inserted stylesheet.

<webview>.removeInsertedCSS(key)

  • key string

Returns Promise<void> - Resolves if the removal was successful.

Removes the inserted CSS from the current web page. 样式由 <webview>.insertCSS(css) 返回的 key 来标识。

<webview>.executeJavaScript(code[, userGesture])

  • code string
  • userGesture boolean (可选) - 默认为 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.

在页面中执行 code。 如果设置了userGesture,它将在页面中创建用户手势上下文。 像 requestFullScreen 这样的需要用户操作的HTML API可以利用这个选项来实现自动化。

<webview>.openDevTools()

打开 guest 页面的 DevTools 窗口。

<webview>.closeDevTools()

关闭 guest 页面的 DevTools 窗口。

<webview>.isDevToolsOpened()

返回 boolean - guest 页面是否打开了 Devtools。

<webview>.isDevToolsFocused()

返回 boolean - guest 页面的 DevTools 窗口是否聚焦。

<webview>.inspectElement(x, y)

  • x Integer
  • y Integer

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

Opens the DevTools for the service worker context present in the guest page.

<webview>.setAudioMuted(muted)

  • muted boolean

设置访客页是否静音。

<webview>.isAudioMuted()

返回 boolean - 访客页是否被静音。

<webview>.isCurrentlyAudible()

返回 boolean - 是否正在播放音频。

<webview>.undo()

在页面中执行编辑命令 undo

<webview>.redo()

在页面中执行编辑命令 redo

<webview>.cut()

在页面中执行编辑命令 cut

<webview>.copy()

在页面中执行编辑命令 copy

<webview>.centerSelection()

Centers the current text selection in page.

<webview>.paste()

在页面中执行编辑命令 paste

<webview>.pasteAndMatchStyle()

在页面中执行编辑命令 pasteAndMatchStyle

<webview>.delete()

在页面中执行编辑命令 delete

<webview>.selectAll()

在页面中执行编辑命令 selectAll

<webview>.unselect()

在页面中执行编辑命令 unselect

<webview>.scrollToTop()

Scrolls to the top of the current <webview>.

<webview>.scrollToBottom()

Scrolls to the bottom of the current <webview>.

<webview>.adjustSelection(options)

  • 选项 对象
    • start Number (optional) - Amount to shift the start index of the current selection.
    • 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.

See webContents.adjustSelection for examples.

<webview>.replace(text)

  • text string

在页面中执行编辑命令 replace

<webview>.replaceMisspelling(text)

  • text string

在页面中执行编辑命令 replaceMisspelling

<webview>.insertText(text)

  • text string

返回 Promise<void>

插入text 到焦点元素

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

  • text string - 要搜索的内容,必须非空。
  • options Object (可选)
    • forward boolean (可选) -向前或向后搜索,默认为 true
    • findNext boolean (可选) - 是否使用此请求开始一个新的文本查找会话。 对于初始请求应该为 true ,对后续请求为 false 。 默认值为 false.
    • matchCase boolean (optional) - Whether search should be case-sensitive, defaults to false.

Returns Integer - The request id used for the request.

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 string - Specifies the action to take place when ending <webview>.findInPage request.
    • clearSelection - Clear the selection.
    • keepSelection - Translate the selection into a normal selection.
    • activateSelection - Focus and click the selection node.

以提供的 action 停止 webview 的任何 findInPage

<webview>.print([options])

  • options Object (可选)
    • silent boolean (optional) - Don't ask user for print settings. 默认值为 false.
    • printBackground boolean (optional) - Prints the background color and image of the web page. 默认值为 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'.
    • color boolean (optional) - Set whether the printed web page will be in color or grayscale. 默认值为 true
    • margins Object (可选)
      • 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 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. 默认值为 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).
      • to number - Index of the last page to print (inclusive) (0-based).
    • duplexMode string (optional) - Set the duplex mode of the printed web page. 可以是 simplexshortEdgelongEdge
    • dpi Record<string, number> (optional)
      • horizontal number (optional) - The horizontal dpi.
      • vertical number (optional) - The vertical 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.

返回 Promise<void>

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

<webview>.printToPDF(options)

  • 选项 对象
    • landscape boolean (optional) - Paper orientation.true for landscape, false for portrait. 默认值为 false.
    • displayHeaderFooter boolean (optional) - Whether to display header and footer. 默认值为 false.
    • printBackground boolean (optional) - Whether to print background graphics. 默认值为 false.
    • scale number(optional) - Scale of the webpage rendering. Defaults to 1.
    • 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. 默认值为 Letter
    • margins Object (可选)
      • top number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches).
      • bottom number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches).
      • left number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches).
      • right number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches).
    • 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 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 string (optional) - HTML template for the print footer. Should use the same format as the headerTemplate.
    • 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 boolean (optional) Experimental - Whether or not to generate a tagged (accessible) PDF. 默认值为 false. As this property is experimental, the generated PDF may not adhere fully to PDF/UA and WCAG standards.
    • generateDocumentOutline boolean (optional) Experimental - Whether or not to generate a PDF document outline from content headers. 默认值为 false.

返回 Promise<Uint8Array> - 使用生成 PDF 的数据解决。

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

rect内捕获页面的快照。 省略 rect 将捕获整个可见页面。

<webview>.send(channel, ...args)

  • channel string
  • ...args any[]

返回 Promise<void>

通过channel向渲染器进程发送异步消息,可以发送任意参数。 The renderer process can handle the message by listening to the channel event with the ipcRenderer module.

See webContents.send for examples.

<webview>.sendToFrame(frameId, channel, ...args)

  • frameId [number, number] - [processId, frameId]
  • channel string
  • ...args any[]

返回 Promise<void>

通过channel向渲染器进程发送异步消息,可以发送任意参数。 The renderer process can handle the message by listening to the channel event with the ipcRenderer module.

See webContents.sendToFrame for examples.

<webview>.sendInputEvent(event)

返回 Promise<void>

Sends an input event to the page.

See webContents.sendInputEvent for detailed description of event object.

<webview>.setZoomFactor(factor)

  • factor number - 缩放比例

更改缩放倍数。 缩放系数是缩放百分比除以 100,即 300% = 3.0。

<webview>.setZoomLevel(level)

  • level number - 缩放等级。

更改缩放等级。 原始尺寸为 0,每升高或将顶代表缩放20%,大和小限制默认分区为 300% 和 50%。 The formula for this is scale := 1.2 ^ level.

注意: Chromium 级别的缩放策略是同源的,这意味着特定域的缩放级别将传播到具有相同域的所有窗口实例。 区分窗口 URL 将使缩放操作工作在每一个窗口。

<webview>.getZoomFactor()

返回 number - 当前的缩放比例。

<webview>.getZoomLevel()

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

<webview>.setVisualZoomLevelLimits(minimumLevel, maximumLevel)

  • minimumLevel number
  • maximumLevel number

返回 Promise<void>

设置最大和最小缩放级别。

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

DOM 事件

webview 标签具有以下有效的 DOM 事件:

Event: 'load-commit'

返回:

  • 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'

导航完成时触发,即选项卡的旋转器将停止旋转,并指派onload事件后。(译者:网页加载的过程中,并不是所有的浏览器都是转圈圈,而且浏览器版本不同,加载效果也有可能不一样。其中 ie 和 chrome 是转圈圈,safari 是进度条,firefox是一个小点左右来回移动--20180103)

Event: 'did-fail-load'

返回:

  • errorCode Integer
  • errorDescription string
  • validatedURL string
  • isMainFrame boolean

这个事件类似于 did-finish-load, 不过是在加载失败或取消后触发,例如调用了 window.stop()

Event: 'did-frame-finish-load'

返回:

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

事件:'did-attach'

Fired when attached to the embedder web contents.

事件: 'dom-ready'

当给定框架中的文档加载完成后,触发该事件。

事件: 'page-title-updated'

返回:

  • title string
  • explicitSet boolean

当导航时页面标题更新时触发。 当标题从文件 url 中合成时 explicitSet 为 false。

事件: 'page-favicon-updated'

返回:

  • favicons string[] - 由连接组成的数组。

当页面获取到 favicon 链接时,触发该事件。

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

当页面通过 HTML API 进入全屏时,触发该事件。

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

当页面通过 HTML API 退出全屏时,触发该事件。

Event: 'console-message'

返回:

  • level Integer - 日志级别,从0到3。 按顺序匹配 verbose, info, warningerror.
  • message string - 实际控制台消息
  • line Integer - 触发控制台消息的源代码行号。
  • sourceId string

当访客窗口记录一条控制台消息时,触发该事件。

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'

返回:

  • result Object
    • requestId Integer
    • activeMatchOrdinal Integer - 当前匹配位置。
    • matches Integer - 符合匹配条件的元素个数。
    • selectionArea Rectangle - 第一个匹配到区域的坐标。
    • finalUpdate boolean

Fired when a result is available for webview.findInPage request.

const webview = document.querySelector('webview')
webview.addEventListener('found-in-page', (e) => {
webview.stopFindInPage('keepSelection')
})

const requestId = webview.findInPage('test')
console.log(requestId)

Event: 'will-navigate'

返回:

  • url string

当用户或页面想要导航时触发。 它可能发生在 window.location 对象改变或用户点击页面上的链接时,可能会发生这种情况。

当使用如 <webview>.loadURL<webview>.back APIs 以编程方式导航时,将不会触发此事件。

It is also not emitted during in-page navigation, such as clicking anchor links or updating the window.location.hash. 可使用 did-navigate-in-page 事件。

Calling event.preventDefault() does NOT have any effect.

Event: 'will-frame-navigate'

返回:

  • url string
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

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 APIs 以编程方式导航时,将不会触发此事件。

It is also not emitted during in-page navigation, such as clicking anchor links or updating the window.location.hash. 可使用 did-navigate-in-page 事件。

Calling event.preventDefault() does NOT have any effect.

Event: 'did-start-navigation'

返回:

  • url string
  • isInPlace boolean
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

当任何 frame (包括 main) 开始导航时触发。 当页面内导航 isInPlacetrue

Event: 'did-redirect-navigation'

返回:

  • url string
  • isInPlace boolean
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

导航期间发生服务端重定向之后后触发。 例如,302 重定向。

Event: 'did-navigate'

返回:

  • url string

当导航完成时触发。

事件在页面内导航不会触发,例如点击锚点或更新 window.location.hash。 可使用 did-navigate-in-page 事件。

Event: 'did-frame-navigate'

返回:

  • url string
  • httpResponseCode Integer - -1 代表非 HTTP 导航。
  • httpStatusText string - 使用非 HTTP 导航时为空
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

当任意 frame 导航完成后触发。

事件在页面内导航不会触发,例如点击锚点或更新 window.location.hash。 可使用 did-navigate-in-page 事件。

Event: 'did-navigate-in-page'

返回:

  • isMainFrame boolean
  • url string

当发生页内导航时,触发该事件。

当发生页内导航时,虽然页面地址发生变化,但它并没有导航到其它页面。 例如,点击锚点链接,或者DOM的 hashchange事件被触发时,都会触发该事件。

事件: 'close'

当访客页面试图关闭自己时触发。

当访客试图关闭自己时,下面的示例代码将 webview 切换到 about:blank

const webview = document.querySelector('webview')
webview.addEventListener('close', () => {
webview.src = 'about:blank'
})

Event: 'ipc-message'

返回:

  • frameId [number, number] - pair of [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:

// 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'

返回:

Fired when the renderer process unexpectedly disappears. 这种情况通常因为进程崩溃或被杀死。

Event: 'plugin-crashed'

返回:

  • name string
  • version string

当插件进程崩溃时触发。

Event: 'destroyed'

当 WebContents 被摧毁时触发。

Event: 'media-started-playing'

多媒体开始播放时,触发该事件。

Event: 'media-paused'

当媒体文件暂停或播放完成的时候触发

Event: 'did-change-theme-color'

返回:

  • themeColor string

页面主页颜色改变时触发。 This is usually due to encountering a meta tag:

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

Event: 'update-target-url'

返回:

  • url string

当鼠标滑到,或者键盘切换到a连接时,触发该事件。

Event: 'devtools-open-url'

返回:

  • url string -被单击或选中的链接的 URL。

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

Event: 'devtools-search-query'

返回:

  • event Event
  • query string - text to query for.

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

Event: 'devtools-opened'

当开发者工具被打开时,触发该事件。

Event: 'devtools-closed'

当开发者工具被关闭时,触发该事件。

Event: 'devtools-focused'

当开发者工具被选中/打开时,触发该事件。

Event: 'context-menu'

返回:

  • params Object
    • x Integer - x 坐标。
    • y Integer - y 坐标。
    • linkURL string - URL of the link that encloses the node the context menu was invoked on.
    • linkText string - Text associated with the link. 如果链接的内容是图片,则可能为空的 string。
    • pageURL string - URL of the top level page that the context menu was invoked on.
    • frameURL string - URL of the subframe that the context menu was invoked on.
    • srcURL string - Source URL for the element that the context menu was invoked on. Elements 源 URLs 是 图片、音频 和 视频。
    • mediaType string - Type of the node the context menu was invoked on. 可以是 none, image, audio, video, canvas, fileplugin
    • hasImageContents boolean - Whether the context menu was invoked on an image which has non-empty contents.
    • isEditable boolean - 上下文内容是否可编辑。
    • 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.
    • 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. 仅当单词拼写错误且启用了拼写检查器时可用。
    • frameCharset string - The character encoding of the frame on which the menu was invoked.
    • 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 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.
    • mediaFlags Object - 调用菜单的媒体 element 的标志。
      • 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 - 这些标志表示渲染进程是否认为能够执行相应操作行为。
      • 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.

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