webContents
渲染和控制网页。
进程:主进程
webContents
是一个 EventEmitter。它负责渲染和控制一个网页,并且是 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)
导航事件
有几个事件可用于监视 webContents
中发生的导航。
文档导航
当 webContents
导航到另一个页面时(而不是 页面内导航),将触发以下事件。
did-start-navigation
will-frame-navigate
will-navigate
(仅当主框架导航时触发)will-redirect
(仅当导航期间发生重定向时触发)did-redirect-navigation
(仅当导航期间发生重定向时触发)did-frame-navigate
did-navigate
(仅当主框架导航时触发)
如果对任何可取消的事件调用了 event.preventDefault()
,则后续事件将不会触发。
页面内导航
页面内导航不会导致页面重新加载,而是导航到当前页面内的某个位置。这些事件不可取消。对于页面内导航,将按以下顺序触发事件:
框架导航
will-navigate
和 did-navigate
事件仅在 mainFrame 导航时触发。如果你想同时监视 <iframe>
中的导航,请使用 will-frame-navigate
和 did-frame-navigate
事件。
方法
这些方法可以从 webContents
模块访问
const { webContents } = require('electron')
console.log(webContents)
webContents.getAllWebContents()
返回 WebContents[]
- 所有 WebContents
实例的数组。这将包含所有窗口、webview、打开的 devtools 以及 devtools 扩展后台页面的 web contents。
webContents.getFocusedWebContents()
返回 WebContents | null
- 此应用程序中获得焦点的 web contents,否则返回 null
。
webContents.fromId(id)
id
Integer
返回 WebContents | undefined
- 具有给定 ID 的 WebContents 实例,如果不存在与给定 ID 关联的 WebContents,则返回 undefined
。
webContents.fromFrame(frame)
frame
WebFrameMain
返回 WebContents | undefined
- 具有给定 WebFrameMain 的 WebContents 实例,如果不存在与给定 WebFrameMain 关联的 WebContents,则返回 undefined
。
webContents.fromDevToolsTargetId(targetId)
targetId
string - 与 WebContents 实例关联的 Chrome DevTools Protocol TargetID。
返回 WebContents | undefined
- 具有给定 TargetID 的 WebContents 实例,如果不存在与给定 TargetID 关联的 WebContents,则返回 undefined
。
在与 Chrome DevTools Protocol 通信时,根据分配的 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 wc.fromDevToolsTargetId(targetId)
}
Class: WebContents
渲染并控制 BrowserWindow 实例的内容。
进程:主进程
此类未从 'electron'
模块导出。它仅作为 Electron API 中其他方法的返回值可用。
实例事件
Event: 'did-finish-load'
当导航完成时发出,即标签页的加载指示器停止旋转,并且 dispatch 了 onload
事件。
Event: 'did-fail-load'
返回
event
EventerrorCode
IntegererrorDescription
stringvalidatedURL
stringisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
此事件类似于 did-finish-load
,但在加载失败时发出。错误代码及其含义的完整列表可在此处 找到。
Event: 'did-fail-provisional-load'
返回
event
EventerrorCode
IntegererrorDescription
stringvalidatedURL
stringisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
此事件类似于 did-fail-load
,但在加载被取消时发出(例如,调用了 window.stop()
)。
Event: 'did-frame-finish-load'
返回
event
EventisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
当一个框架完成导航时发出。
Event: 'did-start-loading'
对应于标签页加载指示器开始旋转的时间点。
Event: 'did-stop-loading'
对应于标签页加载指示器停止旋转的时间点。
事件: 'dom-ready'
当顶级框架中的文档加载完成时发出。
事件: 'page-title-updated'
返回
event
Eventtitle
stringexplicitSet
boolean
页面标题在导航期间被设置时触发。当标题由文件 URL 合成时,explicitSet
为 false。
Event: 'page-favicon-updated'
返回
event
Eventfavicons
string[] - 包含 favicon URL 的数组。
当页面接收到 favicon URL 时发出。
Event: 'content-bounds-updated'
返回
event
Eventbounds
Rectangle - 请求的新的内容边界
当页面调用 window.moveTo
、window.resizeTo
或相关 API 时发出。
默认情况下,这会移动窗口。要阻止此行为,请调用 event.preventDefault()
。
Event: 'did-create-window'
返回
window
BrowserWindowdetails
Objecturl
string - 创建的窗口的 URL。frameName
string - 在window.open()
调用中为创建的窗口命名的名称。referrer
Referrer - 将传递给新窗口的引用页。是否会发送Referer
标头取决于引用页策略。postBody
PostBody (可选) - 将与相应的标头一起发送到新窗口的帖子数据。如果没有要发送的帖子数据,则值为null
。仅当窗口是由设置了target=_blank
的表单创建时才定义。disposition
string - 可以是default
、foreground-tab
、background-tab
、new-window
或other
。
在渲染器通过 window.open
成功创建窗口 *之后* 发出。如果通过 webContents.setWindowOpenHandler
取消了窗口的创建,则不发出此事件。
有关更多详细信息以及如何与 webContents.setWindowOpenHandler
结合使用,请参阅 window.open()
。
Event: 'will-navigate'
返回
details
事件<>url
string - 框架正在导航到的 URL。isSameDocument
boolean - 此事件不会针对使用 window.history API 的同文档导航和引用片段导航触发。此属性始终设置为false
。isMainFrame
boolean - 如果导航发生在主框架中,则为 true。frame
WebFrameMain | null - 要导航的框架。如果访问时框架已导航或已销毁,则可能为null
。initiator
WebFrameMain | null (optional) - 启动导航的框架,可以是父框架(例如,通过带框架名称的window.open
),或者如果导航不是由框架启动的,则为 null。如果启动框架在事件发出之前被删除,则也可能为 null。
url
string 已弃用isInPlace
boolean 已弃用isMainFrame
boolean 已弃用frameProcessId
Integer 已弃用frameRoutingId
Integer 已弃用
当用户或页面想要在主框架中开始导航时发出。当 window.location
对象更改或用户单击页面中的链接时,可能会发生这种情况。
当使用 webContents.loadURL
和 webContents.back
等 API 以编程方式开始导航时,此事件不会发出。
对于页面内导航(例如,单击锚点链接或更新 window.location.hash
)也不会发出此事件。请为此目的使用 did-navigate-in-page
事件。
调用 event.preventDefault()
将阻止导航。
Event: 'will-frame-navigate'
返回
details
事件<>url
string - 框架正在导航到的 URL。isSameDocument
boolean - 此事件不会针对使用 window.history API 的同文档导航和引用片段导航触发。此属性始终设置为false
。isMainFrame
boolean - 如果导航发生在主框架中,则为 true。frame
WebFrameMain | null - 要导航的框架。如果访问时框架已导航或已销毁,则可能为null
。initiator
WebFrameMain | null (optional) - 启动导航的框架,可以是父框架(例如,通过带框架名称的window.open
),或者如果导航不是由框架启动的,则为 null。如果启动框架在事件发出之前被删除,则也可能为 null。
当用户或页面想要在任何框架中开始导航时发出。当 window.location
对象更改或用户单击页面中的链接时,可能会发生这种情况。
与 will-navigate
不同,will-frame-navigate
在主框架或其任何子框架尝试导航时触发。当导航事件来自主框架时,isMainFrame
为 true
。
当使用 webContents.loadURL
和 webContents.back
等 API 以编程方式开始导航时,此事件不会发出。
对于页面内导航(例如,单击锚点链接或更新 window.location.hash
)也不会发出此事件。请为此目的使用 did-navigate-in-page
事件。
调用 event.preventDefault()
将阻止导航。
Event: 'did-start-navigation'
返回
details
事件<>url
string - 框架正在导航到的 URL。isSameDocument
boolean - 导航是否在未更改文档的情况下发生。同文档导航的示例包括引用片段导航、pushState/replaceState 和同页面历史导航。isMainFrame
boolean - 如果导航发生在主框架中,则为 true。frame
WebFrameMain | null - 要导航的框架。如果访问时框架已导航或已销毁,则可能为null
。initiator
WebFrameMain | null (optional) - 启动导航的框架,可以是父框架(例如,通过带框架名称的window.open
),或者如果导航不是由框架启动的,则为 null。如果启动框架在事件发出之前被删除,则也可能为 null。
url
string 已弃用isInPlace
boolean 已弃用isMainFrame
boolean 已弃用frameProcessId
Integer 已弃用frameRoutingId
Integer 已弃用
当任何框架(包括主框架)开始导航时发出。
Event: 'will-redirect'
返回
details
事件<>url
string - 框架正在导航到的 URL。isSameDocument
boolean - 导航是否在未更改文档的情况下发生。同文档导航的示例包括引用片段导航、pushState/replaceState 和同页面历史导航。isMainFrame
boolean - 如果导航发生在主框架中,则为 true。frame
WebFrameMain | null - 要导航的框架。如果访问时框架已导航或已销毁,则可能为null
。initiator
WebFrameMain | null (optional) - 启动导航的框架,可以是父框架(例如,通过带框架名称的window.open
),或者如果导航不是由框架启动的,则为 null。如果启动框架在事件发出之前被删除,则也可能为 null。
url
string 已弃用isInPlace
boolean 已弃用isMainFrame
boolean 已弃用frameProcessId
Integer 已弃用frameRoutingId
Integer 已弃用
当导航过程中发生服务器端重定向时发出。例如 302 重定向。
此事件将在 did-start-navigation
之后,并且总是(对于相同的导航)在 did-redirect-navigation
事件之前发出。
调用 event.preventDefault()
将阻止导航(不仅仅是重定向)。
Event: 'did-redirect-navigation'
返回
details
事件<>url
string - 框架正在导航到的 URL。isSameDocument
boolean - 导航是否在未更改文档的情况下发生。同文档导航的示例包括引用片段导航、pushState/replaceState 和同页面历史导航。isMainFrame
boolean - 如果导航发生在主框架中,则为 true。frame
WebFrameMain | null - 要导航的框架。如果访问时框架已导航或已销毁,则可能为null
。initiator
WebFrameMain | null (optional) - 启动导航的框架,可以是父框架(例如,通过带框架名称的window.open
),或者如果导航不是由框架启动的,则为 null。如果启动框架在事件发出之前被删除,则也可能为 null。
url
string 已弃用isInPlace
boolean 已弃用isMainFrame
boolean 已弃用frameProcessId
Integer 已弃用frameRoutingId
Integer 已弃用
在导航过程中发生服务器端重定向后发出。例如 302 重定向。
此事件无法阻止,如果你想阻止重定向,请查看上面的 will-redirect
事件。
Event: 'did-navigate'
返回
event
Eventurl
stringhttpResponseCode
Integer - 非 HTTP 导航为 -1httpStatusText
string - 非 HTTP 导航为空
当主框架导航完成时发出。
对于页面内导航(例如,单击锚点链接或更新 window.location.hash
)不发出此事件。请为此目的使用 did-navigate-in-page
事件。
Event: 'did-frame-navigate'
返回
event
Eventurl
stringhttpResponseCode
Integer - 非 HTTP 导航为 -1httpStatusText
string - 非 HTTP 导航为空,isMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
当任何框架导航完成时发出。
对于页面内导航(例如,单击锚点链接或更新 window.location.hash
)不发出此事件。请为此目的使用 did-navigate-in-page
事件。
Event: 'did-navigate-in-page'
返回
event
Eventurl
stringisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
当任何框架中发生页面内导航时发出。
当发生页面内导航时,页面 URL 会发生变化,但不会导致页面外部的导航。发生的示例包括单击锚点链接或触发 DOM hashchange
事件时。
Event: 'will-prevent-unload'
返回
event
Event
当 beforeunload
事件处理程序尝试取消页面卸载时发出。
调用 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()
}
})
这将在 BrowserView
上触发,但*不会*被遵守——这是因为我们选择不将 BrowserView
的生命周期与其拥有的 BrowserWindow 相关联,正如 规范 所述。
事件: 'render-process-gone'
返回
event
Eventdetails
RenderProcessGoneDetails
当渲染器进程意外消失时发出。这通常是因为它崩溃或被终止。
Event: 'unresponsive'
当网页变得无响应时发出。
Event: 'responsive'
当无响应的网页重新变得响应时发出。
Event: 'plugin-crashed'
返回
event
Eventname
stringversion
string
当插件进程崩溃时发出。
Event: 'destroyed'
当 webContents
被销毁时发出。
Event: 'input-event'
返回
event
EventinputEvent
InputEvent
当输入事件发送到 WebContents 时发出。有关详细信息,请参阅 InputEvent。
Event: 'before-input-event'
返回
event
Eventinput
Object - 输入属性。type
string -keyUp
或keyDown
。key
string - 等同于 KeyboardEvent.key。code
string - 等同于 KeyboardEvent.code。isAutoRepeat
boolean - 等同于 KeyboardEvent.repeat。isComposing
boolean - 等同于 KeyboardEvent.isComposing。shift
boolean - 等同于 KeyboardEvent.shiftKey。control
boolean - 等同于 KeyboardEvent.controlKey。alt
boolean - 等同于 KeyboardEvent.altKey。meta
boolean - 等同于 KeyboardEvent.metaKey。location
number - 等同于 KeyboardEvent.location。modifiers
string[] - 请参阅 InputEvent.modifiers。
在将 keydown
和 keyup
事件分派到页面之前发出。调用 event.preventDefault
将阻止页面的 keydown
/keyup
事件和菜单快捷键。
要仅阻止菜单快捷键,请使用 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'
返回
event
Eventmouse
MouseInputEvent
在将鼠标事件分派到页面之前发出。
调用 event.preventDefault
将阻止页面的鼠标事件。
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()
}
})
})
事件: 'enter-html-full-screen'
当窗口进入由 HTML API 触发的全屏状态时发出。
事件: 'leave-html-full-screen'
当窗口退出由 HTML API 触发的全屏状态时发出。
Event: 'zoom-changed'
返回
event
EventzoomDirection
string - 可以是in
或out
。
当用户使用鼠标滚轮请求更改缩放级别时发出。
事件:'blur'
当 WebContents
失去焦点时发出。
事件:'focus'
当 WebContents
获得焦点时发出。
请注意,在 macOS 上,获得焦点意味着 WebContents
是窗口的 first responder,因此在窗口之间切换焦点不会触发 WebContents
的 focus
和 blur
事件,因为每个窗口的 first responder 都不会改变。
WebContents
的 focus
和 blur
事件应仅用于检测同一窗口内不同 WebContents
和 BrowserView
之间的焦点变化。
Event: 'devtools-open-url'
返回
event
Eventurl
string - 被点击或选择的链接的 URL。
当在 DevTools 中点击链接或为其上下文菜单中的链接选择“在新标签页中打开”时发出。
Event: 'devtools-search-query'
返回
event
Eventquery
string - 要查询的文本。
当在其上下文菜单中为文本选择“搜索”时发出。
Event: 'devtools-opened'
当 DevTools 打开时发出。
Event: 'devtools-closed'
当 DevTools 关闭时发出。
Event: 'devtools-focused'
当 DevTools 获得焦点/打开时发出。
Event: 'certificate-error'
返回
event
Eventurl
stringerror
string - 错误代码。certificate
Certificatecallback
FunctionisTrusted
boolean - 指示证书是否可信。
isMainFrame
boolean
当无法验证 url
的 certificate
时发出。
用法与 app
的 certificate-error
事件相同。
Event: 'select-client-certificate'
返回
event
Eventurl
URLcertificateList
Certificate[]callback
Functioncertificate
Certificate - 必须是列表中提供的证书。
当请求客户端证书时发出。
用法与 app
的 select-client-certificate
事件相同。
事件: 'login'
返回
event
EventauthenticationResponseDetails
Objecturl
URL
authInfo
ObjectisProxy
booleanscheme
stringhost
stringport
Integerrealm
string
callback
Functionusername
string (可选)password
string (可选)
当 webContents
想要执行基本身份验证时发出。
用法与 app
的 login
事件相同。
Event: 'found-in-page'
返回
event
Eventresult
ObjectrequestId
IntegeractiveMatchOrdinal
Integer - 当前匹配项的序号。matches
Integer - 匹配项的总数。selectionArea
Rectangle - 第一个匹配区域的坐标。finalUpdate
boolean
当 webContents.findInPage
请求可用结果时发出。
Event: 'media-started-playing'
当媒体开始播放时发出。
Event: 'media-paused'
当媒体暂停或播放结束时发出。
Event: 'audio-state-changed'
返回
event
Event<>audible
boolean - 如果一个或多个框架或子webContents
正在发出音频,则为 true。
当媒体变得可听或不可听时发出。
Event: 'did-change-theme-color'
返回
event
Eventcolor
(string | null) - 主题颜色格式为 '#rrggbb'。如果未设置主题颜色,则为null
。
当页面的主题颜色发生变化时发出。这通常是由于遇到了 meta 标签
<meta name='theme-color' content='#ff0000'>
Event: 'update-target-url'
返回
event
Eventurl
string
当鼠标移动到链接上或键盘将焦点移到链接上时发出。
Event: 'cursor-changed'
返回
event
Eventtype
stringimage
NativeImage (optional)scale
Float (optional) - 自定义光标的缩放因子。size
Size (optional) -image
的尺寸。hotspot
Point (optional) - 自定义光标热点的坐标。
当光标类型更改时发出。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
。
如果 type
参数是 custom
,则 image
参数将包含 NativeImage
格式的自定义光标图像,并且 scale
、size
和 hotspot
将包含有关自定义光标的附加信息。
Event: 'context-menu'
返回
event
Eventparams
Objectx
Integer - x 坐标。y
Integer - y 坐标。frame
WebFrameMain | null - 调用上下文菜单的框架。如果访问时框架已导航或已销毁,则可能为null
。linkURL
string - 调用上下文菜单的节点所属链接的 URL。linkText
string - 与链接关联的文本。如果链接的内容是图像,则可能为空字符串。pageURL
string - 调用上下文菜单的顶级页面的 URL。frameURL
string - 调用上下文菜单的子框架的 URL。srcURL
string - 调用上下文菜单的元素的源 URL。具有源 URL 的元素是图像、音频和视频。mediaType
string - 调用上下文菜单的节点类型。可以是none
、image
、audio
、video
、canvas
、file
或plugin
。hasImageContents
boolean - 调用上下文菜单的图像是否具有非空内容。isEditable
boolean - 上下文是否可编辑。selectionText
string - 调用上下文菜单的选定文本。titleText
string - 调用上下文菜单的选定标题文本。altText
string - 调用上下文菜单的选定 alt 文本。suggestedFilename
string - 通过上下文菜单的“链接另存为”选项保存文件时使用的建议文件名。selectionRect
Rectangle - 表示文档空间中选定区域坐标的矩形。selectionStartOffset
number - 选定文本的起始位置。referrerPolicy
Referrer - 调用菜单时所处框架的引用策略。misspelledWord
string - 光标下的拼写错误单词(如果存在)。dictionarySuggestions
string[] - 要显示给用户的建议单词数组,用于替换misspelledWord
。仅在存在拼写错误单词且启用了拼写检查器时可用。frameCharset
string - 调用菜单时所处框架的字符编码。formControlType
string - 调用上下文菜单的源。可能的值包括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
boolean - 如果上下文可编辑,拼写检查是否启用。menuSourceType
string - 调用上下文菜单的输入源。可以是none
、mouse
、keyboard
、touch
、touchMenu
、longPress
、longTap
、touchHandle
、stylus
、adjustSelection
或adjustSelectionReset
。mediaFlags
Object - 调用上下文菜单的媒体元素的标志。inError
boolean - 媒体元素是否已崩溃。isPaused
boolean - 媒体元素是否已暂停。isMuted
boolean - 媒体元素是否已静音。hasAudio
boolean - 媒体元素是否有音频。isLooping
boolean - 媒体元素是否正在循环播放。isControlsVisible
boolean - 媒体元素控件是否可见。canToggleControls
boolean - 媒体元素控件是否可切换。canPrint
boolean - 媒体元素是否可以打印。canSave
boolean - 媒体元素是否可以下载。canShowPictureInPicture
boolean - 媒体元素是否可以显示画中画。isShowingPictureInPicture
boolean - 媒体元素是否正在显示画中画。canRotate
boolean - 媒体元素是否可以旋转。canLoop
boolean - 媒体元素是否可以循环播放。
editFlags
Object - 这些标志指示渲染器是否能够执行相应操作。canUndo
boolean - 渲染器是否认为可以撤销。canRedo
boolean - 渲染器是否认为可以重做。canCut
boolean - 渲染器是否认为可以剪切。canCopy
boolean - 渲染器是否认为可以复制。canPaste
boolean - 渲染器是否认为可以粘贴。canDelete
boolean - 渲染器是否认为可以删除。canSelectAll
boolean - 渲染器是否认为可以选择全部。canEditRichly
boolean - 渲染器是否认为可以丰富地编辑文本。
当有一个需要处理的新上下文菜单时发出。
Event: 'select-bluetooth-device'
返回
event
Eventdevices
BluetoothDevice[]callback
FunctiondeviceId
字符串
当调用 navigator.bluetooth.requestDevice
时需要选择蓝牙设备时发出。应使用要选择的设备的 deviceId
调用 callback
。将空字符串传递给 callback
将取消请求。
如果未为该事件添加事件监听器,则所有蓝牙请求都将被取消。
如果处理该事件时未调用 event.preventDefault
,则将自动选择第一个可用设备。
由于蓝牙的性质,调用 navigator.bluetooth.requestDevice
时扫描设备可能需要一些时间,并且会导致 select-bluetooth-device
多次触发,直到 callback
被一个设备 ID 或一个空字符串(用于取消请求)调用为止。
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'
返回
details
事件<>texture
OffscreenSharedTexture (optional) 实验性 - 帧的 GPU 共享纹理,当webPreferences.offscreen.useSharedTexture
为true
时。
dirtyRect
Rectangleimage
NativeImage - 整个帧的图像数据。
生成新帧时发出。缓冲区中仅传递了脏区域。
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 的硬件加速。此功能对于高性能渲染场景非常有用。
同一时间只能存在有限数量的纹理,因此,一旦使用完纹理,请务必调用 texture.release()
。通过自行管理纹理生命周期,您可以安全地通过 IPC 将 texture.textureInfo
传递给其他进程。
有关更多详细信息,请参阅 offscreen rendering tutorial。要了解如何在原生代码中处理纹理,请参阅 offscreen rendering 的代码文档。
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 重新加载时发出。
Event: 'will-attach-webview'
返回
event
EventwebPreferences
WebPreferences - 将用于 guest 页面的 web 偏好设置。可以修改此对象以调整 guest 页面的偏好设置。params
Record<string, string> - 其他<webview>
参数,如src
URL。可以修改此对象以调整 guest 页面的参数。
当 <webview>
的 web contents 正在附加到此 web contents 时发出。调用 event.preventDefault()
将销毁 guest 页面。
此事件可用于在 <webview>
的 webContents
加载之前配置其 webPreferences
,并提供设置无法通过 <webview>
属性设置的选项的功能。
Event: 'did-attach-webview'
返回
event
EventwebContents
WebContents - 由<webview>
使用的 guest web contents。
当 <webview>
已附加到此 web contents 时发出。
事件: 'console-message'
返回
details
事件<>message
string - 消息文本level
string - 消息严重性。可能的值包括info
、warning
、error
和debug
。lineNumber
Integer - 日志源中的行号sourceId
string - 日志源的 URLframe
WebFrameMain - 记录消息的框架
level
Integer 已弃用 - 日志级别,从 0 到 3。按顺序对应verbose
、info
、warning
和error
。message
string 已弃用 - 实际的控制台消息line
Integer 已弃用 - 触发此控制台消息的源的行号sourceId
string 已弃用
当关联窗口记录控制台消息时发出。
Event: 'preload-error'
返回
event
EventpreloadPath
stringerror
错误
当 preload 脚本 preloadPath
抛出未处理的异常 error
时发出。
Event: 'ipc-message'
返回
event
IpcMainEventchannel
string...args
any[]
当渲染器进程通过 ipcRenderer.send()
发送异步消息时发出。
另请参阅 webContents.ipc
,它提供了一个类似 IpcMain
的接口,用于响应来自此 WebContents 的特定 IPC 消息。
Event: 'ipc-message-sync'
返回
event
IpcMainEventchannel
string...args
any[]
当渲染器进程通过 ipcRenderer.sendSync()
发送同步消息时发出。
另请参阅 webContents.ipc
,它提供了一个类似 IpcMain
的接口,用于响应来自此 WebContents 的特定 IPC 消息。
Event: 'preferred-size-changed'
返回
event
EventpreferredSize
Size - 容纳文档布局所需的最小尺寸,无需滚动。
当 WebContents
的首选大小发生变化时发出。
当 webPreferences
中将 enablePreferredSizeMode
设置为 true
时,才会发出此事件。
Event: 'frame-created'
返回
event
Eventdetails
Objectframe
WebFrameMain | null - 创建的框架。如果访问时框架已导航或已销毁,则可能为null
。
当页面中的 mainFrame、<iframe>
或嵌套的 <iframe>
加载完成时发出。
实例方法
contents.loadURL(url[, options])
url
string
返回 Promise<void>
- 页面加载完成后(请参阅 did-finish-load
) promise 将解析,如果页面加载失败(请参阅 did-fail-load
)则 reject。已附加一个 noop rejection handler,可避免未处理的 rejection 错误。
在窗口中加载 url
。url
必须包含协议前缀,例如 http://
或 file://
。如果加载应绕过 http 缓存,则使用 pragma
标头实现。
const win = new BrowserWindow()
const options = { extraHeaders: 'pragma: no-cache\n' }
win.webContents.loadURL('https://github.com', options)
contents.loadFile(filePath[, options])
filePath
string
返回 Promise<void>
- 页面加载完成后(请参阅 did-finish-load
) promise 将解析,如果页面加载失败(请参阅 did-fail-load
)则 reject。
在窗口中加载给定的文件,filePath
应为相对于应用程序根目录的 HTML 文件路径。例如,一个应用程序结构如下
| root
| - package.json
| - src
| - main.js
| - index.html
将需要如下代码
const win = new BrowserWindow()
win.loadFile('src/index.html')
contents.downloadURL(url[, options])
url
string
在不导航的情况下启动 url
资源的下载。将触发 session
的 will-download
事件。
contents.getURL()
返回 string
- 当前网页的 URL。
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
- 当前网页的标题。
contents.isDestroyed()
返回 boolean
- 网页是否已被销毁。
contents.close([opts])
opts
Object (optional)waitForBeforeUnload
boolean - 如果为 true,则在关闭页面之前触发beforeunload
事件。如果页面阻止了卸载,则 WebContents 不会关闭。如果页面请求阻止卸载,将触发will-prevent-unload
事件。
关闭页面,就像 web content 调用了 window.close()
一样。
如果页面成功关闭(即页面未阻止卸载,或者 waitForBeforeUnload
为 false 或未指定),则 WebContents 将被销毁且不再可用。将发出 destroyed
事件。
contents.focus()
使网页获得焦点。
contents.isFocused()
返回 boolean
- 网页是否获得焦点。
contents.isLoading()
返回 boolean
- 网页是否仍在加载资源。
contents.isLoadingMainFrame()
返回 boolean
- 主框架(而不仅仅是 iframe 或其中的框架)是否仍在加载。
contents.isWaitingForResponse()
返回 boolean
- 网页是否正在等待页面主资源的首次响应。
contents.stop()
停止任何待处理的导航。
contents.reload()
重新加载当前网页。
contents.reloadIgnoringCache()
重新加载当前页面并忽略缓存。
contents.canGoBack()
已弃用
历史
版本(s) | 更改 |
---|---|
>=32.0.0 | API DEPRECATED |
返回 boolean
- 浏览器是否可以返回到之前的网页。
已弃用:应使用新的 contents.navigationHistory.canGoBack
API。
contents.canGoForward()
已弃用
历史
版本(s) | 更改 |
---|---|
>=32.0.0 | API DEPRECATED |
返回 boolean
- 浏览器是否可以前进到下一页。
已弃用:应使用新的 contents.navigationHistory.canGoForward
API。
contents.canGoToOffset(offset)
已弃用
历史
版本(s) | 更改 |
---|---|
>=32.0.0 | API DEPRECATED |
offset
Integer
返回 boolean
- 网页是否可以跳转到 offset
。
已弃用:应使用新的 contents.navigationHistory.canGoToOffset
API。
contents.clearHistory()
已弃用
历史
版本(s) | 更改 |
---|---|
>=32.0.0 | API DEPRECATED |
清除导航历史记录。
已弃用:应使用新的 contents.navigationHistory.clear
API。
contents.goBack()
已弃用
历史
版本(s) | 更改 |
---|---|
>=32.0.0 | API DEPRECATED |
使浏览器返回上一页。
已弃用:应使用新的 contents.navigationHistory.goBack
API。
contents.goForward()
已弃用
历史
版本(s) | 更改 |
---|---|
>=32.0.0 | API DEPRECATED |
使浏览器前进到下一页。
已弃用:应使用新的 contents.navigationHistory.goForward
API。
contents.goToIndex(index)
已弃用
历史
版本(s) | 更改 |
---|---|
>=32.0.0 | API DEPRECATED |
index
Integer
将浏览器导航到指定的绝对网页索引。
已弃用:应使用新的 contents.navigationHistory.goToIndex
API。
contents.goToOffset(offset)
已弃用
历史
版本(s) | 更改 |
---|---|
>=32.0.0 | API DEPRECATED |
offset
Integer
导航到“当前条目”的指定偏移量。
已弃用:应使用新的 contents.navigationHistory.goToOffset
API。
contents.isCrashed()
返回 boolean
- 渲染器进程是否已崩溃。
contents.forcefullyCrashRenderer()
强制终止当前承载此 webContents
的渲染器进程。这将导致 render-process-gone
事件以 reason=killed || reason=crashed
原因触发。请注意,某些 webContents 共享渲染器进程,因此调用此方法也可能导致同一窗口中其他 webContents 的主机进程崩溃。
调用此方法后立即调用 reload()
将强制在新进程中进行重新加载。当此进程不稳定或不可用时,应使用此方法,例如,为了从 unresponsive
事件中恢复。
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
string
覆盖此网页的用户代理。
contents.getUserAgent()
返回 string
- 此网页的用户代理。
contents.insertCSS(css[, options])
css
string
返回 Promise<string>
- 一个 promise,它解析为已插入 CSS 的一个 key,该 key 稍后可用于通过 contents.removeInsertedCSS(key)
移除 CSS。
将 CSS 注入当前网页,并返回一个用于插入的样式的唯一键,该键可以在之后通过 <webview>.removeInsertedCSS(css)
移除。
const win = new BrowserWindow()
win.webContents.on('did-finish-load', () => {
win.webContents.insertCSS('html, body { background-color: #f00; }')
})
contents.removeInsertedCSS(key)
key
string
返回 Promise<void>
- 如果移除成功,则解析。
从当前网页中移除插入的 CSS。样式表由其 key 标识,该 key 是从 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
stringuserGesture
boolean (可选) - 默认为false
。
返回 Promise<any>
- 一个 promise,它解析为已执行代码的结果,或者如果代码的结果是已拒绝的 promise,则 reject。
在页面中执行 code
。
在浏览器窗口中,某些 HTML API(如 requestFullScreen
)只能由用户的手势调用。将 userGesture
设置为 true
将消除此限制。
代码执行将暂停,直到网页停止加载。
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
Integer - 要在此运行 javascript 的世界的 ID,0
是默认世界,999
是 Electron 的contextIsolation
功能所使用的世界。您可以提供任何整数。scripts
WebSource[]userGesture
boolean (可选) - 默认为false
。
返回 Promise<any>
- 一个 promise,它解析为已执行代码的结果,或者如果代码的结果是已拒绝的 promise,则 reject。
功能类似于 executeJavaScript
,但会在隔离的上下文中评估 scripts
。
contents.setIgnoreMenuShortcuts(ignore)
ignore
boolean
当此 web contents 获得焦点时,忽略应用程序菜单快捷键。
contents.setWindowOpenHandler(handler)
-
handler
Function<WindowOpenHandlerResponse>details
Objecturl
string - 传递给window.open()
的 URL 的*解析后*的版本。例如,使用window.open('foo')
打开窗口将得到类似https://the-origin/the/current/path/foo
的结果。frameName
string - 在window.open()
中提供的窗口名称features
string - 传递给window.open()
的逗号分隔的窗口功能列表。disposition
string - 可以是default
、foreground-tab
、background-tab
、new-window
或other
。referrer
Referrer - 将传递给新窗口的引用页。是否会发送Referer
标头取决于引用页策略。postBody
PostBody (可选) - 将与相应的标头一起发送到新窗口的帖子数据。如果没有要发送的帖子数据,则值为null
。仅当窗口是由设置了target=_blank
的表单创建时才定义。
返回
WindowOpenHandlerResponse
- 当设置为{ action: 'deny' }
时,取消新窗口的创建。{ action: 'allow' }
将允许创建新窗口。返回 unrecognized 值,如 null、undefined 或没有识别的 'action' 值的对象,将导致控制台错误,并具有与返回{action: 'deny'}
相同的效果。
在渲染器请求创建新窗口(例如,通过 window.open()
、带有 target="_blank"
的链接、按住 Shift 单击链接或提交带有 <form target="_blank">
的表单)之前调用。有关更多详细信息以及如何与 did-create-window
结合使用,请参阅 window.open()
。
一个示例,展示了如何自定义新 BrowserWindow
的创建过程,使其成为附加到主窗口的 BrowserView
。
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
boolean
静音当前网页的音频。
contents.isAudioMuted()
返回 boolean
- 此页面是否已被静音。
contents.isCurrentlyAudible()
返回 boolean
- 当前是否正在播放音频。
contents.setZoomFactor(factor)
factor
Double - 缩放因子;默认为 1.0。
将缩放比例更改为指定的因子。缩放比例是缩放百分比除以 100,因此 300% = 3.0。
因子必须大于 0.0。
contents.getZoomFactor()
返回 number
- 当前缩放因子。
contents.setZoomLevel(level)
level
number - 缩放级别。
将缩放级别更改为指定级别。原始大小为 0,每次向上或向下增加一个级别,分别表示比原始大小大 20% 或小 20%,最高可达 300% 和 50%。其公式为 scale := 1.2 ^ level
。
Chromium 级别的缩放策略是同源策略,这意味着特定域的缩放级别会传播到具有相同域的所有窗口实例。区分窗口 URL 将使缩放功能在每个窗口中生效。
contents.getZoomLevel()
返回 number
- 当前缩放级别。
contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevel
numbermaximumLevel
number
返回 Promise<void>
设置捏合缩放的最大和最小级别。
在 Electron 中,视觉缩放默认是禁用的。要重新启用它,请调用
const win = new BrowserWindow()
win.webContents.setVisualZoomLevelLimits(1, 3)
contents.undo()
在网页中执行编辑命令 undo
。
contents.redo()
在网页中执行编辑命令 redo
。
contents.cut()
在网页中执行编辑命令 cut
。
contents.copy()
在网页中执行编辑命令 copy
。
contents.centerSelection()
将当前文本选择居中显示在网页中。
contents.copyImageAt(x, y)
x
Integery
Integer
将指定位置的图像复制到剪贴板。
contents.paste()
在网页中执行编辑命令 paste
。
contents.pasteAndMatchStyle()
在网页中执行编辑命令 pasteAndMatchStyle
。
contents.delete()
在网页中执行编辑命令 delete
。
contents.selectAll()
在网页中执行编辑命令 selectAll
。
contents.unselect()
在网页中执行编辑命令 unselect
。
contents.scrollToTop()
滚动到当前 webContents
的顶部。
contents.scrollToBottom()
滚动到当前 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.
示例
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 })
For a call of win.webContents.adjustSelection({ start: 1, end: 5 })
Before

