Skip to main content

webContents

Render and control web pages.渲染和控制网页。

Process:进程:Main

webContents is an EventEmitter. 是一个EventEmitterIt is responsible for rendering and controlling a web page and is a property of the BrowserWindow object. 它负责呈现和控制网页,是BrowserWindow对象的属性。An example of accessing the webContents object:访问webContents对象的示例:

const { BrowserWindow } = require('electron')

const win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL('http://github.com')

const contents = win.webContents
console.log(contents)

Methods方法

These methods can be accessed from the webContents module:可以从webContents模块访问这些方法:

const { webContents } = require('electron')
console.log(webContents)

webContents.getAllWebContents()

Returns返回WebContents[] - An array of all webContents instances. 所有webContents实例的数组。This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages.这将包含所有窗口、web视图、打开的devtools和devtools扩展后台页面的web内容。

webContents.getFocusedWebContents()

Returns返回webContents | null - The web contents that is focused in this application, otherwise returns null.此应用程序中关注的web内容,否则返回null

webContents.fromId(id)

  • id Integer

Returns返回webContents | undefined - A WebContents instance with the given ID, or undefined if there is no WebContents associated with the given ID.具有给定ID的webContents实例,或者如果没有与给定ID关联的webContents则为undefined

webContents.fromDevToolsTargetId(targetId)

  • targetId string - The Chrome DevTools Protocol TargetID associated with the WebContents instance.webContents实例关联的Chrome DevTools协议TargetID

Returns返回webContents | undefined - A WebContents instance with the given TargetID, or undefined if there is no WebContents associated with the given TargetID.具有给定TargetIDwebContents实例,或者如果没有与给定TargetID关联的webContents,则为TargetID

When communicating with the Chrome DevTools Protocol, it can be useful to lookup a WebContents instance based on its assigned TargetID.当与Chrome DevTools协议通信时,根据其分配的TargetID查找webContents实例可能很有用。

async function lookupTargetId (browserWindow) {
const wc = browserWindow.webContents
await wc.debugger.attach('1.3')
const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo')
const { targetId } = targetInfo
const targetWebContents = await webContents.fromDevToolsTargetId(targetId)
}

Class: WebContents

Render and control the contents of a BrowserWindow instance.渲染和控制BrowserWindow实例的内容。

Process:进程:Main
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中其他方法的返回值使用。

Instance Events实例事件

Event: 'did-finish-load'

Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the onload event was dispatched.当导航完成时发出,即选项卡的微调器已停止旋转,并且已调度onload事件。

Event: 'did-fail-load'

Returns:返回:

  • event Event
  • errorCode Integer
  • errorDescription string
  • validatedURL string
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

This event is like did-finish-load but emitted when the load failed. 此事件类似于did-finish-load,但在加载失败时发出。The full list of error codes and their meaning is available here.此处提供了错误代码及其含义的完整列表。

Event: 'did-fail-provisional-load'

Returns:返回:

  • event Event
  • errorCode Integer
  • errorDescription string
  • validatedURL string
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

This event is like did-fail-load but emitted when the load was cancelled (e.g. window.stop() was invoked).此事件类似于did-fail-load,但在取消加载时发出(例如,调用window.stop())。

Event: 'did-frame-finish-load'

Returns:返回:

  • event Event
  • isMainFrame boolean
  • frameProcessId Integer
  • frameRoutingId Integer

Emitted when a frame has done navigation.当帧完成导航时发出。

Event: 'did-start-loading'

Corresponds to the points in time when the spinner of the tab started spinning.对应于选项卡的微调器开始旋转的时间点。

Event: 'did-stop-loading'

Corresponds to the points in time when the spinner of the tab stopped spinning.对应于选项卡的微调器停止旋转的时间点。

Event: 'dom-ready'

Returns:返回:

  • event Event

Emitted when the document in the top-level frame is loaded.在加载顶层框架中的文档时发出。

Event: 'page-title-updated'

Returns:返回:

  • event Event
  • 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:返回:

  • event Event
  • favicons string[] - Array of URLs.URL数组。

Emitted when page receives favicon urls.当页面接收到集合夹URL时发出。

Event: 'new-window' Deprecated

Returns:返回:

  • event NewWindowWebContentsEvent
  • url string
  • frameName string
  • disposition string - Can be default, foreground-tab, background-tab, new-window, save-to-disk and other.可以是defaultforeground-tabbackground-tabnew-windowsave-to-diskother
  • options BrowserWindowConstructorOptions - The options which will be used for creating the new BrowserWindow.将用于创建新BrowserWindow的选项。
  • additionalFeatures string[] - The non-standard features (features not handled by Chromium or Electron) given to window.open(). window.open()的非标准功能(Chromium或Electron未处理的功能)。Deprecated, and will now always be the empty array [].已弃用,现在将始终为空数组[]
  • referrer Referrer - The referrer that will be passed to the new window. 将传递到新窗口的引用人。May or may not result in the Referer header being sent, depending on the referrer policy.可能会也可能不会导致发送Referer标头,具体取决于Referer策略。
  • postBody PostBody (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. 将发送到新窗口的post数据,以及将设置的相应标头。If no post data is to be sent, the value will be null. 如果不发送投递数据,则该值将为nullOnly defined when the window is being created by a form that set target=_blank.仅在由设置target=_blank的表单创建窗口时定义。

Deprecated in favor of webContents.setWindowOpenHandler.已弃用,以支持webContents.setWindowOpenHandler

Emitted when the page requests to open a new window for a url. 当页面请求为url打开新窗口时发出。It could be requested by window.open or an external link like <a target='_blank'>.它可以通过window.open或外部链接(如<a target='_blank'>)请求。

By default a new BrowserWindow will be created for the url.默认情况下,将为url创建一个新的BrowserWindow

Calling event.preventDefault() will prevent Electron from automatically creating a new BrowserWindow. 调用event.preventDefault()将阻止Electron自动创建新的BrowserWindowIf you call event.preventDefault() and manually create a new BrowserWindow then you must set event.newGuest to reference the new BrowserWindow instance, failing to do so may result in unexpected behavior. 如果调用event.preventDefault()并手动创建新的BrowserWindow,则必须将event.newGuest设置为引用新的BrowserWindow实例,否则可能会导致意外行为。For example:例如:

myBrowserWindow.webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => {
event.preventDefault()
const win = new BrowserWindow({
webContents: options.webContents, // use existing webContents if provided
show: false
})
win.once('ready-to-show', () => win.show())
if (!options.webContents) {
const loadOptions = {
httpReferrer: referrer
}
if (postBody != null) {
const { data, contentType, boundary } = postBody
loadOptions.postData = postBody.data
loadOptions.extraHeaders = `content-type: ${contentType}; boundary=${boundary}`
}

win.loadURL(url, loadOptions) // existing webContents will be navigated automatically
}
event.newGuest = win
})

Event: 'did-create-window'

