webContents
Render and control web pages.渲染和控制网页。
Process:进程:Main
webContents
is an EventEmitter. 是一个EventEmitter。It 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 此应用程序中关注的web内容,否则返回null
.null
。
webContents.fromId(id)
id
Integer
Returns返回webContents
| undefined
- A WebContents instance with the given ID, or 具有给定ID的undefined
if there is no WebContents associated with the given 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.TargetID
的webContents
实例,或者如果没有与给定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
EventerrorCode
IntegererrorDescription
stringvalidatedURL
stringisMainFrame
booleanframeProcessId
IntegerframeRoutingId
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
EventerrorCode
IntegererrorDescription
stringvalidatedURL
stringisMainFrame
booleanframeProcessId
IntegerframeRoutingId
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
EventisMainFrame
booleanframeProcessId
IntegerframeRoutingId
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
Eventtitle
stringexplicitSet
boolean
Fired when page title is set during navigation. 在导航过程中设置页面标题时激发。当标题是从文件url合成时,explicitSet
is false when title is synthesized from file url.explicitSet
为false
。
Event: 'page-favicon-updated'
Returns:返回:
event
Eventfavicons
string[] -Array of URLs.URL数组。
Emitted when page receives favicon urls.当页面接收到集合夹URL时发出。
Event: 'new-window' Deprecated
Returns:返回:
event
NewWindowWebContentsEventurl
stringframeName
stringdisposition
string -Can be可以是default
,foreground-tab
,background-tab
,new-window
,save-to-disk
andother
.default
、foreground-tab
、background-tab
、new-window
、save-to-disk
和other
。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
.null
。Only 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自动创建新的BrowserWindow。If 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
BrowserWindowdetails
Objecturl
string -URL for the created window.创建的窗口的URL。frameName
string -Name given to the created window in the在window.open()
call.window.open()
调用中为创建的窗口指定的名称。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
.null
。Only 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
andother
.default
、foreground-tab
、background-tab
、new-window
、save-to-disk
和other
。
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
Eventurl
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.loadURL
和webContents.back
等API以编程方式启动导航时,此事件不会发出。
It is also 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
事件。
Calling 调用event.preventDefault()
will prevent the navigation.event.preventDefault()
将阻止导航。
Event: 'did-start-navigation'
Returns:返回:
event
Eventurl
stringisInPlace
booleanisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
Emitted when any frame (including main) starts navigating. 当任何帧(包括主帧)开始导航时发出。对于页面内导航,isInPlace
will be true
for in-page navigations.isInPlace
将为true
。
Event: 'will-redirect'
Returns:返回:
event
Eventurl
stringisInPlace
booleanisMainFrame
booleanframeProcessId
IntegerframeRoutingId
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
Eventurl
stringisInPlace
booleanisMainFrame
booleanframeProcessId
IntegerframeRoutingId
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
Eventurl
stringhttpResponseCode
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
Eventurl
stringhttpResponseCode
Integer --1 for non HTTP navigations-1
用于非HTTP导航httpStatusText
string -empty for non HTTP navigations,对于非HTTP导航为空,isMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
Emitted when any frame navigation is done.在完成任何帧导航时发出。
This event is not emitted for in-page navigations, such as clicking anchor links or updating the 对于页内导航(如单击锚链接或更新window.location.hash
. window.location.hash
),不会发出此事件。Use 为此,使用did-navigate-in-page
event for this purpose.did-navigate-in-page
事件。
Event: 'did-navigate-in-page'
Returns:返回:
event
Eventurl
stringisMainFrame
booleanframeProcessId
IntegerframeRoutingId
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 发生这种情况的例子是当点击锚链接或触发DOM hashchange
event is triggered.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
Eventkilled
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
Eventdetails
Objectreason
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
islaunch-failed
, in which caseexitCode
will be a platform-specific launch failure error code.reason
是launch-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
Eventname
stringversion
string
Emitted when a plugin process has crashed.当插件进程崩溃时发出。
Event: 'destroyed'
Emitted when 当webContents
is destroyed.webContents
被销毁时发出。
Event: 'before-input-event'
Returns:返回:
event
Eventinput
Object -Input properties.输入属性。type
string -Either要么是keyUp
orkeyDown
.keyUp
要么是keyDown
。key
string -Equivalent to KeyboardEvent.key.等同于KeyboardEvent.key。code
string -Equivalent to KeyboardEvent.code.等同于KeyboardEvent.code。isAutoRepeat
boolean -Equivalent to KeyboardEvent.repeat.等同于KeyboardEvent.repeat。isComposing
boolean -Equivalent to KeyboardEvent.isComposing.等同于KeyboardEvent.isComposing。shift
boolean -Equivalent to KeyboardEvent.shiftKey.等同于KeyboardEvent.shiftKey。control
boolean -Equivalent to KeyboardEvent.controlKey.等同于KeyboardEvent.controlKey。alt
boolean -Equivalent to KeyboardEvent.altKey.等同于KeyboardEvent.altKey。meta
boolean -Equivalent to KeyboardEvent.metaKey.等同于KeyboardEvent.metaKey。location
number -Equivalent to KeyboardEvent.location.等同于KeyboardEvent.location。modifiers
string[] - See InputEvent.modifiers.
Emitted before dispatching the 在调度页面中的keydown
and keyup
events in the page. keydown
和keyup
事件之前发出。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
EventzoomDirection
string -Can be可以是in
orout
.in
或out
。
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 请注意,在macOS上,具有焦点意味着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.webContents
是窗口的第一个响应者,因此在窗口之间切换焦点不会触发webContents
的focus
和blur
事件,因为每个窗口的第一响应者不会改变。
The focus
and blur
events of webContents
should only be used to detect focus change between different webContents
and BrowserView
in the same window.webContents
的focus
和blur
事件只能用于检测同一窗口中不同webContents
和BrowserView
之间的焦点变化。
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
Eventurl
stringerror
string -The error code.错误代码。certificate
Certificatecallback
FunctionisTrusted
boolean -Indicates whether the certificate can be considered trusted.指示是否可以将证书视为可信证书。
isMainFrame
boolean
Emitted when failed to verify the 在验证certificate
for url
.url
的certificate
失败时发出。
The usage is the same with the 用法与certificate-error
event of app
.app
的certificate-error
事件相同。
Event: 'select-client-certificate'
Returns:返回:
event
Eventurl
URLcertificateList
Certificate[]callback
Functioncertificate
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
.app
的select-client-certificate
事件相同。
Event: 'login'
Returns:返回:
event
EventauthenticationResponseDetails
Objecturl
URL
authInfo
ObjectisProxy
booleanscheme
stringhost
stringport
Integerrealm
string
callback
Functionusername
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
Eventresult
ObjectrequestId
IntegeractiveMatchOrdinal
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
Eventcolor
(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
Eventurl
string
Emitted when mouse moves over a link or the keyboard moves the focus to a link.当鼠标在链接上移动或键盘将焦点移动到链接时发出。
Event: 'cursor-changed'
Returns:返回:
event
Eventtype
stringimage
NativeImage (optional)scale
Float (optional) -scaling factor for the custom cursor.自定义游标的缩放因子。size
Size (optional) -the size of theimage
.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
Eventparams
Objectx
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
orplugin
.none
、image
、audio
、video
、canvas
、file
或plugin
。hasImageContents
boolean -Whether the context menu was invoked on an image which has non-empty contents.是否在具有非空内容的图像上调用了上下文菜单。isEditable
boolean -Whether the context is editable.上下文是否可编辑。selectionText
string -Text of the selection that the context menu was invoked on.对其调用上下文菜单的所选内容的文本。titleText
string -Title text of the selection that the context menu was invoked on.调用上下文菜单的所选内容的标题文本。altText
string -Alt text of the selection that the context menu was invoked on.调用上下文菜单时所选内容的Alt文本。suggestedFilename
string -Suggested filename to be used when saving file through 'Save Link As' option of context menu.通过上下文菜单的“链接另存为”选项保存文件时使用的建议文件名。selectionRect
Rectangle -Rect representing the coordinates in the document space of the selection.矩形,表示所选内容在文档空间中的坐标。selectionStartOffset
number -Start position of the selection text.选择文本的起始位置。referrerPolicy
Referrer -The referrer policy of the frame on which the menu is invoked.调用菜单的框架的引用策略。misspelledWord
string -The misspelled word under the cursor, if any.游标下拼写错误的单词(如果有的话)。dictionarySuggestions
string[] -An array of suggested words to show the user to replace the一组建议的单词,向用户显示如何替换misspelledWord
.misspelledWord
.。Only available if there is a misspelled word and spellchecker is enabled.只有当有拼写错误的单词并且启用了拼写检查器时才可用。frameCharset
string -The character encoding of the frame on which the menu was invoked.调用菜单的帧的字符编码。inputFieldType
string -If the context menu was invoked on an input field, the type of that field.如果上下文菜单是在输入字段上调用的,则为该字段的类型。Possible values are可能的值是none
,plainText
,password
,other
.none
、plainText
、password
、other
。spellcheckEnabled
boolean -If the context is editable, whether or not spellchecking is enabled.如果上下文是可编辑的,则无论是否启用拼写检查。menuSourceType
string - Input source that invoked the context menu. Can benone
,mouse
,keyboard
,touch
,touchMenu
,longPress
,longTap
,touchHandle
,stylus
,adjustSelection
, oradjustSelectionReset
.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:返回:
event
Eventdevices
BluetoothDevice[]callback
FunctiondeviceId
string
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,应启用webBluetooth
。If 如果未调用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
EventdirtyRect
Rectangleimage
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
EventwebPreferences
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 thesrc
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
EventwebContents
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
Eventlevel
Integer -The log level, from 0 to 3. In order it matches日志级别,从0到3。按照顺序,它匹配verbose
,info
,warning
anderror
.verbose
、info
、warning
和error
。message
string -The actual console message实际控制台消息line
Integer -The line number of the source that triggered this console message触发此控制台消息的源的行号sourceId
string
Emitted when the associated window logs a console message.当关联的窗口记录控制台消息时发出。
Event: 'preload-error'
Returns:返回:
event
EventpreloadPath
stringerror
Error
Emitted when the preload script 当预加载脚本preloadPath
throws an unhandled exception error
.preloadPath
引发未处理的异常error
时发出。
Event: 'ipc-message'
Returns:返回:
event
Eventchannel
string...args
any[]
Emitted when the renderer process sends an asynchronous message via 当渲染器进程通过ipcRenderer.send()
.ipcRenderer.send()
发送异步消息时发出。
Event: 'ipc-message-sync'
Returns:返回:
event
Eventchannel
string...args
any[]
Emitted when the renderer process sends a synchronous message via 当渲染器进程通过ipcRenderer.sendSync()
.ipcRenderer.sendSync()
发送同步消息时发出。
Event: 'preferred-size-changed'
Returns:返回:
event
EventpreferredSize
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
Eventdetails
Objectframe
WebFrameMain
Emitted when the mainFrame, an 在页面中加载mainFrame、<iframe>
, or a nested <iframe>
is loaded within the page.<iframe>
或嵌套的<iframe>
时发出。
Instance Methods实例方法
contents.loadURL(url[, options])
url
string
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. url
。The 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 如果加载应该绕过http缓存,那么使用pragma
header to achieve it.pragma
头来实现它。
const { webContents } = require('electron')
const options = { extraHeaders: 'pragma: no-cache\n' }
webContents.loadURL('https://github.com', options)
contents.loadFile(filePath[, options])
filePath
string
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.session
的will-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
Returns返回Promise<string>
- A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via 一个promise,它用插入的CSS的一个键来解析,以后可以通过contents.removeInsertedCSS(key)
.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
stringuserGesture
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 在浏览器窗口中,一些HTML API(如requestFullScreen
can only be invoked by a gesture from the user. 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,要在其中运行javascript的世界的ID,0
is the default world,999
is the world used by Electron'scontextIsolation
feature.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
Objecturl
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 likehttps://the-origin/the/current/path/foo
.window.open('foo')
打开窗口会产生类似https://the-origin/the/current/path/foo
的效果。frameName
string -Name of the window provided inwindow.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
orother
.default
、foreground-tab
、background-tab
、new-window
、save-to-disk
或other
。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
.null
。Only 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 请参阅window.open()了解更多详细信息,以及如何将其与did-create-window
.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
numbermaximumLevel
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
Integery
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.要搜索的内容不能为空。
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])
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_micron
和height_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)
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 默认情况下,Electron通过创建具有本地视图的内部webContents
with native view, which developers have very limited control of. webContents
来管理开发工具,而开发人员对本地视图的控制非常有限。With the 使用setDevToolsWebContents
method, developers can use any webContents
to show the devtools in it, including BrowserWindow
, BrowserView
and <webview>
tag.setDevToolsWebContents
方法,开发人员可以使用任何webContents
来显示其中的开发工具,包括BrowserWindow
、BrowserView
和<webview>
标记。
Note that closing the devtools does not destroy the 请注意,关闭devtools并不会销毁devToolsWebContents
, it is caller's responsibility to destroy devToolsWebContents
.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])
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>
标记时,默认情况下mode
是detach
,显式传递空mode
可以强制使用上次使用的dock状态。
On Windows, if Windows Control Overlay is enabled, Devtools will be opened with 在Windows上,如果启用了Windows控制覆盖,则Devtools将以mode: 'detach'
.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
Integery
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 渲染器进程可以通过ipcRenderer模块监听channel
with the ipcRenderer module.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要发送到的帧的ID,或者一对[processId, frameId]
if the frame is in a different process to the main frame.[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 渲染器进程可以通过ipcRenderer模块监听channel
with the ipcRenderer module.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 您还可以从主进程中的所有传入IPC消息中读取frameId
from all incoming IPC messages in the main process.frameId
。
// In the main process
ipcMain.on('ping', (event) => {
console.info('Message came from frameId:', event.frameId)
})
contents.postMessage(channel, message, [transfer])
channel
stringmessage
anytransfer
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
ObjectscreenPosition
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)
inputEvent
MouseInputEvent | MouseWheelInputEvent | KeyboardInputEvent
Sends an input 将输入event
to the page. event
发送到页面。Note: The BrowserWindow containing the contents needs to be focused for 需要对包含内容的BrowserWindow进行聚焦,sendInputEvent()
to work.sendInputEvent()
才能工作。
contents.beginFrameSubscription([onlyDirty ,]callback)
onlyDirty
boolean (optional) -Defaults to默认为false
.false
。callback
Functionimage
NativeImagedirtyRect
Rectangle
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 该图像是NativeImage的一个实例,用于存储捕获的帧。image
is an instance of NativeImage that stores the captured frame.
The dirtyRect
is an object with x, y, width, height
properties that describes which part of the page was repainted. dirtyRect
是一个具有x
、y
、width
、height
属性的对象,用于描述页面的哪个部分被重新绘制。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
Objectfile
string -The path to the file being dragged.正在拖动的文件的路径。files
string[] (optional) -The paths to the files being dragged.要拖动的文件的路径。((files
will overridefile
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
. tab
的chromeMediaSource
与navigator.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 关联渲染器的Chromium内部pid
of the associated renderer. pid
。Can 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 获取一个V8堆快照并将其保存到filePath
.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
.backgroundPage
、window
、browserView
、remote
、webview
或offscreen
。
contents.setImageAnimationPolicy(policy)
policy
string -Can be可以是animate
,animateOnce
ornoAnimation
.animate
、animateOnce
或noAnimation
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 这是Chromium中的一个已知限制,您可以强制使用img.src = img.src
which will result in no network traffic but will update the animation policy.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 在整个Electron应用程序的所有webContents
instances of the entire Electron application.webContents
实例中,每个ID都是唯一的。
contents.session
Readonly
A Session used by this webContents.此webContents
使用的会话。
contents.hostWebContents
Readonly
A webContents instance that might own this 可能拥有此webContents
.webContents
的webContents实例。
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 用户永远不应该存储此对象,因为当DevTools关闭时,它可能会变为null
when the DevTools has been closed.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属性,表示页面框架层次结构的顶部框架。