After

contents.replace(text)
text
string
Executes the editing command replace
in web page.
contents.replaceMisspelling(text)
text
string
Executes the editing command replaceMisspelling
in web page.
contents.insertText(text)
text
string
返回 Promise<void>
将 text
插入到焦点元素中。
contents.findInPage(text[, options])
text
string - Content to be searched, must not be empty.
Returns Integer
- The request id used for the request.
Starts a request to find all matches for the text
in the web page. The result of the request can be obtained by subscribing to found-in-page
event.
contents.stopFindInPage(action)
action
string - Specifies the action to take place when endingwebContents.findInPage
request.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
.
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
Rectangle (可选) - The area of the page to be captured.opts
Object (optional)stayHidden
boolean (可选) - Keep the page hidden instead of visible. Default isfalse
.stayAwake
boolean (可选) - Keep the system awake instead of allowing it to sleep. Default isfalse
.
返回 Promise<NativeImage>
- 解析为 NativeImage
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()
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.
Returns Promise<PrinterInfo[]>
- Resolves with a PrinterInfo[]
contents.print([options], [callback])
callback
Function (可选)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
. Width and height must both be minimum 353 microns but may be higher on some operating systems.
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.
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)
Returns Promise<Buffer>
- Resolves with the generated PDF data.
Prints the window's web page as PDF.
The landscape
will be ignored if @page
CSS at-rule is used in the web page.
An example of webContents.printToPDF
const { app, BrowserWindow } = require('electron')
const fs = require('node:fs')
const path = require('node:path')
const os = require('node:os')
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)
})
})
})
See Page.printToPdf for more information.
contents.addWorkSpace(path)
path
string
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
string
Removes the specified path from DevTools workspace.
contents.setDevToolsWebContents(devToolsWebContents)
devToolsWebContents
WebContents
Uses the devToolsWebContents
as the target WebContents
to show devtools.
The devToolsWebContents
must not have done any navigation, and it should not be used for other purposes after the call.
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, including BrowserWindow
, BrowserView
and <webview>
tag.
Note that closing the devtools does not destroy the devToolsWebContents
, it is caller's responsibility to destroy devToolsWebContents
.
An example of showing devtools in a <webview>
tag
<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
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.
On Windows, if Windows Control Overlay is enabled, Devtools will be opened with mode: 'detach'
.
contents.closeDevTools()
Closes the devtools.
contents.isDevToolsOpened()
Returns boolean
- Whether the devtools is opened.
contents.isDevToolsFocused()
Returns boolean
- Whether the devtools view is focused .
contents.getDevToolsTitle()
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
string
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
Integery
Integer
Starts inspecting element at position (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.
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. 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.
Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception.
For additional reading, refer to Electron's IPC guide.
contents.sendToFrame(frameId, channel, ...args)
frameId
Integer | [number, number] - the ID of the frame to send to, or a pair of[processId, frameId]
if the frame is in a different process to the main frame.channel
string...args
any[]
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.
NOTE: Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception.
The renderer process can handle the message by listening to channel
with the ipcRenderer
module.
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)
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
stringmessage
anytransfer
MessagePortMain[] (可选)
Send a message to the renderer process, optionally transferring ownership of zero or more MessagePortMain
objects.
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.
例如
// 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
ObjectscreenPosition
string - Specify the screen type to emulate (default:desktop
)desktop
- Desktop screen type.mobile
- Mobile screen type.
screenSize
Size - Set the emulated screen size (screenPosition == mobile).viewPosition
Point - Position the view on the screen (screenPosition == mobile) (default:{ x: 0, y: 0 }
).deviceScaleFactor
Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: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
).
Enable device emulation with the given parameters.
contents.disableDeviceEmulation()
Disable device emulation enabled by webContents.enableDeviceEmulation
.
contents.sendInputEvent(inputEvent)
inputEvent
MouseInputEvent | MouseWheelInputEvent | KeyboardInputEvent
Sends an input event
to the page.
The BrowserWindow
containing the contents needs to be focused for sendInputEvent()
to work.
contents.beginFrameSubscription([onlyDirty ,]callback)
onlyDirty
boolean (可选) - Defaults tofalse
.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.
The 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. 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
Objectfile
string - The path to the file being dragged.files
string[] (可选) - The paths to the files being dragged. (files
will overridefile
field)icon
NativeImage | string - The image must be non-empty on 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.
contents.savePage(fullPath, saveType)
fullPath
string - The absolute file path.saveType
string - Specify the save type.HTMLOnly
- Save only the HTML of the page.HTMLComplete
- Save complete-html page.MHTML
- Save complete-html page as 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.
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.
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.
contents.setWebRTCIPHandlingPolicy(policy)
policy
string - Specify the WebRTC IP Handling Policy.default
- Exposes user's public and local IPs. 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.default_public_interface_only
- Exposes user's public IP, but does not expose user's local IP. When this policy is used, WebRTC should only use the default route used by http. This doesn't expose any local addresses.default_public_and_private_interfaces
- Exposes user's public and local IPs. When this policy is used, WebRTC should only use the default route used by 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. When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP.
Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See BrowserLeaks for more details.
contents.getWebRTCUDPPortRange()
返回 Object
min
Integer - The minimum UDP port number that WebRTC should use.max
Integer - The maximum UDP port number that WebRTC should use.
By default this value is { min: 0, max: 0 }
, which would apply no restriction on the udp port range.
contents.setWebRTCUDPPortRange(udpPortRange)
udpPortRange
Objectmin
Integer - The minimum UDP port number that WebRTC should use.max
Integer - The maximum UDP port number that WebRTC should use.
Setting the WebRTC UDP Port Range allows you to restrict the udp port range used by WebRTC. By default the port range is unrestricted.
To reset to an unrestricted port range this value should be set to { min: 0, max: 0 }
.
contents.getMediaSourceId(requestWebContents)
requestWebContents
WebContents - Web contents that the id will be registered to.
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()
Returns Integer
- The operating system pid
of the associated renderer process.
contents.getProcessId()
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
string - Path to the output file.
Returns Promise<void>
- Indicates whether the snapshot has been created successfully.
Takes a V8 heap snapshot and saves it to filePath
.
contents.getBackgroundThrottling()
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)
历史
allowed
boolean
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()
Returns string
- the type of the webContent. Can be backgroundPage
, window
, browserView
, remote
, webview
or offscreen
.
contents.setImageAnimationPolicy(policy)
policy
string - Can beanimate
,animateOnce
ornoAnimation
.
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.
This corresponds to the animationPolicy accessibility feature in Chromium.
实例属性
contents.ipc
Readonly
An IpcMain
scoped to just IPC messages sent from this WebContents.
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)
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)
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
A boolean
property that determines whether this page is muted.
contents.userAgent
A string
property that determines the user agent for this web page.
contents.zoomLevel
A number
property that determines the zoom level for this web contents.
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
A number
property that determines the zoom factor for this web contents.
The zoom factor is the zoom percent divided by 100, so 300% = 3.0.
contents.frameRate
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
Readonly
A Integer
representing the unique ID of this WebContents. Each ID is unique among all WebContents
instances of the entire Electron application.
contents.session
Readonly
A Session
used by this webContents.
contents.navigationHistory
Readonly
A NavigationHistory
used by this webContents.
contents.hostWebContents
Readonly
A WebContents
instance that might own this WebContents
.
contents.devToolsWebContents
Readonly
A WebContents | null
property that represents the of DevTools WebContents
associated with a given WebContents
.
Users should never store this object because it may become null
when the DevTools has been closed.
contents.debugger
Readonly
A Debugger
instance for this webContents.
contents.backgroundThrottling
历史
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
Readonly
A WebFrameMain
property that represents the top frame of the page's frame hierarchy.
contents.opener
Readonly
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
Readonly
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.