Returns:返回:

  • window BrowserWindow
  • details Object
    • url string - URL for the created window.创建的窗口的URL。
    • frameName string - Name given to the created window in the window.open() call.window.open()调用中为创建的窗口指定的名称。
    • options BrowserWindowConstructorOptions - The options used to create the BrowserWindow. 用于创建BrowserWindow的选项。They are merged in increasing precedence: parsed options from the features string from window.open(), security-related webPreferences inherited from the parent, and options given by webContents.setWindowOpenHandler. 它们以越来越高的优先级合并:从window.open()的功能字符串中解析的选项,从父级继承的与安全相关的webPreferences,以及webContents.setWindowOpenHandler提供的选项。Unrecognized options are not filtered out.未筛选出无法识别的选项。
    • referrer Referrer - The referrer that will be passed to the new window. 将传递到新窗口的引用人。May or may not result in the Referer header being sent, depending on the referrer policy.可能会也可能不会导致发送Referer标头,具体取决于Referer策略。
    • postBody PostBody (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. 将发送到新窗口的post数据,以及将设置的相应标头。If no post data is to be sent, the value will be null. 如果不发送投递数据,则该值将为nullOnly defined when the window is being created by a form that set target=_blank.仅在由设置target=_blank的表单创建窗口时定义。
    • disposition string - Can be default, foreground-tab, background-tab, new-window, save-to-disk and other.可以是defaultforeground-tabbackground-tabnew-windowsave-to-diskother

Emitted after successful creation of a window via window.open in the renderer. 通过渲染器中的window.open成功创建窗口后发出。Not emitted if the creation of the window is canceled from webContents.setWindowOpenHandler.如果从webContents.setWindowOpenHandler取消了窗口的创建,则不会发出。

See window.open() for more details and how to use this in conjunction with webContents.setWindowOpenHandler.有关更多详细信息以及如何将其与webContents.setWindowOpenHandler结合使用,请参阅window.open()

Event: 'will-navigate'

Returns:返回:

  • event Event
  • 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 webContents.loadURL and webContents.back.当使用webContents.loadURLwebContents.back等API以编程方式启动导航时,此事件不会发出。

It is also not emitted for in-page navigations, 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() will prevent the navigation.调用event.preventDefault()将阻止导航。

Event: 'did-start-navigation'

Returns:返回:

  • event Event
  • 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: 'will-redirect'

Returns:返回:

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

Emitted when a server side redirect occurs during navigation. 在导航过程中发生服务器端重定向时发出。For example a 302 redirect.例如302重定向。

This event will be emitted after did-start-navigation and always before the did-redirect-navigation event for the same navigation.此事件将在did-start-navigation后发出,并且始终在相同导航的did-redirect-navigation事件之前发出。

Calling event.preventDefault() will prevent the navigation (not just the redirect).调用event.preventDefault()将阻止导航(而不仅仅是重定向)。

Event: 'did-redirect-navigation'

Returns:返回:

  • event Event
  • 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重定向。

This event cannot be prevented, if you want to prevent redirects you should checkout out the will-redirect event above.此事件无法阻止,如果您想阻止重定向,您应该签出上面的will-redirect事件。

Event: 'did-navigate'

Returns:返回:

  • event Event
  • url string
  • httpResponseCode Integer - -1 for non HTTP navigations-1用于非HTTP导航
  • httpStatusText string - empty for non HTTP navigations对于非HTTP导航为空

Emitted when a main 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-frame-navigate'

Returns:返回:

  • event Event
  • 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:返回:

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

Emitted when an in-page navigation happened in any frame.在任何帧中发生页内导航时发出。

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: 'will-prevent-unload'

Returns:返回:

  • event Event

Emitted when a beforeunload event handler is attempting to cancel a page unload.beforeunload事件处理程序试图取消页面卸载时发出。

Calling event.preventDefault() will ignore the beforeunload event handler and allow the page to be unloaded.调用event.preventDefault()将忽略beforeunload事件处理程序,并允许卸载页面。

const { BrowserWindow, dialog } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('will-prevent-unload', (event) => {
const choice = dialog.showMessageBoxSync(win, {
type: 'question',
buttons: ['Leave', 'Stay'],
title: 'Do you want to leave this site?',
message: 'Changes you made may not be saved.',
defaultId: 0,
cancelId: 1
})
const leave = (choice === 0)
if (leave) {
event.preventDefault()
}
})

Note: This will be emitted for BrowserViews but will not be respected - this is because we have chosen not to tie the BrowserView lifecycle to its owning BrowserWindow should one exist per the specification.这将为BrowserView发出,但不会受到尊重-这是因为我们选择不将BrowserView生命周期与其所属的BrowserWindow联系起来,如果规范中存在BrowserWindow的话。

Event: 'crashed' Deprecated

Returns:返回:

  • event Event
  • killed boolean

Emitted when the renderer process crashes or is killed.当渲染器进程崩溃或终止时发出。

Deprecated: This event is superceded by the render-process-gone event which contains more information about why the render process disappeared. 此事件被render-process-gone事件取代,该事件包含有关渲染进程消失原因的更多信息。It isn't always because it crashed. 这并不总是因为它坠毁了。The killed boolean can be replaced by checking reason === 'killed' when you switch to that event.当您切换到该事件时,可以通过检查reason === 'killed'来替换killed布尔值。

Event: 'render-process-gone'

Returns:返回:

  • event Event
  • details Object
    • reason string - The reason the render process is gone. 渲染过程消失的原因。Possible values:可能的值:
      • clean-exit - Process exited with an exit code of zero进程退出,退出代码为零
      • abnormal-exit - Process exited with a non-zero exit code进程已退出,退出代码为非零
      • killed - Process was sent a SIGTERM or otherwise killed externally进程被发送SIGTERM或以其他方式从外部终止
      • crashed - Process crashed进程崩溃
      • oom - Process ran out of memory进程内存不足
      • launch-failed - Process never successfully launched进程从未成功启动
      • integrity-failure - Windows code integrity checks failedWindows代码完整性检查失败
    • exitCode Integer - The exit code of the process, unless reason is launch-failed, in which case exitCode will be a platform-specific launch failure error code.进程的退出代码,除非reasonlaunch-failed,在这种情况下,exitCode将是特定于平台的启动失败错误代码。

Emitted when the renderer process unexpectedly disappears. 当渲染器进程意外消失时发出。This is normally because it was crashed or killed.这通常是因为它坠毁或死亡。

Event: 'unresponsive'

Emitted when the web page becomes unresponsive.当网页变得没有响应时发出。

Event: 'responsive'

Emitted when the unresponsive web page becomes responsive again.当无响应的网页再次响应时发出。

Event: 'plugin-crashed'

Returns:返回:

  • event Event
  • name string
  • version string

Emitted when a plugin process has crashed.当插件进程崩溃时发出。

Event: 'destroyed'

Emitted when webContents is destroyed.webContents被销毁时发出。

Event: 'before-input-event'

Returns:返回:

Emitted before dispatching the keydown and keyup events in the page. 在调度页面中的keydownkeyup事件之前发出。Calling event.preventDefault will prevent the page keydown/keyup events and the menu shortcuts.调用event.preventDefault将阻止页面keydown/keyup事件和菜单快捷方式。

To only prevent the menu shortcuts, use setIgnoreMenuShortcuts:若要仅阻止菜单快捷方式,请使用setIgnoreMenuShortcuts

const { BrowserWindow } = require('electron')

const win = new BrowserWindow({ width: 800, height: 600 })

win.webContents.on('before-input-event', (event, input) => {
// For example, only enable application menu keyboard shortcuts when
// Ctrl/Cmd are down.
win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta)
})

Event: 'enter-html-full-screen'

Emitted when the window enters a full-screen state triggered by HTML API.当窗口进入由HTML API触发的全屏状态时发出。

Event: 'leave-html-full-screen'

Emitted when the window leaves a full-screen state triggered by HTML API.当窗口离开由HTML API触发的全屏状态时发出。

Event: 'zoom-changed'

Returns:返回:

  • event Event
  • zoomDirection string - Can be in or out.可以是inout

Emitted when the user is requesting to change the zoom level using the mouse wheel.当用户请求使用鼠标滚轮更改缩放级别时发出。

Event: 'blur'

Emitted when the webContents loses focus.webContents失去焦点时发出。

Event: 'focus'

Emitted when the webContents gains focus.webContents获得焦点时发出。

Note that on macOS, having focus means the webContents is the first responder of window, so switching focus between windows would not trigger the focus and blur events of webContents, as the first responder of each window is not changed.请注意,在macOS上,具有焦点意味着webContents是窗口的第一个响应者,因此在窗口之间切换焦点不会触发webContentsfocusblur事件,因为每个窗口的第一响应者不会改变。

