webContents
渲染和控制网页。
进程:主进程
🌐 Process: Main
webContents 是一个 事件触发器。
它负责渲染和控制网页,并且是 BrowserWindow 对象的一个属性。访问 webContents 对象的示例:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL('https://github.com')
const contents = win.webContents
console.log(contents)
导航事件
🌐 Navigation Events
可以使用多个事件来监控 webContents 中发生的导航。
🌐 Several events can be used to monitor navigations as they occur within a webContents.
文档导航
🌐 Document Navigations
当 webContents 导航到另一个页面时(与页面内导航 相对),将会触发以下事件。
🌐 When a webContents navigates to another page (as opposed to an in-page navigation), the following events will be fired.
did-start-navigationwill-frame-navigatewill-navigate(仅在主框架导航时触发)will-redirect(仅在导航进程中发生重定向时触发)did-redirect-navigation(仅在导航进程中发生重定向时触发)did-frame-navigatedid-navigate(仅在主框架导航时触发)
如果在任何可取消事件上调用 event.preventDefault(),后续事件将不会触发。
🌐 Subsequent events will not fire if event.preventDefault() is called on any of the cancellable events.
页内导航
🌐 In-page Navigation
页面内导航不会导致页面重新加载,而是导航到当前页面内的一个位置。这些事件不能被取消。对于页面内导航,以下事件将按此顺序触发:
🌐 In-page navigations don't cause the page to reload, but instead navigate to a location within the current page. These events are not cancellable. For an in-page navigations, the following events will fire in this order:
框架导航
🌐 Frame Navigation
will-navigate 和 did-navigate 事件仅在 mainFrame 导航时触发。
如果你也想观察 <iframe> 中的导航,请使用 will-frame-navigate 和 did-frame-navigate 事件。
🌐 The will-navigate and did-navigate events only fire when the mainFrame navigates.
If you want to also observe navigations in <iframe>s, use will-frame-navigate and did-frame-navigate events.
方法
🌐 Methods
可以从 webContents 模块访问这些方法:
🌐 These methods can be accessed from the webContents module:
const { webContents } = require('electron')
console.log(webContents)
webContents.getAllWebContents()
返回 WebContents[] - 一个包含所有 WebContents 实例的数组。它将包含所有窗口、WebView、已打开的开发者工具以及开发者工具扩展后台页面的网页内容。
🌐 Returns WebContents[] - An array of all WebContents instances. This will contain web contents
for all windows, webviews, opened DevTools, and DevTools extension background pages.
webContents.getFocusedWebContents()
返回 WebContents | null - 此应用中当前聚焦的网页内容,否则返回 null。
🌐 Returns WebContents | null - The web contents that is focused in this application, otherwise
returns null.
webContents.fromId(id)
id整数
返回 WebContents | undefined——具有给定 ID 的 WebContents 实例;如果没有与给定 ID 关联的 WebContents,则返回 undefined。
🌐 Returns WebContents | undefined - A WebContents instance with the given ID, or
undefined if there is no WebContents associated with the given ID.
webContents.fromFrame(frame)
frame网络框架主程序
返回 WebContents | undefined - 使用给定的 WebFrameMain 创建的 WebContents 实例,或者如果给定的 WebFrameMain 没有关联的 WebContents,则返回 undefined。
🌐 Returns WebContents | undefined - A WebContents instance with the given WebFrameMain, or
undefined if there is no WebContents associated with the given WebFrameMain.
webContents.fromDevToolsTargetId(targetId)
targetId字符串 - 与该 WebContents 实例关联的 Chrome DevTools 协议 TargetID。
返回 WebContents | undefined - 一个具有给定 TargetID 的 WebContents 实例;如果没有与给定 TargetID 关联的 WebContents,则返回 undefined。
🌐 Returns WebContents | undefined - A WebContents instance with the given TargetID, or
undefined if there is no WebContents associated with the given TargetID.
在与 Chrome DevTools Protocol 通信时,根据分配的 TargetID 查找 WebContents 实例可能会很有用。
🌐 When communicating with the Chrome DevTools Protocol, it can be useful to lookup a WebContents instance based on its assigned TargetID.
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 wc.fromDevToolsTargetId(targetId)
}
类:WebContents
🌐 Class: WebContents
渲染并控制 BrowserWindow 实例的内容。
进程: 主进程
此类未从 'electron' 模块导出。它仅作为 Electron API 中其他方法的返回值提供。
实例事件
🌐 Instance Events
Event: 'did-finish-load'
当导航完成时触发,即标签页的加载指示器已停止旋转,并且已分发 onload 事件。
🌐 Emitted when the navigation is done, i.e. the spinner of the tab has stopped
spinning, and the onload event was dispatched.
Event: 'did-fail-load'
返回:
🌐 Returns:
event活动errorCode整数errorDescription字符串validatedURL字符串isMainFrame布尔值frameProcessId整数frameRoutingId整数
此事件类似于 did-finish-load,但在加载失败时触发。完整的错误代码列表及其含义可在 此处 查看。
🌐 This event is like did-finish-load but emitted when the load failed.
The full list of error codes and their meaning is available here.
Event: 'did-fail-provisional-load'
返回:
🌐 Returns:
event活动errorCode整数errorDescription字符串validatedURL字符串isMainFrame布尔值frameProcessId整数frameRoutingId整数
这个事件类似于 did-fail-load,但在加载被取消时触发(例如,当调用了 window.stop())。
🌐 This event is like did-fail-load but emitted when the load was cancelled
(e.g. window.stop() was invoked).
Event: 'did-frame-finish-load'
返回:
🌐 Returns:
event活动isMainFrame布尔值frameProcessId整数frameRoutingId整数
当框架完成导航时发出。
🌐 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'
当加载顶层框架中的文档时发出。
🌐 Emitted when the document in the top-level frame is loaded.
Event: 'page-title-updated'
返回:
🌐 Returns:
event活动title字符串explicitSet布尔值
在导航进程中设置页面标题时触发。当标题由文件 URL 合成时,explicitSet 为 false。
🌐 Fired when page title is set during navigation. explicitSet is false when
title is synthesized from file url.
Event: 'page-favicon-updated'
返回:
🌐 Returns:
event活动faviconsstring[] - URL 数组。
当页面收到 favicon url 时发出。
🌐 Emitted when page receives favicon urls.
Event: 'content-bounds-updated'
返回:
🌐 Returns:
event活动bounds矩形 - 请求新的内容边界
当页面调用 window.moveTo、window.resizeTo 或相关 API 时触发。
🌐 Emitted when the page calls window.moveTo, window.resizeTo or related APIs.
默认情况下,这将移动窗口。要防止这种行为,请调用 event.preventDefault()。
🌐 By default, this will move the window. To prevent that behavior, call
event.preventDefault().
Event: 'did-create-window'
返回:
🌐 Returns:
window浏览器窗口details对象url字符串 - 已创建窗口的 URL。frameName字符串 - 在window.open()调用中为创建的窗口指定的名称。referrer引用来源 - 将传递给新窗口的引用来源。是否发送Referer头取决于引用来源策略,可能会发送,也可能不会发送。postBodyPostBody(可选)- 将发送到新窗口的帖子数据,以及将设置的相应头。如果不发送任何帖子数据,值将为null。仅在窗口由设置了target=_blank的表单创建时定义。disposition字符串 - 可以是default、foreground-tab、background-tab、new-window或other。
在渲染器中通过 window.open 成功创建窗口后触发。如果窗口的创建被 webContents.setWindowOpenHandler 取消,则不会触发。
🌐 Emitted after successful creation of a window via window.open in the renderer.
Not emitted if the creation of the window is canceled from
webContents.setWindowOpenHandler.
有关更多详细信息以及如何将其与 webContents.setWindowOpenHandler 一起使用,请参见 window.open()。
🌐 See window.open() for more details and how to use this in conjunction with webContents.setWindowOpenHandler.
Event: 'will-navigate'
返回:
🌐 Returns:
- “details”事件<>
url字符串 - 框架正在导航到的 URL。isSameDocument布尔值 - 对于使用 window.history API 的同一文档导航和引用片段导航,此事件不会触发。此属性在此事件中始终设置为false。isMainFrame布尔值 - 如果导航发生在主框架中,则为真。frameWebFrameMain | null - 要导航的框架。如果在框架已经导航或被销毁后访问,可能为null。initiatorWebFrameMain | null(可选) - 发起导航的框架,可以是父框架(例如,通过使用框架名称的window.open),如果导航不是由框架发起,则为 null。如果在事件触发前发起导航的框架已被删除,也可能为 null。
url字符串 已弃用isInPlace布尔类型 已弃用isMainFrame布尔型 已弃用frameProcessId整数 已弃用frameRoutingId整数 已弃用
当用户或页面想在主框架上开始导航时触发。它可能发生在 window.location 对象被更改或用户在页面中点击链接时。
🌐 Emitted when a user or the page wants to start navigation on the main frame. It can happen when
the window.location object is changed or a user clicks a link in the page.
当使用像 webContents.loadURL 和 webContents.back 这样的 API 编程方式启动导航时,该事件不会触发。
🌐 This event will not emit when the navigation is started programmatically with
APIs like webContents.loadURL and webContents.back.
对于页内导航,例如点击锚点链接或更新 window.location.hash,也不会触发它。请使用 did-navigate-in-page 事件来实现此目的。
🌐 It is also not emitted for in-page navigations, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
调用 event.preventDefault() 将阻止导航。
🌐 Calling event.preventDefault() will prevent the navigation.
Event: 'will-frame-navigate'
返回:
🌐 Returns:
- “details”事件<>
url字符串 - 框架正在导航到的 URL。isSameDocument布尔值 - 对于使用 window.history API 的同一文档导航和引用片段导航,此事件不会触发。此属性在此事件中始终设置为false。isMainFrame布尔值 - 如果导航发生在主框架中,则为真。frameWebFrameMain | null - 要导航的框架。如果在框架已经导航或被销毁后访问,可能为null。initiatorWebFrameMain | null(可选) - 发起导航的框架,可以是父框架(例如,通过使用框架名称的window.open),如果导航不是由框架发起,则为 null。如果在事件触发前发起导航的框架已被删除,也可能为 null。
当用户或页面想要在任何帧中开始导航时触发。它可能发生在 window.location 对象被更改或用户在页面中点击链接时。
🌐 Emitted when a user or the page wants to start navigation in any frame. It can happen when
the window.location object is changed or a user clicks a link in the page.
与 will-navigate 不同,will-frame-navigate 会在主框架或其任何子框架尝试导航时触发。当导航事件来自主框架时,isMainFrame 将是 true。
🌐 Unlike will-navigate, will-frame-navigate is fired when the main frame or any of its subframes attempts to navigate. When the navigation event comes from the main frame, isMainFrame will be true.
当使用像 webContents.loadURL 和 webContents.back 这样的 API 编程方式启动导航时,该事件不会触发。
🌐 This event will not emit when the navigation is started programmatically with
APIs like webContents.loadURL and webContents.back.
对于页内导航,例如点击锚点链接或更新 window.location.hash,也不会触发它。请使用 did-navigate-in-page 事件来实现此目的。
🌐 It is also not emitted for in-page navigations, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
调用 event.preventDefault() 将阻止导航。
🌐 Calling event.preventDefault() will prevent the navigation.
Event: 'did-start-navigation'
返回:
🌐 Returns:
- “details”事件<>
url字符串 - 框架正在导航到的 URL。isSameDocument布尔值 - 指导航是否在不更改文档的情况下发生。相同文档导航的例子包括引用片段导航、pushState/replaceState,以及同一页面的历史导航。isMainFrame布尔值 - 如果导航发生在主框架中,则为真。frameWebFrameMain | null - 要导航的框架。如果在框架已经导航或被销毁后访问,可能为null。initiatorWebFrameMain | null(可选) - 发起导航的框架,可以是父框架(例如,通过使用框架名称的window.open),如果导航不是由框架发起,则为 null。如果在事件触发前发起导航的框架已被删除,也可能为 null。
url字符串 已弃用isInPlace布尔类型 已弃用isMainFrame布尔型 已弃用frameProcessId整数 已弃用frameRoutingId整数 已弃用
当任何框架(包括主框架)开始导航时发出。
🌐 Emitted when any frame (including main) starts navigating.
Event: 'will-redirect'
返回:
🌐 Returns:
- “details”事件<>
url字符串 - 框架正在导航到的 URL。isSameDocument布尔值 - 指导航是否在不更改文档的情况下发生。相同文档导航的例子包括引用片段导航、pushState/replaceState,以及同一页面的历史导航。isMainFrame布尔值 - 如果导航发生在主框架中,则为真。frameWebFrameMain | null - 要导航的框架。如果在框架已经导航或被销毁后访问,可能为null。initiatorWebFrameMain | null(可选) - 发起导航的框架,可以是父框架(例如,通过使用框架名称的window.open),如果导航不是由框架发起,则为 null。如果在事件触发前发起导航的框架已被删除,也可能为 null。
url字符串 已弃用isInPlace布尔类型 已弃用isMainFrame布尔型 已弃用frameProcessId整数 已弃用frameRoutingId整数 已弃用
当导航进程中发生服务器端重定向时触发。例如,302 重定向。
🌐 Emitted when a server side redirect occurs during navigation. For example a 302 redirect.
此事件将在 did-start-navigation 之后触发,并且总是在同一次导航的 did-redirect-navigation 事件之前触发。
🌐 This event will be emitted after did-start-navigation and always before the
did-redirect-navigation event for the same navigation.
调用 event.preventDefault() 将会阻止导航(不仅仅是重定向)。
🌐 Calling event.preventDefault() will prevent the navigation (not just the
redirect).
Event: 'did-redirect-navigation'
返回:
🌐 Returns:
- “details”事件<>
url字符串 - 框架正在导航到的 URL。isSameDocument布尔值 - 指导航是否在不更改文档的情况下发生。相同文档导航的例子包括引用片段导航、pushState/replaceState,以及同一页面的历史导航。isMainFrame布尔值 - 如果导航发生在主框架中,则为真。frameWebFrameMain | null - 要导航的框架。如果在框架已经导航或被销毁后访问,可能为null。initiatorWebFrameMain | null(可选) - 发起导航的框架,可以是父框架(例如,通过使用框架名称的window.open),如果导航不是由框架发起,则为 null。如果在事件触发前发起导航的框架已被删除,也可能为 null。
url字符串 已弃用isInPlace布尔类型 已弃用isMainFrame布尔型 已弃用frameProcessId整数 已弃用frameRoutingId整数 已弃用
在导航进程中发生服务器端重定向后触发。例如,302 重定向。
🌐 Emitted after a server side redirect occurs during navigation. For example a 302 redirect.
此事件无法被阻止,如果你想阻止重定向,你应该查看上面的 will-redirect 事件。
🌐 This event cannot be prevented, if you want to prevent redirects you should
check out the will-redirect event above.
Event: 'did-navigate'
返回:
🌐 Returns:
event活动url字符串httpResponseCode整数 - 对于非 HTTP 导航为 -1httpStatusText字符串 - 对于非 HTTP 导航为空
当主框架导航完成时发出。
🌐 Emitted when a main frame navigation is done.
此事件不会在页面内导航时触发,例如点击锚点链接或更新 window.location.hash。请使用 did-navigate-in-page 事件来实现此目的。
🌐 This event is not emitted for in-page navigations, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
Event: 'did-frame-navigate'
返回:
🌐 Returns:
event活动url字符串httpResponseCode整数 - 对于非 HTTP 导航为 -1httpStatusText字符串 - 对于非 HTTP 导航为空,isMainFrame布尔值frameProcessId整数frameRoutingId整数
当任何帧导航完成时发出。
🌐 Emitted when any frame navigation is done.
此事件不会在页面内导航时触发,例如点击锚点链接或更新 window.location.hash。请使用 did-navigate-in-page 事件来实现此目的。
🌐 This event is not emitted for in-page navigations, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
Event: 'did-navigate-in-page'
返回:
🌐 Returns:
event活动url字符串isMainFrame布尔值frameProcessId整数frameRoutingId整数
当任何框架中发生页内导航时发出。
🌐 Emitted when an in-page navigation happened in any frame.
当页面内导航发生时,页面 URL 会发生变化,但不会导致页面外的导航。这种情况的例子包括点击锚点链接或触发 DOM hashchange 事件时。
🌐 When in-page navigation happens, the page URL changes but does not cause
navigation outside of the page. Examples of this occurring are when anchor links
are clicked or when the DOM hashchange event is triggered.
Event: 'will-prevent-unload'
返回:
🌐 Returns:
event活动
当 beforeunload 事件处理程序试图取消页面卸载时触发。
🌐 Emitted when a beforeunload event handler is attempting to cancel a page unload.
调用 event.preventDefault() 将忽略 beforeunload 事件处理程序,并允许页面被卸载。
🌐 Calling event.preventDefault() will ignore the beforeunload event handler
and allow the page to be unloaded.
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()
}
})
这将会在 BrowserViews 中触发,但不会被遵循——这是因为我们选择不将 BrowserView 的生命周期绑定到其所属的 BrowserWindow(如果存在)上,根据 规范。
Event: 'render-process-gone'
返回:
🌐 Returns:
event活动detailsRenderProcessGoneDetails
当渲染进程意外消失时触发。这通常是由于进程崩溃或被终止。
🌐 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: 'destroyed'
当 webContents 被销毁时触发。
🌐 Emitted when webContents is destroyed.
Event: 'input-event'
返回:
🌐 Returns:
event活动inputEvent输入事件
当输入事件发送到 WebContents 时触发。详情请参见 InputEvent。
🌐 Emitted when an input event is sent to the WebContents. See InputEvent for details.
Event: 'before-input-event'
返回:
🌐 Returns:
event活动input对象 - 输入属性。type字符串 - 可以是keyUp或keyDown。key字符串 - 等同于 KeyboardEvent.key。code字符串 - 等同于 KeyboardEvent.code。isAutoRepeat布尔值 - 等同于 KeyboardEvent.repeat。isComposing布尔值 - 等同于 KeyboardEvent.isComposing。shift布尔值 - 等同于 KeyboardEvent.shiftKey。control布尔值 - 等同于 KeyboardEvent.controlKey。alt布尔值 - 等同于 KeyboardEvent.altKey。meta布尔值 - 等同于 KeyboardEvent.metaKey。location数字 - 相当于 KeyboardEvent.location。modifiers字符串数组 - 参见 InputEvent.modifiers。
在页面分发 keydown 和 keyup 事件之前触发。调用 event.preventDefault 将阻止页面的 keydown/keyup 事件以及菜单快捷键。
🌐 Emitted before dispatching the keydown and keyup events in the page.
Calling event.preventDefault will prevent the page keydown/keyup events
and the menu shortcuts.
如果只想阻止菜单快捷键,请使用 setIgnoreMenuShortcuts:
🌐 To only prevent the menu shortcuts, use
setIgnoreMenuShortcuts:
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-input-event', (event, input) => {
// Enable application menu keyboard shortcuts when Ctrl/Cmd are down.
win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta)
})
})
Event: 'before-mouse-event'
返回:
🌐 Returns:
event活动mouse鼠标输入事件
在页面中调度鼠标事件之前发出。
🌐 Emitted before dispatching mouse events in the page.
调用 event.preventDefault 将会阻止页面鼠标事件。
🌐 Calling event.preventDefault will prevent the page mouse events.
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-mouse-event', (event, mouse) => {
// Prevent mouseDown events.
if (mouse.type === 'mouseDown') {
console.log(mouse)
/*
{
type: 'mouseDown',
clickCount: 1,
movementX: 0,
movementY: 0,
button: 'left',
x: 632.359375,
y: 480.6875,
globalX: 168.359375,
globalY: 193.6875
}
*/
event.preventDefault()
}
})
})
Event: 'enter-html-full-screen'
当窗口进入由 HTML API 触发的全屏状态时发出。
🌐 Emitted when the window enters a full-screen state triggered by HTML API.
Event: 'leave-html-full-screen'
当窗口离开由 HTML API 触发的全屏状态时发出。
🌐 Emitted when the window leaves a full-screen state triggered by HTML API.
Event: 'zoom-changed'
返回:
🌐 Returns:
event活动zoomDirection字符串 - 可以是in或out。
当用户请求使用鼠标滚轮更改缩放级别时发出。
🌐 Emitted when the user is requesting to change the zoom level using the mouse wheel.
Event: 'blur'
当 WebContents 失去焦点时触发。
🌐 Emitted when the WebContents loses focus.
Event: 'focus'
当 WebContents 获得焦点时触发。
🌐 Emitted when the WebContents gains focus.
请注意,在 macOS 上,获得焦点意味着 WebContents 是窗口的第一响应者,因此在窗口之间切换焦点不会触发 WebContents 的 focus 和 blur 事件,因为每个窗口的第一响应者并未改变。
🌐 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.
WebContents 的 focus 和 blur 事件应仅用于检测同一窗口中不同 WebContents 和 BrowserView 之间的焦点变化。
🌐 The focus and blur events of WebContents should only be used to detect
focus change between different WebContents and BrowserView in the same
window.
Event: 'devtools-open-url'
返回:
🌐 Returns:
event活动url字符串 - 被点击或选择的链接的 URL。
当在开发者工具中点击链接或在其上下文菜单中选择“在新标签页中打开”时触发。
🌐 Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu.
Event: 'devtools-search-query'
返回:
🌐 Returns:
event活动query字符串 - 要查询的文本。
当在其右键菜单中为文本选择“搜索”时触发。
🌐 Emitted when 'Search' is selected for text in its context menu.
Event: 'devtools-opened'
打开 DevTools 时发出。
🌐 Emitted when DevTools is opened.
Event: 'devtools-closed'
当 DevTools 关闭时发出。
🌐 Emitted when DevTools is closed.
Event: 'devtools-focused'
当 DevTools 聚焦/打开时发出。
🌐 Emitted when DevTools is focused / opened.
Event: 'certificate-error'
返回:
🌐 Returns:
event活动url字符串error字符串 - 错误代码。certificate证书callback函数isTrusted布尔值 - 表示该证书是否可以被视为可信。
isMainFrame布尔值
当无法验证 url 的 certificate 时触发。
🌐 Emitted when failed to verify the certificate for url.
用法与 app 的 certificate-error 事件 相同。
🌐 The usage is the same with the certificate-error event of app.
Event: 'select-client-certificate'
返回:
🌐 Returns:
请求客户端证书时发出。
🌐 Emitted when a client certificate is requested.
用法与 app 的 select-client-certificate 事件 相同。
🌐 The usage is the same with the select-client-certificate event of app.
Event: 'login'
返回:
🌐 Returns:
event活动authenticationResponseDetails对象url网址
authInfo对象isProxy布尔值scheme字符串host字符串port整数realm字符串
callback函数username字符串(可选)password字符串(可选)
当 webContents 想要进行基本身份验证时触发。
🌐 Emitted when webContents wants to do basic auth.
用法与 app 的 login 事件 相同。
🌐 The usage is the same with the login event of app.
Event: 'found-in-page'
返回:
🌐 Returns:
event活动result对象requestId整数activeMatchOrdinal整数 - 活动匹配的位置。matches整数 - 比赛数量。selectionArea矩形 - 第一个匹配区域的坐标。finalUpdate布尔值
当webContents.findInPage请求有结果可用时触发。
🌐 Emitted when a result is available for
webContents.findInPage request.
Event: 'media-started-playing'
当媒体开始播放时发出。
🌐 Emitted when media starts playing.
Event: 'media-paused'
当媒体暂停或播放完毕时发出。
🌐 Emitted when media is paused or done playing.
Event: 'audio-state-changed'
返回:
🌐 Returns:
- “event”事件<>
audible布尔值 - 如果一个或多个帧或子webContents正在发出音频,则为真。
当媒体变得可听见或不可听见时发出。
🌐 Emitted when media becomes audible or inaudible.
Event: 'did-change-theme-color'
返回:
🌐 Returns:
event活动color(字符串 | 空)- 主题颜色的格式为 '#rrggbb'。当未设置主题颜色时,值为null。
当页面的主题颜色更改时触发。通常是由于遇到 meta 标签导致的:
🌐 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活动url字符串
当鼠标移动到链接上或键盘将焦点移动到链接时发出。
🌐 Emitted when mouse moves over a link or the keyboard moves the focus to a link.
Event: 'cursor-changed'
返回:
🌐 Returns:
event活动type字符串image本地图片(可选)scale浮点数(可选)- 自定义光标的缩放因子。size尺寸(可选)-image的尺寸。hotspot点(可选)- 自定义光标热点的坐标。
当光标类型发生变化时触发。type 参数可以是 pointer、crosshair、hand、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、m-panning-vertical、m-panning-horizontal、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、custom、null、drag-drop-none、drag-drop-move、drag-drop-copy、drag-drop-link、ns-no-resize、ew-no-resize、nesw-no-resize、nwse-no-resize 或 default。
🌐 Emitted when the cursor's type changes. The type parameter can be pointer,
crosshair, hand, 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, m-panning-vertical,
m-panning-horizontal, 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, custom, null, drag-drop-none, drag-drop-move, drag-drop-copy,
drag-drop-link, ns-no-resize, ew-no-resize, nesw-no-resize, nwse-no-resize,
or default.
如果 type 参数是 custom,则 image 参数将以 NativeImage 的形式保存自定义光标图片,而 scale、size 和 hotspot 将保存关于自定义光标的额外信息。
🌐 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活动params对象x整数 - x 坐标。y整数 - y 坐标。frameWebFrameMain | null - 上下文菜单被调用的框架。如果在框架导航或被销毁后访问,可能为null。linkURL字符串 - 包含触发上下文菜单节点的链接的 URL。linkText字符串 - 与链接相关的文本。如果链接内容是图片,该字符串可能为空。pageURL字符串 - 调用上下文菜单的顶层页面的 URL。frameURL字符串 - 调用上下文菜单的子框架的 URL。srcURL字符串 - 调用上下文菜单时该元素的源 URL。具有源 URL 的元素包括图片、音频和视频。mediaType字符串 - 上下文菜单被调用时节点的类型。可以是none、image、audio、video、canvas、file或plugin。hasImageContents布尔值 - 上下文菜单是否在具有非空内容的图片上被调用。isEditable布尔值 - 上下文是否可编辑。selectionText字符串 - 调用上下文菜单时所选文本的内容。titleText字符串 - 调用上下文菜单的所选项的标题文本。altText字符串 - 调用上下文菜单的所选项的替代文本。suggestedFilename字符串 - 建议的文件名,用于通过右键菜单的“另存为”选项保存文件时使用。selectionRect矩形 - 表示文档空间中选区坐标的矩形。selectionStartOffset编号 - 选中文本的起始位置。referrerPolicy引用来源 - 调用菜单的框架的引用来源策略。misspelledWord字符串 - 光标下的拼写错误单词(如果有)。dictionarySuggestionsstring[] - 一个建议词数组,用于向用户显示以替换misspelledWord。仅在存在拼写错误且启用了拼写检查器时可用。frameCharset字符串 - 调用菜单的帧的字符编码。formControlType字符串 - 调用上下文菜单的源。可能的值包括none、button-button、field-set、input-button、input-checkbox、input-color、input-date、input-datetime-local、input-email、input-file、input-hidden、input-image、input-month、input-number、input-password、input-radio、input-range、input-reset、input-search、input-submit、input-telephone、input-text、input-time、input-url、input-week、output、reset-button、select-list、select-list、select-multiple、select-one、submit-button和text-area。spellcheckEnabled布尔值 - 如果上下文是可编辑的,是否启用拼写检查。menuSourceType字符串 - 调用上下文菜单的输入来源。可以是none、mouse、keyboard、touch、touchMenu、longPress、longTap、touchHandle、stylus、adjustSelection或adjustSelectionReset。mediaFlags对象 - 调用上下文菜单的媒体元素的标志。inError布尔值 - 媒体元素是否已崩溃。isPaused布尔值 - 媒体元素是否已暂停。isMuted布尔值 - 媒体元素是否被静音。hasAudio布尔值 - 媒体元素是否有音频。isLooping布尔值 - 媒体元素是否循环播放。isControlsVisible布尔值 - 媒体元素的控件是否可见。canToggleControls布尔值 - 媒体元素的控件是否可切换。canPrint布尔值 - 媒体元素是否可以打印。canSave布尔值 - 表示媒体元素是否可以被下载。canShowPictureInPicture布尔值 - 媒体元素是否可以显示画中画。isShowingPictureInPicture布尔值 - 指示媒体元素当前是否正在显示画中画模式。canRotate布尔值 - 媒体元素是否可以旋转。canLoop布尔值 - 媒体元素是否可以循环播放。
editFlags对象 - 这些标志表示渲染器是否认为能够执行相应的操作。canUndo布尔值 - 渲染器认为它是否可以撤销。canRedo布尔值 - 渲染器认为它是否可以重做。canCut布尔值 - 渲染器认为它是否可以剪切。canCopy布尔值 - 渲染器认为它是否可以复制。canPaste布尔值 - 渲染器认为它是否可以粘贴。canDelete布尔值 - 渲染器认为它是否可以删除。canSelectAll布尔值 - 渲染器是否认为它可以选择全部。canEditRichly布尔值 - 渲染器是否认为它可以进行富文本编辑。
当有需要处理的新上下文菜单时发出。
🌐 Emitted when there is a new context menu that needs to be handled.
Event: 'select-bluetooth-device'
返回:
🌐 Returns:
event活动devices蓝牙设备数组callback函数deviceId字符串
当调用 navigator.bluetooth.requestDevice 时需要选择蓝牙设备时,会触发此事件。应调用 callback 并传入要选择的设备的 deviceId。传入空字符串给 callback 将取消该请求。
🌐 Emitted when a bluetooth device needs to be selected when a call to
navigator.bluetooth.requestDevice is made. callback should be called with
the deviceId of the device to be selected. Passing an empty string to
callback will cancel the request.
如果没有为此事件添加事件监听器,则所有蓝牙请求都将被取消。
🌐 If no event listener is added for this event, all bluetooth requests will be cancelled.
如果在处理此事件时未调用 event.preventDefault,将自动选择第一个可用设备。
🌐 If event.preventDefault is not called when handling this event, the first available
device will be automatically selected.
由于蓝牙的特性,在调用 navigator.bluetooth.requestDevice 时扫描设备可能需要一些时间,并且会导致 select-bluetooth-device 多次触发,直到调用 callback 并传入设备 ID 或空字符串以取消请求。
🌐 Due to the nature of bluetooth, scanning for devices when
navigator.bluetooth.requestDevice is called may take time and will cause
select-bluetooth-device to fire multiple times until callback is called
with either a device id or an empty string to cancel the request.
const { app, BrowserWindow } = require('electron')
let win = null
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) {
// The device wasn't found so we need to either wait longer (eg until the
// device is turned on) or cancel the request by calling the callback
// with an empty string.
callback('')
} else {
callback(result.deviceId)
}
})
})
Event: 'paint'
返回:
🌐 Returns:
- “details”事件<>
textureOffscreenSharedTexture(可选)实验性 - 当webPreferences.offscreen.useSharedTexture为true时,帧的 GPU 共享纹理。
dirtyRect矩形image原生图片 - 整个帧的图片数据。
当生成新帧时发出。缓冲区中只传递脏区域。
🌐 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.toBitmap())
})
win.loadURL('https://github.com')
在使用共享纹理(将 webPreferences.offscreen.useSharedTexture 设置为 true)功能时,你可以在不通过 CPU 和 GPU 内存之间拷贝数据的情况下,将纹理句柄传递给外部渲染管线,同时利用 Chromium 的硬件加速支持。这一功能对高性能渲染场景非常有用。
🌐 When using shared texture (set webPreferences.offscreen.useSharedTexture to true) feature, you can pass the texture handle to external rendering pipeline without the overhead of
copying data between CPU and GPU memory, with Chromium's hardware acceleration support. This feature is helpful for high-performance rendering scenarios.
同一时间只能存在有限数量的纹理,因此在使用完纹理后尽快调用 texture.release() 非常重要。
通过自行管理纹理的生命周期,你可以安全地通过 IPC 将 texture.textureInfo 传递给其他进程。
🌐 Only a limited number of textures can exist at the same time, so it's important that you call texture.release() as soon as you're done with the texture.
By managing the texture lifecycle by yourself, you can safely pass the texture.textureInfo to other processes through IPC.
更多详细信息请参见离屏渲染教程。要了解如何在本地代码中处理纹理,请参考离屏渲染的代码文档。
🌐 More details can be found in the offscreen rendering tutorial. To learn about how to handle the texture in native code, refer to offscreen rendering's code documentation..
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ webPreferences: { offscreen: { useSharedTexture: true } } })
win.webContents.on('paint', async (e, dirty, image) => {
if (e.texture) {
// By managing lifecycle yourself, you can handle the event in async handler or pass the `e.texture.textureInfo`
// to other processes (not `e.texture`, the `e.texture.release` function is not passable through IPC).
await new Promise(resolve => setTimeout(resolve, 50))
// You can send the native texture handle to native code for importing into your rendering pipeline.
// Read more at https://github.com/electron/electron/blob/main/shell/browser/osr/README.md
// importTextureHandle(dirty, e.texture.textureInfo)
// You must call `e.texture.release()` as soon as possible, before the underlying frame pool is drained.
e.texture.release()
}
})
win.loadURL('https://github.com')
Event: 'devtools-reload-page'
当 DevTools 窗口指示 webContents 重新加载时触发
🌐 Emitted when the DevTools window instructs the webContents to reload
Event: 'will-attach-webview'
返回:
🌐 Returns:
event活动webPreferencesWebPreferences - 将用于访客页面的网页偏好设置。可以修改此对象以调整访客页面的偏好设置。paramsRecord<string, string> - 其他<webview>参数,如srcURL。 该对象可以修改以调整访客页面的参数。
当 <webview> 的网页内容被附加到此网页内容时触发。调用 event.preventDefault() 将销毁访客页面。
🌐 Emitted when a <webview>'s web contents is being attached to this web
contents. Calling event.preventDefault() will destroy the guest page.
此事件可用于在加载 <webview> 之前配置其 webContents 的 webPreferences,并提供设置无法通过 <webview> 属性设置的选项的能力。
🌐 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.
Event: 'did-attach-webview'
返回:
🌐 Returns:
event活动webContentsWebContents -<webview>使用的来宾网页内容。
当 <webview> 已附加到此网页内容时触发。
🌐 Emitted when a <webview> has been attached to this web contents.
Event: 'console-message'
返回:
🌐 Returns:
- “details”事件<>
message字符串 - 消息文本level字符串 - 消息严重性,可能的值包括info、warning、error和debug。lineNumber整数 - 日志源中的行号sourceId字符串 - 日志源的 URLframeWebFrameMain - 记录该消息的框架
level整数 已弃用 - 日志级别,范围从 0 到 3。其顺序对应verbose、info、warning和error。message字符串 已弃用 - 实际的控制台消息line整数 已弃用 - 触发此控制台消息的源代码行号sourceId字符串 已弃用
当关联的窗口记录控制台消息时发出。
🌐 Emitted when the associated window logs a console message.
Event: 'preload-error'
返回:
🌐 Returns:
event活动preloadPath字符串error错误
当预加载脚本 preloadPath 抛出未处理的异常 error 时触发。
🌐 Emitted when the preload script preloadPath throws an unhandled exception error.
Event: 'ipc-message'
返回:
🌐 Returns:
eventIpcMainEventchannel字符串...argsany[]
当渲染进程通过 ipcRenderer.send() 发送异步消息时触发。
🌐 Emitted when the renderer process sends an asynchronous message via ipcRenderer.send().
另请参见 webContents.ipc,它提供了类似 IpcMain 的接口,用于专门响应来自此 WebContents 的 IPC 消息。
🌐 See also webContents.ipc, which provides an IpcMain-like interface for responding to IPC messages specifically from this WebContents.
Event: 'ipc-message-sync'
返回:
🌐 Returns:
eventIpcMainEventchannel字符串...argsany[]
当渲染进程通过 ipcRenderer.sendSync() 发送同步消息时触发。
🌐 Emitted when the renderer process sends a synchronous message via ipcRenderer.sendSync().
另请参见 webContents.ipc,它提供了类似 IpcMain 的接口,用于专门响应来自此 WebContents 的 IPC 消息。
🌐 See also webContents.ipc, which provides an IpcMain-like interface for responding to IPC messages specifically from this WebContents.
Event: 'preferred-size-changed'
返回:
🌐 Returns:
event活动preferredSize尺寸 - 容纳文档布局所需的最小尺寸——无需滚动即可显示。
当 WebContents 的首选大小发生变化时触发。
🌐 Emitted when the WebContents preferred size has changed.
只有在 webPreferences 中将 enablePreferredSizeMode 设置为 true 时,才会触发此事件。
🌐 This event will only be emitted when enablePreferredSizeMode is set to true
in webPreferences.
Event: 'frame-created'
返回:
🌐 Returns:
event活动details对象frameWebFrameMain | null - 创建的框架。 如果在框架导航或被销毁后访问,可能是null。
当页面中加载 mainFrame、一个 <iframe> 或嵌套的 <iframe> 时触发。
🌐 Emitted when the mainFrame, an <iframe>, or a nested <iframe> is loaded within the page.
实例方法
🌐 Instance Methods
contents.loadURL(url[, options])
url字符串
返回 Promise<void> —— 当页面加载完成时,Promise 将会解析(参见 did-finish-load),如果页面加载失败则会拒绝(参见 did-fail-load)。已经附加了一个空操作的拒绝处理程序,以避免未处理的拒绝错误。如果现有页面有 beforeUnload 处理程序,除非 will-prevent-unload 被处理,否则会调用 did-fail-load。
🌐 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). A noop rejection handler is already attached, which avoids unhandled rejection errors. If the existing page has a beforeUnload handler, did-fail-load will be called unless will-prevent-unload is handled.
在窗口中加载 url。url 必须包含协议前缀,例如 http:// 或 file://。如果加载时需要跳过 HTTP 缓存,则使用 pragma 头来实现。
🌐 Loads the url in the window. The url must contain the protocol prefix,
e.g. the http:// or file://. If the load should bypass http cache then
use the pragma header to achieve it.
const win = new BrowserWindow()
const options = { extraHeaders: 'pragma: no-cache\n' }
win.webContents.loadURL('https://github.com', options)
contents.loadFile(filePath[, options])
filePath字符串
返回 Promise<void> —— 当页面加载完成时,Promise 会被解决(参见 did-finish-load),如果页面加载失败则会被拒绝(参见 did-fail-load)。
🌐 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).
在窗口中加载给定的文件,filePath 应该是相对于应用根目录的 HTML 文件路径。例如,一个应用结构如下:
🌐 Loads the given file in the window, filePath should be a path to
an HTML file relative to the root of your application. For instance
an app structure like this:
| root
| - package.json
| - src
| - main.js
| - index.html
需要这样的代码
🌐 Would require code like this
const win = new BrowserWindow()
win.loadFile('src/index.html')
contents.downloadURL(url[, options])
url字符串
在不进行导航的情况下,启动对 url 资源的下载。session 的 will-download 事件将被触发。
🌐 Initiates a download of the resource at url without navigating. The
will-download event of session will be triggered.
contents.getURL()
返回 string - 当前网页的 URL。
🌐 Returns string - The URL of the current web page.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com').then(() => {
const currentURL = win.webContents.getURL()
console.log(currentURL)
})
contents.getTitle()
返回 string - 当前网页的标题。
🌐 Returns string - The title of the current web page.
contents.isDestroyed()
返回 boolean - 网页是否已被销毁。
🌐 Returns boolean - Whether the web page is destroyed.
contents.close([opts])
opts对象(可选)waitForBeforeUnload布尔值 - 如果为 true,在关闭页面之前触发beforeunload事件。如果页面阻止卸载,WebContents 将不会被关闭。如果页面请求阻止卸载,将触发will-prevent-unload事件。
关闭页面,就好像网页内容调用了 window.close()。
🌐 Closes the page, as if the web content had called window.close().
如果页面成功关闭(即页面未阻止卸载,或者 waitForBeforeUnload 为 false 或未指定),WebContents 将被销毁且无法再使用。将会触发 destroyed 事件。
🌐 If the page is successfully closed (i.e. the unload is not prevented by the
page, or waitForBeforeUnload is false or unspecified), the WebContents will
be destroyed and no longer usable. The destroyed event
will be emitted.
contents.focus()
聚焦网页。
🌐 Focuses the web page.
contents.isFocused()
返回 boolean - 网页是否处于焦点状态。
🌐 Returns boolean - Whether the web page is focused.
contents.isLoading()
返回 boolean - 网页是否仍在加载资源。
🌐 Returns boolean - Whether web page is still loading resources.
contents.isLoadingMainFrame()
返回 boolean - 指示主框架(而不仅仅是其中的 iframe 或子框架)是否仍在加载。
🌐 Returns boolean - Whether the main frame (and not just iframes or frames within it) is
still loading.
contents.isWaitingForResponse()
返回 boolean - 网页是否正在等待页面主资源的首次响应。
🌐 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() 已弃用
🌐 contents.canGoBack() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
返回 boolean - 浏览器是否可以返回到前一个网页。
🌐 Returns boolean - Whether the browser can go back to previous web page.
已弃用: 应使用新的 contents.navigationHistory.canGoBack API。
contents.canGoForward() 已弃用
🌐 contents.canGoForward() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
返回 boolean - 浏览器是否可以前进到下一个网页。
🌐 Returns boolean - Whether the browser can go forward to next web page.
已弃用: 应使用新的 contents.navigationHistory.canGoForward API。
contents.canGoToOffset(offset) 已弃用
🌐 contents.canGoToOffset(offset) Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
offset整数
返回 boolean - 网页是否可以跳转到 offset。
🌐 Returns boolean - Whether the web page can go to offset.
已弃用: 应使用新的 contents.navigationHistory.canGoToOffset API。
contents.clearHistory() 已弃用
🌐 contents.clearHistory() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
清除导航历史记录。
🌐 Clears the navigation history.
已弃用: 应使用新的 contents.navigationHistory.clear API。
contents.goBack() 已弃用
🌐 contents.goBack() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
使浏览器返回网页。
🌐 Makes the browser go back a web page.
已弃用: 应使用新的 contents.navigationHistory.goBack API。
contents.goForward() 已弃用
🌐 contents.goForward() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
使浏览器前进一个网页。
🌐 Makes the browser go forward a web page.
已弃用: 应使用新的 contents.navigationHistory.goForward API。
contents.goToIndex(index) 已弃用
🌐 contents.goToIndex(index) Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
index整数
将浏览器导航到指定的绝对网页索引。
🌐 Navigates browser to the specified absolute web page index.
已弃用: 应使用新的 contents.navigationHistory.goToIndex API。
contents.goToOffset(offset) 已弃用
🌐 contents.goToOffset(offset) Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
offset整数
导航到“当前条目”的指定偏移位置。
🌐 Navigates to the specified offset from the "current entry".
已弃用: 应使用新的 contents.navigationHistory.goToOffset API。
contents.isCrashed()
返回 boolean - 渲染器进程是否已崩溃。
🌐 Returns boolean - Whether the renderer process has crashed.
contents.forcefullyCrashRenderer()
强制终止当前托管此 webContents 的渲染进程。这将导致 render-process-gone 事件与 reason=killed || reason=crashed 一起被触发。请注意,一些 webContents 共享渲染进程,因此调用此方法也可能导致其他 webContents 的主机进程崩溃。
🌐 Forcefully terminates the renderer process that is currently hosting this
webContents. This will cause the render-process-gone event to be emitted
with the 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.
在调用此方法后立即调用 reload() 将强制在新进程中重新加载。当此进程不稳定或无法使用时,应使用此方法,例如为了从 unresponsive 事件中恢复。
🌐 Calling reload() immediately after calling this
method will force the reload to occur in a new process. This should be used
when this process is unstable or unusable, for instance in order to recover
from the unresponsive event.
const win = new BrowserWindow()
win.webContents.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) {
win.webContents.forcefullyCrashRenderer()
win.webContents.reload()
}
})
contents.setUserAgent(userAgent)
userAgent字符串
覆盖此网页的用户代理。
🌐 Overrides the user agent for this web page.
contents.getUserAgent()
返回 string - 此网页的用户代理。
🌐 Returns string - The user agent for this web page.
contents.insertCSS(css[, options])
css字符串
返回 Promise<string> - 一个 Promise,解析时会返回插入的 CSS 的键,该键可以用来通过 contents.removeInsertedCSS(key) 删除 CSS。
🌐 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).
将 CSS 注入当前网页,并返回插入样式表的唯一键。
🌐 Injects CSS into the current web page and returns a unique key for the inserted stylesheet.
const win = new BrowserWindow()
win.webContents.on('did-finish-load', () => {
win.webContents.insertCSS('html, body { background-color: #f00; }')
})
contents.removeInsertedCSS(key)
key字符串
返回 Promise<void> - 如果移除成功,则解析。
🌐 Returns Promise<void> - Resolves if the removal was successful.
从当前网页中移除已插入的 CSS。样式表通过其键来识别,该键由 contents.insertCSS(css) 返回。
🌐 Removes the inserted CSS from the current web page. The stylesheet is identified
by its key, which is returned from contents.insertCSS(css).
const win = new BrowserWindow()
win.webContents.on('did-finish-load', async () => {
const key = await win.webContents.insertCSS('html, body { background-color: #f00; }')
win.webContents.removeInsertedCSS(key)
})
contents.executeJavaScript(code[, userGesture])
code字符串userGesture布尔值(可选)- 默认值为false。
返回 Promise<any> - 一个 Promise,如果代码执行成功则会以执行结果解析,如果代码结果是被拒绝的 Promise,则会被拒绝。
🌐 Returns Promise<any> - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
在页面中评估 code。
🌐 Evaluates code in page.
在浏览器窗口中,一些 HTML API(如 requestFullScreen)只能通过用户的手势来调用。将 userGesture 设置为 true 将移除此限制。
🌐 In the browser window some HTML APIs like requestFullScreen can only be
invoked by a gesture from the user. Setting userGesture to true will remove
this limitation.
代码执行将暂停,直到网页停止加载。
🌐 Code execution will be suspended until web page stop loading.
const win = new BrowserWindow()
win.webContents.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整数 - 用于运行 JavaScript 的世界 ID,0是默认世界,999是 ElectroncontextIsolation功能使用的世界。你可以在此处提供任意整数。scripts网页来源[]userGesture布尔值(可选)- 默认值为false。
返回 Promise<any> - 一个 Promise,如果代码执行成功则会以执行结果解析,如果代码结果是被拒绝的 Promise,则会被拒绝。
🌐 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.
类似于 executeJavaScript,但在独立的环境中评估 scripts。
🌐 Works like executeJavaScript but evaluates scripts in an isolated context.
contents.setIgnoreMenuShortcuts(ignore)
ignore布尔值
当此 Web 内容获得焦点时,忽略应用菜单快捷方式。
🌐 Ignore application menu shortcuts while this web contents is focused.
contents.setWindowOpenHandler(handler)
-
handlerFunction<WindowOpenHandlerResponse>details对象url字符串 - 传递给window.open()的 URL 的 已解析 版本。例如,用window.open('foo')打开一个窗口将得到类似https://the-origin/the/current/path/foo的结果。frameName字符串 - 在window.open()中提供的窗口名称features字符串 - 以逗号分隔的窗口功能列表,提供给window.open()。disposition字符串 - 可以是default、foreground-tab、background-tab、new-window或other。referrer引用来源 - 将传递给新窗口的引用来源。是否发送Referer头取决于引用来源策略,可能会发送,也可能不会发送。postBodyPostBody(可选)- 将要发送到新窗口的帖子数据,以及将要设置的相应头信息。如果不发送任何帖子数据,则其值为null。仅在窗口由设置了target=_blank的表单创建时定义。
返回
WindowOpenHandlerResponse- 当设置为{ action: 'deny' }时,会取消新窗口的创建。{ action: 'allow' }将允许新窗口被创建。返回未识别的值,例如 null、undefined,或没有被识别的 'action' 值的对象,会导致控制台错误,并产生与返回{action: 'deny'}相同的效果。
在渲染器请求新窗口时调用,例如通过 window.open()、带有 target="_blank" 的链接、按住 Shift 点击链接,或使用 <form target="_blank"> 提交表单。有关更多详情以及如何将其与 did-create-window 一起使用,请参见 window.open()。
🌐 Called before creating a window when 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">. See
window.open() for more details and how to use this in
conjunction with did-create-window.
一个示例,展示如何自定义新 BrowserWindow 创建的进程,使其改为附加到主窗口的 BrowserView:
🌐 An example showing how to customize the process of new BrowserWindow creation to be BrowserView attached to main window instead:
const { BrowserView, BrowserWindow } = require('electron')
const mainWindow = new BrowserWindow()
mainWindow.webContents.setWindowOpenHandler((details) => {
return {
action: 'allow',
createWindow: (options) => {
const browserView = new BrowserView(options)
mainWindow.addBrowserView(browserView)
browserView.setBounds({ x: 0, y: 0, width: 640, height: 480 })
return browserView.webContents
}
}
})
contents.setAudioMuted(muted)
muted布尔值
将当前网页的音频静音。
🌐 Mute the audio on the current web page.
contents.isAudioMuted()
返回 boolean - 此页面是否已被静音。
🌐 Returns boolean - Whether this page has been muted.
contents.isCurrentlyAudible()
返回 boolean - 音频当前是否正在播放。
🌐 Returns boolean - Whether audio is currently playing.
contents.setZoomFactor(factor)
factor双重 - 缩放因子;默认值为 1.0。
将缩放因子更改为指定的因子。缩放因子是缩放百分比除以100,因此300% = 3.0。
🌐 Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0.
该系数必须大于 0.0。
🌐 The factor must be greater than 0.0.
contents.getZoomFactor()
返回 number - 当前的缩放因子。
🌐 Returns number - the current zoom factor.
contents.setZoomLevel(level)
level数字 - 缩放级别。
将缩放级别更改为指定级别。原始大小为0,每增加或减少一个增量表示缩放为原始大小的120%或80%,默认限制分别为原始大小的300%和50%。其公式为 scale := 1.2 ^ 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. The formula for this is
scale := 1.2 ^ level.
Chromium级别的缩放策略是同源策略,这意味着特定域的缩放等级会在所有具有相同域的窗口实例之间传播。区分窗口的URL将使缩放在每个窗口上单独生效。
contents.getZoomLevel()
返回 number - 当前的缩放级别。
🌐 Returns number - the current zoom level.
contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevel号码maximumLevel号码
返回 Promise<void>
🌐 Returns Promise<void>
设置最大和最小捏合缩放级别。
🌐 Sets the maximum and minimum pinch-to-zoom level.
在 Electron 中,视觉缩放默认是禁用的。要重新启用它,请调用:
const win = new BrowserWindow()
win.webContents.setVisualZoomLevelLimits(1, 3)
contents.undo()
在网页中执行编辑命令 undo。
🌐 Executes the editing command undo in web page.
contents.redo()
在网页中执行编辑命令 redo。
🌐 Executes the editing command redo in web page.
contents.cut()
在网页中执行编辑命令 cut。
🌐 Executes the editing command cut in web page.
contents.copy()
在网页中执行编辑命令 copy。
🌐 Executes the editing command copy in web page.
contents.centerSelection()
将当前文本选择在网页中居中。
🌐 Centers the current text selection in web page.
contents.copyImageAt(x, y)
x整数y整数
将给定位置的图片复制到剪贴板。
🌐 Copy the image at the given position to the clipboard.
contents.paste()
在网页中执行编辑命令 paste。
🌐 Executes the editing command paste in web page.
contents.pasteAndMatchStyle()
在网页中执行编辑命令 pasteAndMatchStyle。
🌐 Executes the editing command pasteAndMatchStyle in web page.
contents.delete()
在网页中执行编辑命令 delete。
🌐 Executes the editing command delete in web page.
contents.selectAll()
在网页中执行编辑命令 selectAll。
🌐 Executes the editing command selectAll in web page.
contents.unselect()
在网页中执行编辑命令 unselect。
🌐 Executes the editing command unselect in web page.
contents.scrollToTop()
滚动到当前 webContents 的顶部。
🌐 Scrolls to the top of the current webContents.
contents.scrollToBottom()
滚动到当前 webContents 的底部。
🌐 Scrolls to the bottom of the current webContents.
contents.adjustSelection(options)
按给定的数量调整焦点框中当前文本选择的起始和结束位置。负数会将选择移动到文档的开头,正数会将选择移动到文档的末尾。
🌐 Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document.
示例:
🌐 Example:
const win = new BrowserWindow()
// Adjusts the beginning of the selection 1 letter forward,
// and the end of the selection 5 letters forward.
win.webContents.adjustSelection({ start: 1, end: 5 })
// Adjusts the beginning of the selection 2 letters forward,
// and the end of the selection 3 letters backward.
win.webContents.adjustSelection({ start: 2, end: -3 })
对于一次 win.webContents.adjustSelection({ start: 1, end: 5 }) 调用
🌐 For a call of win.webContents.adjustSelection({ start: 1, end: 5 })
前:
🌐 Before:
后:
🌐 After:
contents.replace(text)
text字符串
在网页中执行编辑命令 replace。
🌐 Executes the editing command replace in web page.
contents.replaceMisspelling(text)
text字符串
在网页中执行编辑命令 replaceMisspelling。
🌐 Executes the editing command replaceMisspelling in web page.
contents.insertText(text)
text字符串
返回 Promise<void>
🌐 Returns Promise<void>
将 text 插入到当前焦点元素。
🌐 Inserts text to the focused element.
contents.findInPage(text[, options])
text字符串 - 要搜索的内容,不能为空。
返回 Integer - 请求使用的请求ID。
🌐 Returns Integer - The request id used for the request.
启动一个请求以在网页中查找所有 text 的匹配项。请求的结果可以通过订阅 found-in-page 事件来获取。
🌐 Starts a request to find all matches for the text in the web page. The result of the request
can be obtained by subscribing to found-in-page event.
contents.stopFindInPage(action)
action字符串 - 指定在结束webContents.findInPage请求时要执行的操作。clearSelection- 清除选择。keepSelection- 将选择转换为正常选择。activateSelection- 聚焦并单击选择节点。
阻止对 webContents 发出的任何 findInPage 请求,使用提供的 action。
🌐 Stops any findInPage request for the webContents with the provided action.
const win = new BrowserWindow()
win.webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) win.webContents.stopFindInPage('clearSelection')
})
const requestId = win.webContents.findInPage('api')
console.log(requestId)
contents.capturePage([rect, opts])
rect矩形(可选)- 要捕获的页面区域。opts对象(可选)stayHidden布尔值(可选)- 保持页面隐藏而不是可见。默认值为false。stayAwake布尔值(可选)- 保持系统唤醒而不是让它进入睡眠模式。默认值为false。
返回 Promise<NativeImage> - 解析为一个 NativeImage
🌐 Returns Promise<NativeImage> - Resolves with a NativeImage
在 rect 中捕获页面的快照。省略 rect 将捕获整个可见页面。 当浏览器窗口被隐藏且捕获器数量非零时,页面被视为可见。 如果你希望页面保持隐藏,应确保将 stayHidden 设置为 true。
🌐 Captures a snapshot of the page within rect. Omitting rect will capture the whole visible page.
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.
contents.isBeingCaptured()
返回 boolean - 判断此页面是否正在被捕获。当捕获器数量大于 0 时返回 true。
🌐 Returns boolean - Whether this page is being captured. It returns true when the capturer count
is greater than 0.
contents.getPrintersAsync()
获取系统打印机列表。
🌐 Get the system printer list.
返回 Promise<PrinterInfo[]> - 解析为 PrinterInfo[]
🌐 Returns Promise<PrinterInfo[]> - Resolves with a PrinterInfo[]
contents.print([options], [callback])
callback功能(可选)success布尔值 - 表示打印调用是否成功。failureReason字符串 - 如果打印失败,将回调错误描述。
当传入自定义 pageSize 时,Chromium 会尝试验证 width_microns 和 height_microns 的平台特定最小值。宽度和高度都必须至少为 353 微米,但在某些操作系统上可能会更大。
🌐 When a custom pageSize is passed, Chromium attempts to validate platform specific minimum values for width_microns and height_microns. Width and height must both be minimum 353 microns but may be higher on some operating systems.
打印窗口的网页。当 silent 设置为 true 时,如果 deviceName 为空,Electron 将选择系统默认打印机并使用打印的默认设置。
🌐 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.
打印失败的一些可能原因包括:
🌐 Some possible failureReasons for print failure include:
- 打印机设置无效
- 打印作业已取消
- 打印作业失败
使用 page-break-before: always; CSS 样式强制换页打印。
🌐 Use page-break-before: always; CSS style to force to print to a new page.
用法示例:
🌐 Example usage:
const win = new BrowserWindow()
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)
返回 Promise<Buffer> - 解析为生成的 PDF 数据。
🌐 Returns Promise<Buffer> - Resolves with the generated PDF data.
将窗口的网页打印为 PDF。
🌐 Prints the window's web page as PDF.
如果网页中使用了 @page CSS 规则,landscape 将被忽略。
🌐 The landscape will be ignored if @page CSS at-rule is used in the web page.
webContents.printToPDF 的一个例子:
🌐 An example of webContents.printToPDF:
const { app, BrowserWindow } = require('electron')
const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')
app.whenReady().then(() => {
const win = new BrowserWindow()
win.loadURL('https://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)
})
})
})
有关更多信息,请参见 Page.printToPdf。
🌐 See Page.printToPdf for more information.
contents.addWorkSpace(path)
path字符串
将指定路径添加到 DevTools 工作区。必须在创建 DevTools 之后使用:
🌐 Adds the specified path to DevTools workspace. Must be used after DevTools creation:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname)
})
contents.removeWorkSpace(path)
path字符串
从 DevTools 工作区中删除指定的路径。
🌐 Removes the specified path from DevTools workspace.
contents.setDevToolsWebContents(devToolsWebContents)
devToolsWebContents网页内容
使用 devToolsWebContents 作为目标 WebContents 来显示开发者工具。
🌐 Uses the devToolsWebContents as the target WebContents to show DevTools.
devToolsWebContents 不能进行任何导航,并且在调用之后不应被用于其他目的。
🌐 The devToolsWebContents must not have done any navigation, and it should not
be used for other purposes after the call.
默认情况下,Electron 通过创建一个带有原生视图的内部 WebContents 来管理 DevTools,开发者对其控制非常有限。通过 setDevToolsWebContents 方法,开发者可以使用任何 WebContents 来显示 DevTools,例如 BrowserWindow 或 WebContentsView。
🌐 By default, Electron manages the DevTools by creating an internal WebContents
with native view, which developers have very limited control of. With the
setDevToolsWebContents method, developers can use any WebContents to show
the DevTools in it, such as BrowserWindow or WebContentsView.
请注意,关闭开发者工具并不会销毁 devToolsWebContents,销毁 devToolsWebContents 是调用者的责任,需要手动完成。
🌐 Note that closing the DevTools does not destroy the devToolsWebContents, it
is the caller's responsibility to destroy devToolsWebContents manually.
在 BrowserWindow 中显示开发者工具的示例:
🌐 An example of showing DevTools in a 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.
当 contents 是 <webview> 标签时,mode 默认会是 detach,显式传入一个空的 mode 可以强制使用上次使用的停靠状态。
🌐 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.
在 Windows 上,如果启用了 Windows 控制覆盖,DevTools 将会以 mode: 'detach' 打开。
🌐 On Windows, if Windows Control Overlay is enabled, DevTools will be opened with mode: 'detach'.
contents.closeDevTools()
关闭开发者工具视图。
🌐 Closes the DevTools view.
contents.isDevToolsOpened()
返回 boolean - DevTools 视图是否已打开。
🌐 Returns boolean - Whether the DevTools view is opened.
contents.isDevToolsFocused()
返回 boolean - DevTools 视图是否处于焦点状态。
🌐 Returns boolean - Whether the DevTools view is focused .
contents.getDevToolsTitle()
返回 string - 当前 DevTools 窗口的标题。只有在 DevTools 以 undocked 或 detach 模式打开时,这才会可见。
🌐 Returns string - the current title of the DevTools window. This will only be visible
if DevTools is opened in undocked or detach mode.
contents.setDevToolsTitle(title)
title字符串
将开发者工具窗口的标题更改为 title。仅当开发者工具以 undocked 或 detach 模式打开时才可见。
🌐 Changes the title of the DevTools window to title. This will only be visible if DevTools is
opened in undocked or detach mode.
contents.toggleDevTools()
切换开发者工具。
🌐 Toggles the developer tools.
contents.inspectElement(x, y)
x整数y整数
开始检查位置为(x,y)的元素。
🌐 Starts inspecting element at position (x, y).
contents.inspectSharedWorker()
打开共享工作线程上下文的开发者工具。
🌐 Opens the developer tools for the shared worker context.
contents.inspectSharedWorkerById(workerId)
workerId字符串
根据共享 worker 的 ID 检查共享 worker。
🌐 Inspects the shared worker based on its ID.
contents.getAllSharedWorkers()
返回 SharedWorkerInfo[] - 有关所有共享工作者的信息。
🌐 Returns SharedWorkerInfo[] - Information about all Shared Workers.
contents.inspectServiceWorker()
打开服务工作线程上下文的开发者工具。
🌐 Opens the developer tools for the service worker context.
contents.send(channel, ...args)
channel字符串...argsany[]
通过 channel 向渲染进程发送异步消息,并附带参数。参数将使用 结构化克隆算法 序列化,就像 postMessage 一样,因此原型链将不会被包含。发送函数、Promise、Symbol、WeakMap 或 WeakSet 将会抛出异常。
🌐 Send an asynchronous message to the renderer process via channel, along with
arguments. Arguments will be serialized with the Structured Clone Algorithm,
just like postMessage, so prototype chains will not be
included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will
throw an exception.
发送非标准的 JavaScript 类型,例如 DOM 对象或特殊的 Electron 对象,会抛出异常。
🌐 Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception.
欲了解更多内容,请参阅 Electron 的 IPC 指南。
🌐 For additional reading, refer to Electron's IPC guide.
contents.sendToFrame(frameId, channel, ...args)
frameId整数 | [数字, 数字] - 要发送的帧的 ID,或者如果帧在与主帧不同的进程中,则为[processId, frameId]的一对值。channel字符串...argsany[]
通过 channel 向渲染进程中的特定框架发送异步消息,并携带参数。参数将使用 结构化克隆算法 序列化,就像 postMessage 一样,因此原型链不会被包含。发送函数、Promise、符号、WeakMap 或 WeakSet 将会抛出异常。
🌐 Send an asynchronous message to a specific frame in a renderer process via
channel, along with arguments. Arguments will be serialized with the
Structured Clone Algorithm, just like postMessage, so prototype
chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or
WeakSets will throw an exception.
注意: 发送非标准的 JavaScript 类型,例如 DOM 对象或特殊的 Electron 对象,将会抛出异常。
渲染进程可以通过使用 ipcRenderer 模块监听 channel 来处理消息。
🌐 The renderer process can handle the message by listening to channel with the
ipcRenderer module.
如果你想获取给定渲染器上下文的 frameId,你应该使用 webFrame.routingId 值。例如。
🌐 If you want to get the frameId of a given renderer context you should use
the webFrame.routingId value. E.g.
// In a renderer process
console.log('My frameId is:', require('electron').webFrame.routingId)
你也可以在主进程中从所有传入的 IPC 消息中读取 frameId。
🌐 You can also read frameId from all incoming IPC messages in the main process.
// In the main process
ipcMain.on('ping', (event) => {
console.info('Message came from frameId:', event.frameId)
})
contents.postMessage(channel, message, [transfer])
channel字符串message任何transferMessagePortMain[](可选)
向渲染进程发送消息,可选择转移零个或多个 MessagePortMain 对象的所有权。
🌐 Send a message to the renderer process, optionally transferring ownership of
zero or more MessagePortMain objects.
传输的 MessagePortMain 对象可以通过访问触发事件的 ports 属性在渲染进程中使用。当它们到达渲染器时,它们将是原生 DOM MessagePort 对象。
🌐 The transferred MessagePortMain objects will be available in the renderer
process by accessing the ports property of the emitted event. When they
arrive in the renderer, they will be native DOM MessagePort objects.
例如:
🌐 For example:
// Main process
const win = new BrowserWindow()
const { port1, port2 } = new MessageChannelMain()
win.webContents.postMessage('port', { message: 'hello' }, [port1])
// Renderer process
ipcRenderer.on('port', (e, msg) => {
const [port] = e.ports
// ...
})
contents.enableDeviceEmulation(parameters)
parameters对象screenPosition字符串 - 指定要模拟的屏幕类型(默认值:desktop):desktop- 桌面屏幕类型。mobile- 移动屏幕类型。
screenSize尺寸 - 设置模拟的屏幕尺寸(screenPosition == mobile)。viewPosition点 - 在屏幕上定位视图 (screenPosition == 移动设备) (默认值:{ x: 0, y: 0 })。deviceScaleFactor整数 - 设置设备缩放因子(如果为零,则默认为原始设备缩放因子)(默认值:0)。viewSize大小 - 设置模拟视图尺寸(为空表示不覆盖)scale浮点数 - 在可用空间内模拟视图的缩放比例(不适用于适应视图模式)(默认值:1)。
使用给定参数启用设备模拟。
🌐 Enable device emulation with the given parameters.
contents.disableDeviceEmulation()
禁用由 webContents.enableDeviceEmulation 启用的设备模拟。
🌐 Disable device emulation enabled by webContents.enableDeviceEmulation.
contents.sendInputEvent(inputEvent)
将输入 event 发送到页面。
🌐 Sends an input event to the page.
包含内容的BrowserWindow需要被聚焦,sendInputEvent()才能工作。
contents.beginFrameSubscription([onlyDirty ,]callback)
开始订阅显示事件和捕获的帧,当有显示事件时,将使用 callback(image, dirtyRect) 调用 callback。
🌐 Begin subscribing for presentation events and captured frames, the callback
will be called with callback(image, dirtyRect) when there is a presentation
event.
image 是一个 NativeImage 的实例,用于存储捕获的帧。
🌐 The image is an instance of NativeImage that stores the
captured frame.
dirtyRect 是一个包含 x, y, width, height 属性的对象,用于描述页面的哪个部分被重绘。如果 onlyDirty 设置为 true,image 将只包含重绘的区域。onlyDirty 默认为 false。
🌐 The dirtyRect is an object with x, y, width, height properties that
describes which part of the page was repainted. If onlyDirty is set to
true, image will only contain the repainted area. onlyDirty defaults to
false.
contents.endFrameSubscription()
结束对框架渲染事件的订阅。
🌐 End subscribing for frame presentation events.
contents.startDrag(item)
item对象file字符串 - 被拖动文件的路径。filesstring[](可选)- 被拖动文件的路径。(files将覆盖file字段)iconNativeImage | 字符串 - 图片在 macOS 上不能为空。
将 item 设置为当前拖放操作的拖动项目,file 是要拖动的文件的绝对路径,icon 是拖动时光标下显示的图片。
🌐 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.
contents.savePage(fullPath, saveType)
fullPath字符串 - 文件的绝对路径。saveType字符串 - 指定保存类型。HTMLOnly- 仅保存页面的 HTML。HTMLComplete- 保存完整的 html 页面。MHTML- 将完整的 html 页面保存为 MHTML。
返回 Promise<void> - 如果页面已保存,则解析。
🌐 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()
返回 boolean - 表示是否启用了_屏幕外渲染_。
🌐 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()
返回 boolean - 如果启用了 离屏渲染,则返回它当前是否正在绘制。
🌐 Returns boolean - If offscreen rendering is enabled returns whether it is currently painting.
contents.setFrameRate(fps)
fps整数
如果启用了 离屏渲染,则将帧率设置为指定的数值。当 webPreferences.offscreen.useSharedTexture 为 false 时,只接受 1 到 240 之间的值。
🌐 If offscreen rendering is enabled sets the frame rate to the specified number.
When webPreferences.offscreen.useSharedTexture is false only values between 1 and 240 are accepted.
contents.getFrameRate()
返回 Integer - 如果启用了 离屏渲染,则返回当前帧率。
🌐 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.
如果启用了 离屏渲染,将使帧无效并通过 'paint' 事件生成一个新帧。
🌐 If offscreen rendering is enabled invalidates the frame and generates a new
one through the 'paint' event.
contents.getWebRTCIPHandlingPolicy()
返回 string - 返回 WebRTC IP 处理策略。
🌐 Returns string - Returns the WebRTC IP Handling Policy.
contents.setWebRTCIPHandlingPolicy(policy)
policy字符串 - 指定 WebRTC IP 处理策略。default- 暴露用户的公共和本地IP。这是默认行为。当使用此策略时,WebRTC有权枚举所有接口并绑定它们以发现公共接口。default_public_interface_only- 暴露用户的公共IP,但不会暴露用户的本地IP。当使用此策略时,WebRTC应仅使用HTTP使用的默认路由。这不会暴露任何本地地址。default_public_and_private_interfaces- 暴露用户的公共和本地 IP。当使用此策略时,WebRTC 应仅使用 HTTP 使用的默认路由。这也会暴露相关的默认私有地址。默认路由是在多宿主端点上由操作系统选择的路由。disable_non_proxied_udp- 不会暴露公共或本地IP。当使用此策略时,WebRTC 应仅通过 TCP 与对等方或服务器通信,除非代理服务器支持 UDP。
设置 WebRTC IP 处理策略可以让你控制通过 WebRTC 暴露哪些 IP。有关更多详情,请参阅 BrowserLeaks。
🌐 Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See BrowserLeaks for more details.
contents.getWebRTCUDPPortRange()
返回 Object:
🌐 Returns Object:
min整数 - WebRTC 应使用的最小 UDP 端口号。max整数 - WebRTC 应使用的最大 UDP 端口号。
默认情况下,该值为 { min: 0, max: 0 },这不会对 UDP 端口范围施加任何限制。
🌐 By default this value is { min: 0, max: 0 } , which would apply no restriction on the udp port range.
contents.setWebRTCUDPPortRange(udpPortRange)
udpPortRange对象min整数 - WebRTC 应使用的最小 UDP 端口号。max整数 - WebRTC 应使用的最大 UDP 端口号。
设置 WebRTC UDP 端口范围可以让你限制 WebRTC 使用的 UDP 端口范围。默认情况下,端口范围是不受限制的。
🌐 Setting the WebRTC UDP Port Range allows you to restrict the udp port range used by WebRTC. By default the port range is unrestricted.
要重置为无限制端口范围,应将此值设置为 { min: 0, max: 0 }。
contents.getMediaSourceId(requestWebContents)
requestWebContentsWebContents - 将注册该 ID 的网页内容。
返回 string - WebContents 流的标识符。此标识符可以用于与 navigator.mediaDevices.getUserMedia 配合使用,使用的 chromeMediaSource 为 tab。
该标识符仅限于注册它的 web 内容,并且仅在 10 秒内有效。
🌐 Returns string - The identifier of a WebContents stream. This identifier can be used
with navigator.mediaDevices.getUserMedia using a chromeMediaSource of tab.
The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds.
contents.getOSProcessId()
返回 Integer - 关联渲染器进程的操作系统 pid。
🌐 Returns Integer - The operating system pid of the associated renderer
process.
contents.getProcessId()
返回 Integer - 关联渲染器的 Chromium 内部 pid。可以与帧特定导航事件传递的 frameProcessId 进行比较(例如 did-frame-navigate)
🌐 Returns Integer - The Chromium internal pid of the associated renderer. Can
be compared to the frameProcessId passed by frame specific navigation events
(e.g. did-frame-navigate)
contents.takeHeapSnapshot(filePath)
filePath字符串 - 输出文件的路径。
返回 Promise<void> - 指示快照是否已成功创建。
🌐 Returns Promise<void> - Indicates whether the snapshot has been created successfully.
获取 V8 堆快照并将其保存到 filePath。
🌐 Takes a V8 heap snapshot and saves it to filePath.
contents.getBackgroundThrottling()
返回 boolean——用于指示当页面被置于后台时,此 WebContents 是否会限制动画和定时器的运行。这也会影响页面可见性 API。
🌐 Returns boolean - whether or not this WebContents will throttle animations and timers
when the page becomes backgrounded. This also affects the Page Visibility API.
contents.setBackgroundThrottling(allowed)
History
allowed布尔值
控制当页面进入后台时,此 WebContents 是否会限制动画和定时器。这也会影响页面可见性 API。
🌐 Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API.
contents.getType()
返回 string - webContent 的类型。可以是 backgroundPage、window、browserView、remote、webview 或 offscreen。
🌐 Returns string - the type of the webContent. Can be backgroundPage, window, browserView, remote, webview or offscreen.
contents.setImageAnimationPolicy(policy)
policy字符串 - 可以是animate、animateOnce或noAnimation。
为此 webContents 设置图片动画策略。该策略仅影响新图片,当前正在动画的现有图片不受影响。这是 Chromium 已知的限制,你可以使用 img.src = img.src 强制重新计算图片动画,这不会产生网络流量,但会更新动画策略。
🌐 Sets the image animation policy for this 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 中的 动画策略 辅助功能。
🌐 This corresponds to the animationPolicy accessibility feature in Chromium.
实例属性
🌐 Instance Properties
contents.ipc 只读
🌐 contents.ipc Readonly
一个仅限于从此 WebContents 发送的 IPC 消息的 IpcMain 范围。
🌐 An IpcMain scoped to just IPC messages sent from this
WebContents.
使用 ipcRenderer.send、ipcRenderer.sendSync 或 ipcRenderer.postMessage 发送的 IPC 消息将按以下顺序传递:
🌐 IPC messages sent with ipcRenderer.send, ipcRenderer.sendSync or
ipcRenderer.postMessage will be delivered in the following order:
contents.on('ipc-message')contents.mainFrame.on(channel)contents.ipc.on(channel)ipcMain.on(channel)
使用 invoke 注册的处理程序将按以下顺序进行检查。第一个被定义的处理程序将被调用,其余的将被忽略。
🌐 Handlers registered with invoke will be checked in the following order. The
first one that is defined will be called, the rest will be ignored.
contents.mainFrame.handle(channel)contents.handle(channel)ipcMain.handle(channel)
在 WebContents 上注册的处理程序或事件监听器将接收来自任何框架(包括子框架)的 IPC 消息。在大多数情况下,只有主框架可以发送 IPC 消息。但是,如果启用了 nodeIntegrationInSubFrames 选项,子框架也可以发送 IPC 消息。在这种情况下,处理程序应检查 IPC 事件的 senderFrame 属性,以确保消息来自预期的框架。或者,可以使用 WebFrameMain.ipc 接口直接在相应的框架上注册处理程序。
🌐 A handler or event listener registered on the WebContents will receive IPC
messages sent from any frame, including child frames. In most cases, only the
main frame can send IPC messages. However, if the nodeIntegrationInSubFrames
option is enabled, it is possible for child frames to send IPC messages also.
In that case, handlers should check the senderFrame property of the IPC event
to ensure that the message is coming from the expected frame. Alternatively,
register handlers on the appropriate frame directly using the
WebFrameMain.ipc interface.
contents.audioMuted
一个 boolean 属性,用于确定此页面是否被静音。
🌐 A boolean property that determines whether this page is muted.
contents.userAgent
string 属性,用于确定此网页的用户代理。
🌐 A string property that determines the user agent for this web page.
contents.zoomLevel
一个 number 属性,用于确定此网页内容的缩放级别。
🌐 A number property that determines the zoom level for this web contents.
原始尺寸为0,每向上或向下增加一次表示缩放比原始大小放大或缩小20%,其默认限制分别为原始尺寸的300%和50%。计算公式为 scale := 1.2 ^ 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. The formula for this is scale := 1.2 ^ level.
contents.zoomFactor
number 属性,用于确定此网页内容的缩放比例。
🌐 A number property that determines the zoom factor for this web contents.
缩放系数是缩放百分比除以 100,因此 300% = 3.0。
🌐 The zoom factor is the zoom percent divided by 100, so 300% = 3.0.
contents.frameRate
Integer 属性用于将网页内容的帧率设置为指定的数值。仅接受 1 到 240 之间的值。
🌐 An Integer property that sets the frame rate of the web contents to the specified number.
Only values between 1 and 240 are accepted.
仅在启用_离屏渲染_时适用。
🌐 Only applicable if offscreen rendering is enabled.
contents.id 只读
🌐 contents.id Readonly
一个 Integer,表示这个 WebContents 的唯一 ID。每个 ID 在整个 Electron 应用的所有 WebContents 实例中都是唯一的。
🌐 A Integer representing the unique ID of this WebContents. Each ID is unique among all WebContents instances of the entire Electron application.
contents.session 只读
🌐 contents.session Readonly
该 webContents 使用的 Session。
🌐 A Session used by this webContents.
contents.navigationHistory 只读
🌐 contents.navigationHistory Readonly
该 webContents 使用的 NavigationHistory。
🌐 A NavigationHistory used by this webContents.
contents.hostWebContents 只读
🌐 contents.hostWebContents Readonly
一个 WebContents | null 属性,表示可能拥有此 WebContents 的 WebContents 实例。
🌐 A WebContents | null property that represents a WebContents
instance that might own this WebContents.
contents.devToolsWebContents 只读
🌐 contents.devToolsWebContents Readonly
一个 WebContents | null 属性,表示与给定 WebContents 关联的 DevTools WebContents。
🌐 A WebContents | null property that represents the DevTools WebContents associated with a given WebContents.
用户绝不应该存储此对象,因为当开发者工具关闭时,它可能会变为 null。
contents.debugger 只读
🌐 contents.debugger Readonly
该 webContents 的 Debugger 实例。
🌐 A Debugger instance for this webContents.
contents.backgroundThrottling
History
boolean 属性用于确定当页面进入后台时,该 WebContents 是否会限制动画和计时器的执行。这也会影响页面可见性 API。
🌐 A boolean property that determines whether or not this WebContents will throttle animations and timers
when the page becomes backgrounded. This also affects the Page Visibility API.
contents.mainFrame 只读
🌐 contents.mainFrame Readonly
一个 WebFrameMain 属性,表示页面框架层次结构的顶层框架。
🌐 A WebFrameMain property that represents the top frame of the page's frame hierarchy.
contents.opener 只读
🌐 contents.opener Readonly
[WebFrameMain | null](web-frame-main.md) 属性,表示打开此 WebContents 的框架,无论是通过 open() 方法,还是通过带有 target 属性的链接导航。
🌐 A WebFrameMain | null property that represents the frame that opened this WebContents, either
with open(), or by navigating a link with a target attribute.
contents.focusedFrame 只读
🌐 contents.focusedFrame Readonly
一个 WebFrameMain | null 属性,表示此 WebContents 中当前获得焦点的框架。可以是顶层框架、内部的 <iframe>,或者如果没有任何元素获得焦点,则为 null。
🌐 A WebFrameMain | null property that represents the currently focused frame in this WebContents.
Can be the top frame, an inner <iframe>, or null if nothing is focused.