The focus and blur events of webContents should only be used to detect focus change between different webContents and BrowserView in the same window.webContentsfocusblur事件只能用于检测同一窗口中不同webContentsBrowserView之间的焦点变化。

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: 'certificate-error'

Returns:返回:

  • event Event
  • url string
  • error string - The error code.错误代码。
  • certificate Certificate
  • callback Function
    • isTrusted boolean - Indicates whether the certificate can be considered trusted.指示是否可以将证书视为可信证书。
  • isMainFrame boolean

Emitted when failed to verify the certificate for url.在验证urlcertificate失败时发出。

The usage is the same with the certificate-error event of app.用法与appcertificate-error事件相同。

Event: 'select-client-certificate'

Returns:返回:

  • event Event
  • url URL
  • certificateList Certificate[]
  • callback Function
    • certificate Certificate - Must be a certificate from the given list.必须是给定列表中的证书。

Emitted when a client certificate is requested.在请求客户端证书时发出。

The usage is the same with the select-client-certificate event of app.用法与appselect-client-certificate事件相同。

Event: 'login'

Returns:返回:

  • event Event
  • authenticationResponseDetails Object
    • url URL
  • authInfo Object
    • isProxy boolean
    • scheme string
    • host string
    • port Integer
    • realm string
  • callback Function
    • username string (optional)
    • password string (optional)

Emitted when webContents wants to do basic auth.webContents想要进行基本身份验证时发出。

The usage is the same with the login event of app.用法与应用程序的login事件相同。

Event: 'found-in-page'

Returns:返回:

  • event Event
  • 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

Emitted when a result is available for [webContents.findInPage] request.当[webContents.findInPage]请求的结果可用时发出。

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

  • event Event
  • color (string | null) - Theme color is in format of '#rrggbb'. 主题颜色的格式为“#rrggbb”。It is null when no theme color is set.当没有设置主题颜色时,它为null

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

  • event Event
  • url string

Emitted when mouse moves over a link or the keyboard moves the focus to a link.当鼠标在链接上移动或键盘将焦点移动到链接时发出。

Event: 'cursor-changed'

Returns:返回:

  • event Event
  • type string
  • image NativeImage (optional)
  • scale Float (optional) - scaling factor for the custom cursor.自定义游标的缩放因子。
  • size Size (optional) - the size of the image.image的大小。
  • hotspot Point (optional) - coordinates of the custom cursor's hotspot.自定义游标热点的坐标。

Emitted when the cursor's type changes. 当游标的类型更改时发出。The type parameter can be default, crosshair, pointer, text, wait, help, e-resize, n-resize, ne-resize, nw-resize, s-resize, se-resize, sw-resize, w-resize, ns-resize, ew-resize, nesw-resize, nwse-resize, col-resize, row-resize, m-panning, e-panning, n-panning, ne-panning, nw-panning, s-panning, se-panning, sw-panning, w-panning, move, vertical-text, cell, context-menu, alias, progress, nodrop, copy, none, not-allowed, zoom-in, zoom-out, grab, grabbing or custom.

If the type parameter is custom, the image parameter will hold the custom cursor image in a NativeImage, and scale, size and hotspot will hold additional information about the custom cursor.

Event: 'context-menu'

Returns:返回:

  • event Event
  • params Object
    • x Integer - x coordinate.x坐标。
    • y Integer - y coordinate.y坐标。
    • frame WebFrameMain - Frame from which the context menu was invoked.从中调用上下文菜单的帧。
    • 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.可以是noneimageaudiovideocanvasfileplugin
    • 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.可能的值是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.
    • 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.当存在需要处理的新上下文菜单时发出。

Event: 'select-bluetooth-device'

Returns:返回:

Emitted when bluetooth device needs to be selected on call to navigator.bluetooth.requestDevice. 当需要在调用navigator.bluetooth.requestDevice时选择蓝牙设备时发出。To use navigator.bluetooth api webBluetooth should be enabled. 要使用navigator.bluetooth api,应启用webBluetoothIf event.preventDefault is not called, first available device will be selected. 如果未调用event.preventDefault,将选择第一个可用的设备。callback should be called with deviceId to be selected, passing empty string to callback will cancel the request.应该使用要选择的deviceId来调用callback,将空字符串传递给callback将取消请求。

If no event listener is added for this event, all bluetooth requests will be cancelled.如果没有为此事件添加事件侦听器,则所有蓝牙请求都将被取消。

const { app, BrowserWindow } = require('electron')

let win = null
app.commandLine.appendSwitch('enable-experimental-web-platform-features')

app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => {
event.preventDefault()
const result = deviceList.find((device) => {
return device.deviceName === 'test'
})
if (!result) {
callback('')
} else {
callback(result.deviceId)
}
})
})

Event: 'paint'

Returns:返回:

  • event Event
  • dirtyRect Rectangle
  • image NativeImage - The image data of the whole frame.整个帧的图像数据。

Emitted when a new frame is generated. 生成新帧时发射。Only the dirty area is passed in the buffer.缓冲区中只传递脏区域。

const { BrowserWindow } = require('electron')

const win = new BrowserWindow({ webPreferences: { offscreen: true } })
win.webContents.on('paint', (event, dirty, image) => {
// updateBitmap(dirty, image.getBitmap())
})
win.loadURL('http://github.com')

Event: 'devtools-reload-page'

Emitted when the devtools window instructs the webContents to reload当devtools窗口指示重新加载webContents时发出

Event: 'will-attach-webview'

Returns:返回:

  • event Event
  • webPreferences WebPreferences - The web preferences that will be used by the guest page. 来宾页面将使用的web首选项。This object can be modified to adjust the preferences for the guest page.可以修改此对象以调整来宾页面的首选项。
  • params Record<string, string> - The other <webview> parameters such as the src URL. 其他<webview>参数,例如src URL。This object can be modified to adjust the parameters of the guest page.可以修改此对象以调整来宾页面的参数。

Emitted when a <webview>'s web contents is being attached to this web contents. <webview>的web内容附加到此web内容时发出。Calling event.preventDefault() will destroy the guest page.调用event.preventDefault()将销毁来宾页面。

This event can be used to configure webPreferences for the webContents of a <webview> before it's loaded, and provides the ability to set settings that can't be set via <webview> attributes.此事件可用于在加载<webview>之前为其webContents配置webPreferences,并提供设置无法通过<webview>属性设置的设置的功能。

Event: 'did-attach-webview'

Returns:返回:

  • event Event
  • webContents webContents - The guest web contents that is used by the <webview>.<webview>使用的来宾web内容。

Emitted when a <webview> has been attached to this web contents.<webview>已附加到此web内容时发出。

Event: 'console-message'

Returns:返回:

  • event Event
  • level Integer - The log level, from 0 to 3. In order it matches verbose, info, warning and error.日志级别,从0到3。按照顺序,它匹配verboseinfowarningerror
  • message string - The actual console message实际控制台消息
  • line Integer - The line number of the source that triggered this console message触发此控制台消息的源的行号
  • sourceId string

Emitted when the associated window logs a console message.当关联的窗口记录控制台消息时发出。

Event: 'preload-error'

Returns:返回:

  • event Event
  • preloadPath string
  • error Error

Emitted when the preload script preloadPath throws an unhandled exception error.当预加载脚本preloadPath引发未处理的异常error时发出。

Event: 'ipc-message'

Returns:返回:

  • event Event
  • channel string
  • ...args any[]

Emitted when the renderer process sends an asynchronous message via ipcRenderer.send().当渲染器进程通过ipcRenderer.send()发送异步消息时发出。

Event: 'ipc-message-sync'

Returns:返回:

  • event Event
  • channel string
  • ...args any[]

Emitted when the renderer process sends a synchronous message via ipcRenderer.sendSync().当渲染器进程通过ipcRenderer.sendSync()发送同步消息时发出。

Event: 'preferred-size-changed'

Returns:返回:

  • event Event
  • preferredSize Size - The minimum size needed to contain the layout of the document—without requiring scrolling.包含文档布局而不需要滚动所需的最小大小。

Emitted when the webContents preferred size has changed.webContents首选大小发生更改时发出。

This event will only be emitted when enablePreferredSizeMode is set to true in webPreferences.只有在webPreferences中将enablePreferredSizeMode设置为true时,才会发出此事件。

Event: 'frame-created'

Returns:返回:

  • event Event
  • details Object
    • frame WebFrameMain

Emitted when the mainFrame, an <iframe>, or a nested <iframe> is loaded within the page.在页面中加载mainFrame<iframe>或嵌套的<iframe>时发出。

Instance Methods实例方法

contents.loadURL(url[, options])

  • url string
  • 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)。A noop rejection handler is already attached, which avoids unhandled rejection errors.已经附加了noop拒绝处理程序,从而避免了未处理的拒绝错误。

Loads the url in the window. 在窗口中加载urlThe url must contain the protocol prefix, e.g. the http:// or file://. url必须包含协议前缀,例如http://file://If the load should bypass http cache then use the pragma header to achieve it.如果加载应该绕过http缓存,那么使用pragma头来实现它。

const { webContents } = require('electron')
const options = { extraHeaders: 'pragma: no-cache\n' }
webContents.loadURL('https://github.com', options)

contents.loadFile(filePath[, options])

  • filePath string
  • options Object (optional)
    • query Record<string, string> (optional) - Passed to url.format().已传递到url.format()
    • search string (optional) - Passed to url.format().已传递到url.format()
    • hash string (optional) - Passed to url.format().已传递到url.format()

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 given file in the window, filePath should be a path to an HTML file relative to the root of your application. 在窗口中加载给定的文件,filePath应该是相对于应用程序根的HTML文件的路径。For instance an app structure like this:例如,像这样的应用程序结构:

| root
| - package.json
| - src
| - main.js
| - index.html

Would require code like this需要这样的代码

win.loadFile('src/index.html')

contents.downloadURL(url)

  • url string

Initiates a download of the resource at url without navigating. url处启动资源下载,而不进行导航。The will-download event of session will be triggered.将触发sessionwill-download事件。

contents.getURL()

Returns返回string - The URL of the current web page.当前网页的URL。

const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com').then(() => {
const currentURL = win.webContents.getURL()
console.log(currentURL)
})

contents.getTitle()

Returns返回string - The title of the current web page.当前网页的标题。

contents.isDestroyed()

Returns返回boolean - Whether the web page is destroyed.网页是否被破坏。

contents.focus()

Focuses the web page.关注网页。

contents.isFocused()

Returns返回boolean - Whether the web page is focused.网页是否聚焦。

contents.isLoading()

Returns返回boolean - Whether web page is still loading resources.网页是否仍在加载资源。

contents.isLoadingMainFrame()

Returns返回boolean - Whether the main frame (and not just iframes or frames within it) is still loading.主框架(而不仅仅是iframe或其中的框架)是否仍在加载。

contents.isWaitingForResponse()

Returns返回boolean - Whether the web page is waiting for a first-response from the main resource of the page.网页是否正在等待来自页面的主资源的第一个响应。

contents.stop()

Stops any pending navigation.停止任何挂起的导航。

contents.reload()

Reloads the current web page.重新加载当前网页。

contents.reloadIgnoringCache()

Reloads current page and ignores cache.重新加载当前页面并忽略缓存。

contents.canGoBack()

Returns返回boolean - Whether the browser can go back to previous web page.浏览器是否可以返回到上一个网页。

contents.canGoForward()

Returns返回boolean - Whether the browser can go forward to next web page.浏览器是否可以转到下一个网页。

contents.canGoToOffset(offset)

  • offset Integer

Returns返回boolean - Whether the web page can go to offset.网页是否可以进行前往offset

contents.clearHistory()

Clears the navigation history.清除导航历史记录。

contents.goBack()

Makes the browser go back a web page.使浏览器返回网页。

contents.goForward()

Makes the browser go forward a web page.使浏览器前进为网页。

contents.goToIndex(index)

  • index Integer

Navigates browser to the specified absolute web page index.将浏览器导航到指定的绝对网页索引。

contents.goToOffset(offset)

  • offset Integer

Navigates to the specified offset from the "current entry".从“当前条目”导航到指定的偏移量。

contents.isCrashed()

Returns返回boolean - Whether the renderer process has crashed.渲染器进程是否已崩溃。

contents.forcefullyCrashRenderer()

Forcefully terminates the renderer process that is currently hosting this webContents. 强制终止当前承载此webContents的渲染器进程。This will cause the render-process-gone event to be emitted with the reason=killed || reason=crashed. 这将导致render-process-gone事件以reason=killed || reason=crashed的形式发出。Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well.请注意,一些webContents共享渲染器进程,因此调用此方法也可能导致其他webContents的主机进程崩溃。

Calling reload() immediately after calling this method will force the reload to occur in a new process. 在调用此方法后立即调用reload()将强制在新进程中进行重新加载。This should be used when this process is unstable or unusable, for instance in order to recover from the unresponsive event.当此进程不稳定或不可用时,例如为了从unresponsive事件中恢复,应使用此选项。

contents.on('unresponsive', async () => {
const { response } = await dialog.showMessageBox({
message: 'App X has become unresponsive',
title: 'Do you want to try forcefully reloading the app?',
buttons: ['OK', 'Cancel'],
cancelId: 1
})
if (response === 0) {
contents.forcefullyCrashRenderer()
contents.reload()
}
})

contents.setUserAgent(userAgent)

  • userAgent string

Overrides the user agent for this web page.覆盖此网页的用户代理。

contents.getUserAgent()

Returns返回string - The user agent for this web page.此网页的用户代理。

contents.insertCSS(css[, options])

  • css string
  • options Object (optional)
    • cssOrigin string (optional) - Can be either 'user' or 'author'. 可以是“用户”或“作者”。Sets the cascade origin of the inserted stylesheet. Default is 'author'.设置插入样式表的级联原点。默认值为“author”。

Returns返回Promise<string> - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via contents.removeInsertedCSS(key).一个promise,它用插入的CSS的一个键来解析,以后可以通过contents.removeInsertedCSS(key)来删除CSS。

Injects CSS into the current web page and returns a unique key for the inserted stylesheet.将CSS注入当前网页,并为插入的样式表返回一个唯一的键。

contents.on('did-finish-load', () => {
contents.insertCSS('html, body { background-color: #f00; }')
})

contents.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 contents.insertCSS(css).样式表由其键标识,该键是从contents.insertCSS(css)返回的。

contents.on('did-finish-load', async () => {
const key = await contents.insertCSS('html, body { background-color: #f00; }')
contents.removeInsertedCSS(key)
})

contents.executeJavaScript(code[, userGesture])

  • code string
  • userGesture boolean (optional) - Default is 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

In the browser window some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. 在浏览器窗口中,一些HTML API(如requestFullScreen)只能通过用户的手势调用。Setting userGesture to true will remove this limitation.userGesture设置为true将删除此限制。

Code execution will be suspended until web page stop loading.代码执行将暂停,直到网页停止加载。

contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true)
.then((result) => {
console.log(result) // Will be the JSON object from the fetch call
})

contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])

  • worldId Integer - The ID of the world to run the javascript in, 0 is the default world, 999 is the world used by Electron's contextIsolation feature. 要在其中运行javascript的世界的ID,0是默认世界,999是Electron的contextIsolation功能使用的世界。 You can provide any integer here.您可以在此处提供任何整数。
  • scripts WebSource[]
  • userGesture boolean (optional) - Default is 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.用执行的代码的结果解析的承诺,或者如果代码的结果是被拒绝的承诺,则被拒绝。

Works like executeJavaScript but evaluates scripts in an isolated context.executeJavaScript类似,但在独立的上下文中评估scripts

contents.setIgnoreMenuShortcuts(ignore)

  • ignore boolean

Ignore application menu shortcuts while this web contents is focused.当此web内容处于焦点状态时,忽略应用程序菜单快捷方式。

contents.setWindowOpenHandler(handler)

  • handler Function<{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}>

    • details Object
      • url string - The resolved version of the URL passed to window.open(). 传递给window.open()的URL的已解决版本。e.g. opening a window with window.open('foo') will yield something like https://the-origin/the/current/path/foo.使用window.open('foo')打开窗口会产生类似https://the-origin/the/current/path/foo的效果。
      • frameName string - Name of the window provided in window.open()windowopen()中提供的窗口的名称
      • features string - Comma separated list of window features provided to window.open().提供给window.open()的窗口功能的逗号分隔列表。
      • disposition string - Can be default, foreground-tab, background-tab, new-window, save-to-disk or other.可以是defaultforeground-tabbackground-tabnew-windowsave-to-diskother
      • referrer Referrer - The referrer that will be passed to the new window. 将传递到新窗口的引用人。May or may not result in the Referer header being sent, depending on the referrer policy.可能会也可能不会导致发送Referer标头,具体取决于Referer策略。
      • postBody PostBody (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. 将发送到新窗口的post数据,以及将设置的相应标头。If no post data is to be sent, the value will be null. 如果不发送投递数据,则该值将为nullOnly defined when the window is being created by a form that set target=_blank.仅在由设置target=_blank的表单创建窗口时定义。

    Returns返回{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions} - deny cancels the creation of the new window. deny取消创建新窗口。allow will allow the new window to be created. allow将允许创建新窗口。Specifying overrideBrowserWindowOptions allows customization of the created window. 指定overrideBrowserWindowOptions允许自定义创建的窗口。Returning an unrecognized value such as a null, undefined, or an object without a recognized 'action' value will result in a console error and have the same effect as returning {action: 'deny'}.返回无法识别的值,如null、未定义或没有可识别的“action”值的对象,将导致控制台错误,其效果与返回{action: 'deny'}相同。

Called before creating a window a new window is requested by the renderer, e.g. by window.open(), a link with target="_blank", shift+clicking on a link, or submitting a form with <form target="_blank">. 在创建窗口之前调用,渲染器会请求一个新窗口,例如通过window.open()target="_blank"的链接、shift+单击链接,或提交<form target="_blank">的表单。See window.open() for more details and how to use this in conjunction with did-create-window.请参阅window.open()了解更多详细信息,以及如何将其与did-create-window结合使用。

contents.setAudioMuted(muted)

  • muted boolean

Mute the audio on the current web page.将当前网页上的音频静音。

contents.isAudioMuted()

Returns返回boolean - Whether this page has been muted.此页面是否已静音。

contents.isCurrentlyAudible()

Returns返回boolean - Whether audio is currently playing.当前是否正在播放音频。

contents.setZoomFactor(factor)

  • factor Double - Zoom factor; default is 1.0.缩放因子;默认值为1.0。

Changes the zoom factor to the specified factor. 将缩放因子更改为指定的因子。Zoom factor is zoom percent divided by 100, so 300% = 3.0.缩放因子是缩放百分比除以100,因此300%=3.0。

The factor must be greater than 0.0.该系数必须大于0.0。

contents.getZoomFactor()

Returns返回number - the current zoom factor.当前缩放因子。

contents.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将使每个窗口都能进行缩放。

contents.getZoomLevel()

Returns返回number - the current zoom level.当前缩放级别。

contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)

  • minimumLevel number
  • maximumLevel number

Returns返回Promise<void>

Sets the maximum and minimum pinch-to-zoom level.将最大和最小夹点设置为缩放级别。

NOTE: Visual zoom is disabled by default in Electron. :Electron中默认禁用视觉缩放。To re-enable it, call:要重新启用它,请调用:

contents.setVisualZoomLevelLimits(1, 3)

contents.undo()

Executes the editing command undo in web page.在网页中执行编辑命令undo

contents.redo()

Executes the editing command redo in web page.在网页中执行编辑命令redo

contents.cut()

Executes the editing command cut in web page.在网页中执行编辑命令cut

contents.copy()

Executes the editing command copy in web page.在网页中执行编辑命令copy

contents.copyImageAt(x, y)

  • x Integer
  • y Integer

Copy the image at the given position to the clipboard.将给定位置的图像复制到剪贴板。

contents.paste()

Executes the editing command paste in web page.在网页中执行编辑命令paste

contents.pasteAndMatchStyle()

Executes the editing command pasteAndMatchStyle in web page.在网页中执行编辑命令pasteAndMatchStyle

contents.delete()

Executes the editing command delete in web page.在网页中执行编辑命令delete

contents.selectAll()

Executes the editing command selectAll in web page.在网页中执行编辑命令selectAll

contents.unselect()

Executes the editing command unselect in web page.在网页中执行编辑命令unselect

contents.replace(text)

  • text string

Executes the editing command replace in web page.在网页中执行编辑命令replace

contents.replaceMisspelling(text)

  • text string

Executes the editing command replaceMisspelling in web page.在网页中执行编辑命令replaceMisspelling

contents.insertText(text)

  • text string

Returns返回Promise<void>

Inserts text to the focused element.在焦点元素中插入text

contents.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事件来获得。

contents.stopFindInPage(action)

  • action string - Specifies the action to take place when ending [webContents.findInPage] request.指定在结束[webContents.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 webContents with the provided action.使用提供的action停止对webContents的任何findInPage查找页面请求。

const { webContents } = require('electron')
webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
})

const requestId = webContents.findInPage('api')
console.log(requestId)

contents.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将捕获整个可见页面。

contents.isBeingCaptured()

Returns返回boolean - Whether this page is being captured. 是否正在捕获此页面。It returns true when the capturer count is large then 0.当捕获器计数大于0时,返回true

contents.incrementCapturerCount([size, stayHidden, stayAwake])

  • size Size (optional) - The preferred size for the capturer.捕获器的首选尺寸。
  • stayHidden boolean (optional) - Keep the page hidden instead of visible.将页面隐藏而不显示。
  • stayAwake boolean (optional) - Keep the system awake instead of allowing it to sleep.让系统保持清醒,而不是让它进入睡眠状态。

Increase the capturer count by one. The page is considered visible when its browser window is hidden and the capturer count is non-zero. 将捕获器数量增加一。当页面的浏览器窗口被隐藏并且捕获器计数为非零时,该页面被视为可见。If you would like the page to stay hidden, you should ensure that stayHidden is set to true.如果希望页面保持隐藏状态,则应确保stayHidden设置为true

This also affects the Page Visibility API.这也会影响页面可见性API。

contents.decrementCapturerCount([stayHidden, stayAwake])

  • stayHidden boolean (optional) - Keep the page in hidden state instead of visible.将页面保持为隐藏状态,而不是可见状态。
  • stayAwake boolean (optional) - Keep the system awake instead of allowing it to sleep.让系统保持清醒,而不是让它进入睡眠状态。

Decrease the capturer count by one. 将捕获器计数减少一。The page will be set to hidden or occluded state when its browser window is hidden or occluded and the capturer count reaches zero. 当页面的浏览器窗口被隐藏或遮挡并且捕获器计数为零时,页面将被设置为隐藏或遮挡状态。If you want to decrease the hidden capturer count instead you should set stayHidden to true.如果你想减少隐藏的捕获器数量,你应该将stayHidden设置为true

contents.getPrinters() Deprecated

Get the system printer list.获取系统打印机列表。

Returns 返回PrinterInfo[]

Deprecated: Should use the new contents.getPrintersAsync API.应该使用新的contents.getPrintersAsync API。

contents.getPrintersAsync()

Get the system printer list.获取系统打印机列表。

Returns返回Promise<PrinterInfo[]> - Resolves with a PrinterInfo[]使用PrinterInfo[]进行解析

contents.print([options], [callback])

  • 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. On macOS, only one 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开始)。
    • 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.可以是A3A4A5LegalLetterTabloid或者包含height的对象。
  • callback Function (optional)
    • success boolean - Indicates success of the print call.表示打印调用成功。
    • failureReason string - Error description called back if the print fails.如果打印失败,将调用错误描述。

When a custom pageSize is passed, Chromium attempts to validate platform specific minimum values for width_microns and height_microns. 当传递自定义pageSize时,Chromium会尝试验证width_micronheight_micron的特定于平台的最小值。Width and height must both be minimum 353 microns but may be higher on some operating systems.宽度和高度都必须至少为353微米,但在某些操作系统上可能更高。

Prints window's web page. When silent is set to true, Electron will pick the system's default printer if deviceName is empty and the default settings for printing.打印窗口的网页。当silent设置为true时,如果deviceName为空并且默认设置为打印,Electron将选择系统的默认打印机。

Use page-break-before: always; CSS style to force to print to a new page.在之前使用page-break-before: always;CSS样式以强制打印到新页面。

Example usage:示例用法:

const options = {
silent: true,
deviceName: 'My-Printer',
pageRanges: [{
from: 0,
to: 1
}]
}
win.webContents.print(options, (success, errorType) => {
if (!success) console.log(errorType)
})

contents.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表示最小边距。
    • 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.要打印的页面范围。
      • 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 and width in microns.可以是A3A4A5LegalletterTabloid或包含heightwidth的对象(单位是微米)
    • printBackground boolean (optional) - Whether to print CSS backgrounds.是否打印CSS背景。
    • printSelectionOnly boolean (optional) - Whether to print selection only.是否只打印所选内容。

Returns返回Promise<Buffer> - Resolves with the generated PDF data.使用生成的PDF数据进行解析。

Prints window's web page as PDF with Chromium's preview printing custom settings.使用Chromium的预览打印自定义设置将窗口的网页打印为PDF。

The landscape will be ignored if @page CSS at-rule is used in the web page.如果在网页中使用@page CSS at规则,则landscape将被忽略。

By default, an empty options will be regarded as:默认情况下,空options将被视为:

{
marginsType: 0,
printBackground: false,
printSelectionOnly: false,
landscape: false,
pageSize: 'A4',
scaleFactor: 100
}

Use page-break-before: always; CSS style to force to print to a new page.page-break-before: always;CSS样式以强制打印到新页面。

An example of webContents.printToPDF:webContents.printToPDF示例:

const { BrowserWindow } = require('electron')
const fs = require('fs')
const path = require('path')
const os = require('os')

const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com')

win.webContents.on('did-finish-load', () => {
// Use default printing options
const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf')
win.webContents.printToPDF({}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
})

contents.addWorkSpace(path)

  • path string

Adds the specified path to DevTools workspace. Must be used after DevTools creation:将指定的路径添加到DevTools工作区。必须在创建DevTools后使用:

const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname)
})

contents.removeWorkSpace(path)

  • path string

Removes the specified path from DevTools workspace.从DevTools工作区中删除指定的路径。

contents.setDevToolsWebContents(devToolsWebContents)

  • devToolsWebContents WebContents

Uses the devToolsWebContents as the target webContents to show devtools.使用devToolsWebContents作为目标webContents来显示devtools。

The devToolsWebContents must not have done any navigation, and it should not be used for other purposes after the call.devToolsWebContents不能进行任何导航,并且在调用后不应将其用于其他目的。

By default Electron manages the devtools by creating an internal webContents with native view, which developers have very limited control of. 默认情况下,Electron通过创建具有本地视图的内部webContents来管理开发工具,而开发人员对本地视图的控制非常有限。With the setDevToolsWebContents method, developers can use any webContents to show the devtools in it, including BrowserWindow, BrowserView and <webview> tag.使用setDevToolsWebContents方法,开发人员可以使用任何webContents来显示其中的开发工具,包括BrowserWindowBrowserView<webview>标记。

Note that closing the devtools does not destroy the devToolsWebContents, it is caller's responsibility to destroy devToolsWebContents.请注意,关闭devtools并不会销毁devToolsWebContents,销毁devToolsWebContents是调用者的责任。

An example of showing devtools in a <webview> tag:<webview>标签中显示devtools的示例:

<html>
<head>
<style type="text/css">
* { margin: 0; }
#browser { height: 70%; }
#devtools { height: 30%; }
</style>
</head>
<body>
<webview id="browser" src="https://github.com"></webview>
<webview id="devtools" src="about:blank"></webview>
<script>
const { ipcRenderer } = require('electron')
const emittedOnce = (element, eventName) => new Promise(resolve => {
element.addEventListener(eventName, event => resolve(event), { once: true })
})
const browserView = document.getElementById('browser')
const devtoolsView = document.getElementById('devtools')
const browserReady = emittedOnce(browserView, 'dom-ready')
const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready')
Promise.all([browserReady, devtoolsReady]).then(() => {
const targetId = browserView.getWebContentsId()
const devtoolsId = devtoolsView.getWebContentsId()
ipcRenderer.send('open-devtools', targetId, devtoolsId)
})
</script>
</body>
</html>
// Main process
const { ipcMain, webContents } = require('electron')
ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => {
const target = webContents.fromId(targetContentsId)
const devtools = webContents.fromId(devtoolsContentsId)
target.setDevToolsWebContents(devtools)
target.openDevTools()
})

An example of showing devtools in a BrowserWindow:BrowserWindow中显示开发工具的示例:

const { app, BrowserWindow } = require('electron')

let win = null
let devtools = null

app.whenReady().then(() => {
win = new BrowserWindow()
devtools = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.setDevToolsWebContents(devtools.webContents)
win.webContents.openDevTools({ mode: 'detach' })
})

contents.openDevTools([options])

  • options Object (optional)
    • mode string - Opens the devtools with specified dock state, can be left, right, bottom, undocked, detach. 打开具有指定停靠状态的devtools,可以是leftrightbottomundockeddetachDefaults to last used dock state. 默认为上次使用的停靠状态。In undocked mode it's possible to dock back. undocked模式下,可以向后对接。In detach mode it's not.detach模式下则不然。
    • activate boolean (optional) - Whether to bring the opened devtools window to the foreground. 是否将打开的devtools窗口置于前台。The default is true.默认值为true

Opens the devtools.打开开发工具。

When contents is a <webview> tag, the mode would be detach by default, explicitly passing an empty mode can force using last used dock state.contents<webview>标记时,默认情况下modedetach,显式传递空mode可以强制使用上次使用的dock状态。

On Windows, if Windows Control Overlay is enabled, Devtools will be opened with mode: 'detach'.在Windows上,如果启用了Windows控制覆盖,则Devtools将以mode: 'detach'打开。

contents.closeDevTools()

Closes the devtools.关闭开发工具。

contents.isDevToolsOpened()

Returns返回boolean - Whether the devtools is opened.是否打开devtools。

contents.isDevToolsFocused()

Returns返回boolean - Whether the devtools view is focused .devtools视图是否集中。

contents.toggleDevTools()

Toggles the developer tools.切换开发人员工具。

contents.inspectElement(x, y)

  • x Integer
  • y Integer

Starts inspecting element at position (x, y).在位置(x, y)开始检查元素。

contents.inspectSharedWorker()

Opens the developer tools for the shared worker context.打开共享工作环境的开发人员工具

contents.inspectSharedWorkerById(workerId)

  • workerId string

Inspects the shared worker based on its ID.根据共享工作者的ID检查其身份。

contents.getAllSharedWorkers()

Returns 返回SharedWorkerInfo[] - Information about all Shared Workers.有关所有共享工作者的信息。

contents.inspectServiceWorker()

Opens the developer tools for the service worker context.打开服务工作者上下文的开发人员工具。

contents.send(channel, ...args)

  • channel string
  • ...args any[]

Send an asynchronous message to the renderer process via channel, along with arguments. 通过channel向渲染器进程发送异步消息以及参数。Arguments will be serialized with the Structured Clone Algorithm, just like postMessage, so prototype chains will not be included. 参数将使用结构化克隆算法进行序列化,就像postMessage一样,所以原型链将不包括在内。Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.发送Function、Promise、Symbol、WeakMap或WeakSet将引发异常。

NOTE: Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception.:发送DOM对象或特殊Electron对象等非标准JavaScript类型将引发异常。

The renderer process can handle the message by listening to channel with the ipcRenderer module.渲染器进程可以通过ipcRenderer模块监听channel来处理消息。

An example of sending messages from the main process to the renderer process:从主进程向渲染器进程发送消息的示例:

// In the main process.
const { app, BrowserWindow } = require('electron')
let win = null

app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!')
})
})
<!-- index.html -->
<html>
<body>
<script>
require('electron').ipcRenderer.on('ping', (event, message) => {
console.log(message) // Prints 'whoooooooh!'
})
</script>
</body>
</html>

contents.sendToFrame(frameId, channel, ...args)

  • frameId Integer | [number, number] - the ID of the frame to send to, or a pair of [processId, frameId] if the frame is in a different process to the main frame.要发送到的帧的ID,或者一对[processId, frameId](如果该帧处于与主帧不同的进程中)。
  • channel string
  • ...args any[]

Send an asynchronous message to a specific frame in a renderer process via channel, along with arguments. 通过channel向渲染器进程中的特定帧发送异步消息以及参数。Arguments will be serialized with the Structured Clone Algorithm, just like postMessage, so prototype chains will not be included. 参数将使用结构化克隆算法进行序列化,就像postMessage一样,所以原型链将不包括在内。Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.发送函数、承诺、符号、WeakMaps或WeakSets将引发异常。

NOTE: Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception.发送诸如DOM对象或特殊Electron对象之类的非标准JavaScript类型将引发异常。

The renderer process can handle the message by listening to channel with the ipcRenderer module.渲染器进程可以通过ipcRenderer模块监听channel来处理消息。

If you want to get the frameId of a given renderer context you should use the webFrame.routingId value. E.g.如果要获取给定渲染器上下文的frameId,则应使用webFrame.routingId值。如。

// In a renderer process
console.log('My frameId is:', require('electron').webFrame.routingId)

You can also read frameId from all incoming IPC messages in the main process.您还可以从主进程中的所有传入IPC消息中读取frameId

// In the main process
ipcMain.on('ping', (event) => {
console.info('Message came from frameId:', event.frameId)
})

contents.postMessage(channel, message, [transfer])

  • channel string
  • message any
  • transfer MessagePortMain[] (optional)

Send a message to the renderer process, optionally transferring ownership of zero or more [MessagePortMain][] objects.向呈现器进程发送消息,可以选择传输零个或多个[MessagePortMain][]对象的所有权。

The transferred MessagePortMain objects will be available in the renderer process by accessing the ports property of the emitted event. 通过访问发出事件的ports属性,传输的MessagePortMain对象将在渲染器进程中可用。When they arrive in the renderer, they will be native DOM MessagePort objects.当它们到达呈现器时,它们将是本机DOMMessagePort对象。

For example:例如:

// Main process
const { port1, port2 } = new MessageChannelMain()
webContents.postMessage('port', { message: 'hello' }, [port1])

// Renderer process
ipcRenderer.on('port', (e, msg) => {
const [port] = e.ports
// ...
})

contents.enableDeviceEmulation(parameters)

  • parameters Object
    • screenPosition string - Specify the screen type to emulate (default: desktop):指定要模拟的屏幕类型(默认设置:desktop):
      • desktop - Desktop screen type.桌面屏幕类型。
      • mobile - Mobile screen type.移动屏幕类型。
    • screenSize Size - Set the emulated screen size (screenPosition == mobile).设置模拟屏幕大小(screenPosition==mobile)。
    • viewPosition Point - Position the view on the screen (screenPosition == mobile)将视图定位在屏幕上(screenPosition==mobile (default: { x: 0, y: 0 }).(默认值:{ x: 0, y: 0 })。
    • deviceScaleFactor Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: 0).设置设备比例因子(如果零默认为原始设备比例因子)(默认值:0)。
    • viewSize Size - Set the emulated view size (empty means no override)设置模拟视图大小(空表示没有覆盖)
    • scale Float - Scale of emulated view inside available space (not in fit to view mode) 可用空间内模拟视图的比例(不适合视图模式)(default: 1).(默认值:1)。

Enable device emulation with the given parameters.使用给定参数启用设备仿真。

contents.disableDeviceEmulation()

Disable device emulation enabled by webContents.enableDeviceEmulation.禁用由webContents.enableDeviceEmulation启用的设备仿真。

contents.sendInputEvent(inputEvent)

Sends an input event to the page. 将输入event发送到页面。Note: The BrowserWindow containing the contents needs to be focused for sendInputEvent() to work.需要对包含内容的BrowserWindow进行聚焦,sendInputEvent()才能工作。

contents.beginFrameSubscription([onlyDirty ,]callback)

  • onlyDirty boolean (optional) - Defaults to false.默认为false
  • callback Function

Begin subscribing for presentation events and captured frames, the callback will be called with callback(image, dirtyRect) when there is a presentation event.开始订阅演示事件和捕获的帧,当出现演示事件时,将使用callback(image, dirtyRect)调用callback

The image is an instance of NativeImage that stores the captured frame.该图像是NativeImage的一个实例,用于存储捕获的帧。

The dirtyRect is an object with x, y, width, height properties that describes which part of the page was repainted. dirtyRect是一个具有xywidthheight属性的对象,用于描述页面的哪个部分被重新绘制。If onlyDirty is set to true, image will only contain the repainted area. onlyDirty设置为true,则image将只包含重新绘制的区域。onlyDirty defaults to false.默认为false

contents.endFrameSubscription()

End subscribing for frame presentation events.结束对框架演示活动的订阅。

contents.startDrag(item)

  • item Object
    • file string - The path to the file being dragged.正在拖动的文件的路径。
    • files string[] (optional) - The paths to the files being dragged. 要拖动的文件的路径。(files will override file field)files将覆盖file字段)
    • icon NativeImage | string - The image must be non-empty on macOS.在macOS上,图像必须为非空。

Sets the item as dragging item for current drag-drop operation, file is the absolute path of the file to be dragged, and icon is the image showing under the cursor when dragging.将项目设置为当前拖放操作的拖动项目,file是要拖动的文件的绝对路径,icon是拖动时显示在游标下的图像。

contents.savePage(fullPath, saveType)

  • fullPath string - The absolute file path.绝对文件路径。
  • saveType string - Specify the save type.指定保存类型。
    • HTMLOnly - Save only the HTML of the page.只保存页面的HTML。
    • HTMLComplete - Save complete-html page.保存完整的html页面。
    • MHTML - Save complete-html page as MHTML.将完整的html页面保存为MHTML。

Returns返回Promise<void> - resolves if the page is saved.如果保存页面,则解析。

const { BrowserWindow } = require('electron')
const win = new BrowserWindow()

win.loadURL('https://github.com')

win.webContents.on('did-finish-load', async () => {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => {
console.log('Page was saved successfully.')
}).catch(err => {
console.log(err)
})
})

contents.showDefinitionForSelection() macOS

Shows pop-up dictionary that searches the selected word on the page.显示在页面上搜索所选单词的弹出词典。

contents.isOffscreen()

Returns返回boolean - Indicates whether offscreen rendering is enabled.指示是否启用屏幕外渲染

contents.startPainting()

If offscreen rendering is enabled and not painting, start painting.如果启用了屏幕外渲染而未进行绘制,请开始绘制。

contents.stopPainting()

If offscreen rendering is enabled and painting, stop painting.如果启用了屏幕外渲染并进行绘制,请停止绘制。

contents.isPainting()

Returns返回boolean - If offscreen rendering is enabled returns whether it is currently painting.如果启用了屏幕外渲染,则返回当前是否正在绘制。

contents.setFrameRate(fps)

  • fps Integer

If offscreen rendering is enabled sets the frame rate to the specified number. 如果启用了屏幕外渲染,则将帧速率设置为指定的数字。Only values between 1 and 240 are accepted.只接受介于1和240之间的值。

contents.getFrameRate()

Returns返回Integer - If offscreen rendering is enabled returns the current frame rate.如果启用了屏幕外渲染,则返回当前帧速率。

contents.invalidate()

Schedules a full repaint of the window this web contents is in.安排对该web内容所在的窗口进行完全重新绘制。

If offscreen rendering is enabled invalidates the frame and generates a new one through the 'paint' event.如果启用了屏幕外渲染,则会使帧无效,并通过“绘制”事件生成新帧。

contents.getWebRTCIPHandlingPolicy()

Returns返回string - Returns the WebRTC IP Handling Policy.返回WebRTC IP处理策略。

contents.setWebRTCIPHandlingPolicy(policy)

  • policy string - Specify the WebRTC IP Handling Policy.指定WebRTC IP处理策略。
    • default - Exposes user's public and local IPs. 公开用户的公共和本地IP。This is the default behavior. 这是默认行为。When this policy is used, WebRTC has the right to enumerate all interfaces and bind them to discover public interfaces.使用此策略时,WebRTC有权枚举所有接口并绑定它们以发现公共接口。
    • default_public_interface_only - Exposes user's public IP, but does not expose user's local IP. 公开用户的公共IP,但不公开用户的本地IP。When this policy is used, WebRTC should only use the default route used by http. 使用此策略时,WebRTC应仅使用http使用的默认路由。This doesn't expose any local addresses.这不会暴露任何本地地址。
    • default_public_and_private_interfaces - Exposes user's public and local IPs. 公开用户的公共和本地IP。When this policy is used, WebRTC should only use the default route used by http. 使用此策略时,WebRTC应仅使用http使用的默认路由。This also exposes the associated default private address. 这也公开了关联的默认私有地址。Default route is the route chosen by the OS on a multi-homed endpoint.默认路由是操作系统在多址端点上选择的路由。
    • disable_non_proxied_udp - Does not expose public or local IPs. 不公开公共或本地IP。When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP.使用此策略时,除非代理服务器支持UDP,否则WebRTC应仅使用TCP联系对等方或服务器。

Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. 通过设置WebRTC IP处理策略,可以控制通过WebRTC公开哪些IP。See BrowserLeaks for more details.有关更多详细信息,请参阅BrowserLeaks

contents.getMediaSourceId(requestWebContents)

  • requestWebContents webContents - Web contents that the id will be registered to.id将注册到的Web内容。

Returns返回string - The identifier of a WebContents stream. WebContents流的标识符。This identifier can be used with navigator.mediaDevices.getUserMedia using a chromeMediaSource of tab. 此标识符可以使用tabchromeMediaSourcenavigator.mediaDevices.getUserMedia一起使用。The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds.标识符仅限于其注册到的web内容,并且仅在10秒内有效。

contents.getOSProcessId()

Returns返回Integer - The operating system pid of the associated renderer process.关联的呈现器进程的操作系统pid

contents.getProcessId()

Returns返回Integer - The Chromium internal pid of the associated renderer. 关联渲染器的Chromium内部pidCan be compared to the frameProcessId passed by frame specific navigation events (e.g. did-frame-navigate)可以与特定于帧的导航事件传递的frameProcessId进行比较(例如,did-frame-navigate

contents.takeHeapSnapshot(filePath)

  • filePath string - Path to the output file.输出文件的路径。

Returns返回Promise<void> - Indicates whether the snapshot has been created successfully.指示快照是否已成功创建。

Takes a V8 heap snapshot and saves it to filePath.获取一个V8堆快照并将其保存到filePath中。

contents.getBackgroundThrottling()

Returns返回boolean - whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. 当页面变为后台时,此WebContents是否会限制动画和计时器。This also affects the Page Visibility API.这也会影响页面可见性API。

contents.setBackgroundThrottling(allowed)

  • allowed boolean

Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. 控制当页面变为后台时,此WebContents是否会限制动画和计时器。This also affects the Page Visibility API.这也会影响页面可见性API。

contents.getType()

Returns返回string - the type of the webContent. webContents的类型。Can be backgroundPage, window, browserView, remote, webview or offscreen.可以是backgroundPagewindowbrowserViewremotewebviewoffscreen

contents.setImageAnimationPolicy(policy)

  • policy string - Can be animate, animateOnce or noAnimation.可以是animateanimateOncenoAnimation

Sets the image animation policy for this webContents. 设置此webContents的图像动画策略。The policy only affects new images, existing images that are currently being animated are unaffected. 该策略只影响新图像,当前正在制作动画的现有图像不受影响。This is a known limitation in Chromium, you can force image animation to be recalculated with img.src = img.src which will result in no network traffic but will update the animation policy.这是Chromium中的一个已知限制,您可以强制使用img.src = img.src重新计算图像动画,这将导致没有网络流量,但会更新动画策略。

This corresponds to the animationPolicy accessibility feature in Chromium.这与Chromium中的animationPolicy可访问性功能相对应。

Instance Properties实例属性

contents.audioMuted

A boolean property that determines whether this page is muted.一个boolean属性,用于确定此页面是否被静音。

contents.userAgent

A string property that determines the user agent for this web page.一个string属性,用于确定此网页的用户代理。

contents.zoomLevel

A number property that determines the zoom level for this web contents.一个number属性,用于确定此web内容的缩放级别。

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

contents.zoomFactor

A number property that determines the zoom factor for this web contents.一个number属性,用于确定此web内容的缩放因子。

The zoom factor is the zoom percent divided by 100, so 300% = 3.0.缩放因子是缩放百分比除以100,因此300%=3.0。

contents.frameRate

An Integer property that sets the frame rate of the web contents to the specified number. Integer属性,用于将web内容的帧速率设置为指定的数字。Only values between 1 and 240 are accepted.只接受介于1和240之间的值。

Only applicable if offscreen rendering is enabled.仅在启用屏幕外渲染时适用。

contents.id Readonly

A Integer representing the unique ID of this WebContents. 一个Integer,表示此WebContents的唯一ID。Each ID is unique among all webContents instances of the entire Electron application.在整个Electron应用程序的所有webContents实例中,每个ID都是唯一的。

contents.session Readonly

A Session used by this webContents.webContents使用的会话

contents.hostWebContents Readonly

A webContents instance that might own this webContents.可能拥有此webContentswebContents实例。

contents.devToolsWebContents Readonly

A WebContents | null property that represents the of DevTools webContents associated with a given webContents.一个WebContents | null属性,表示与给定WebContents关联的DevTools的WebContents

Note: Users should never store this object because it may become null when the DevTools has been closed.用户永远不应该存储此对象,因为当DevTools关闭时,它可能会变为null

contents.debugger Readonly

A Debugger instance for this webContents.webContents调试器实例。

contents.backgroundThrottling

A boolean property that determines whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. 一个boolean属性,用于确定当页面变为后台时,此WebContents是否会限制动画和计时器。This also affects the Page Visibility API.这也会影响页面可见性API。

contents.mainFrame Readonly

A WebFrameMain property that represents the top frame of the page's frame hierarchy.WebFrameMain属性,表示页面框架层次结构的顶部框架。