webContents
渲染以及控制 web 页面
Process: Main
webContents
是一个EventEmitter. It is responsible for rendering and controlling a web page and is a property of the BrowserWindow
object. 这是一个访问 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
Several events can be used to monitor navigations as they occur within a webContents
.
Document Navigations
When a webContents
navigates to another page (as opposed to an in-page navigation), the following events will be fired.
did-start-navigation
will-frame-navigate
will-navigate
(only fired when main frame navigates)will-redirect
(only fired when a redirect happens during navigation)did-redirect-navigation
(only fired when a redirect happens during navigation)did-frame-navigate
did-navigate
(only fired when main frame navigates)
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
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.
方法
通过webContents
模块可以访问以下方法:
const { webContents } = require('electron')
console.log(webContents)
webContents.getAllWebContents()
返回 WebContents[]
- 所有 WebContents
实例的数组。 包含所有Windows,webviews,opened devtools 和 devtools 扩展背景页的 web 内容
webContents.getFocusedWebContents()
Returns WebContents | null
- The web contents that is focused in this application, otherwise returns null
.
webContents.fromId(id)
id
Integer
Returns WebContents | undefined
- A WebContents instance with the given ID, or undefined
if there is no WebContents associated with the given ID.
webContents.fromFrame(frame)
frame
WebFrameMain
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
string - WebContents 例实相关的 Chrome DevTools Protocol TargetID 。
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 的实例
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
渲染和控制 BrowserWindow 实例的内容。
Process: Main
This class is not exported from the 'electron'
module. 它只能作为 Electron API 中其他方法的返回值。
实例事件
Event: 'did-finish-load'
导航完成时触发,即选项卡的旋转器将停止旋转,并指派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-finish-load
,只不过是在加载失败或取消加载之后触发,例如调用 window.stop()
。
Event: 'did-frame-finish-load'
返回:
event
EventisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
当框架完成导航(navigation)时触发
Event: 'did-start-loading'
当tab中的旋转指针(spinner)开始旋转时,就会触发该事件。
Event: 'did-stop-loading'
当tab中的旋转指针(spinner)结束旋转时,就会触发该事件。
事件: 'dom-ready'
当顶级 frame 的 document 被加载完时触发。
事件: 'page-title-updated'
返回:
event
Eventtitle
stringexplicitSet
boolean
当导航时页面标题更新时触发。 当标题从文件 url 中合成时 explicitSet
为 false。
事件: 'page-favicon-updated'
返回:
event
Eventfavicons
string[] - 由连接组成的数组。
当页面获取到favicon的连接时,触发该事件。
Event: 'content-bounds-updated'
返回:
event
Eventbounds
Rectangle - requested new content bounds
Emitted when the page calls window.moveTo
, window.resizeTo
or related APIs.
By default, this will move the window. To prevent that behavior, call event.preventDefault()
.
Event: 'did-create-window'
返回:
window
BrowserWindowdetails
Objecturl
string - 创建窗口的 URL。frameName
string -window.open()
调用的创建窗口名称。referrer
Referrer - The referrer that will be passed to the new window. 可能会也可能不会发送Referer
头,取决于 referrer 策略。postBody
PostBody (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. 如果没有 post 数据被发送,值将为null
。 仅当窗口从 form 并设置target=_blank
时创建,才会被定义。disposition
string - Can bedefault
,foreground-tab
,background-tab
,new-window
orother
.
在渲染进程中由 window.open
成功创建窗口_之后_ 触发。 Not emitted if the creation of the window is canceled from webContents.setWindowOpenHandler
.
See window.open()
for more details and how to use this in conjunction with webContents.setWindowOpenHandler
.
Event: 'will-navigate'
返回:
details
Event<>url
string - The URL the frame is navigating to.isSameDocument
boolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set tofalse
for this event.isMainFrame
boolean - True if the navigation is taking place in a main frame.frame
WebFrameMain | null - The frame to be navigated. May benull
if accessed after the frame has either navigated or been destroyed.initiator
WebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.open
with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
url
string DeprecatedisInPlace
boolean DeprecatedisMainFrame
boolean DeprecatedframeProcessId
Integer DeprecatedframeRoutingId
Integer Deprecated
Emitted when a user or the page wants to start navigation on the main frame. 它可能发生在 window.location
对象改变或用户点击页面上的链接时,可能会发生这种情况。
当使用如 webContents.loadURL
和 webContents.back
APIs 以编程方式导航时,将不会触发此事件。
页面内导航也不会触发,例如点击锚点或更新 window.location.hash
。 可使用 did-navigate-in-page
事件。
调用event.preventDefault()
将阻止导航。
Event: 'will-frame-navigate'
返回:
details
Event<>url
string - The URL the frame is navigating to.isSameDocument
boolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set tofalse
for this event.isMainFrame
boolean - True if the navigation is taking place in a main frame.frame
WebFrameMain | null - The frame to be navigated. May benull
if accessed after the frame has either navigated or been destroyed.initiator
WebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.open
with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
Emitted when a user or the page wants to start navigation in any frame. 它可能发生在 window.location
对象改变或用户点击页面上的链接时,可能会发生这种情况。
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
APIs 以编程方式导航时,将不会触发此事件。
页面内导航也不会触发,例如点击锚点或更新 window.location.hash
。 可使用 did-navigate-in-page
事件。
调用event.preventDefault()
将阻止导航。
Event: 'did-start-navigation'
返回:
details
Event<>url
string - The URL the frame is navigating to.isSameDocument
boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.isMainFrame
boolean - True if the navigation is taking place in a main frame.frame
WebFrameMain | null - The frame to be navigated. May benull
if accessed after the frame has either navigated or been destroyed.initiator
WebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.open
with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
url
string DeprecatedisInPlace
boolean DeprecatedisMainFrame
boolean DeprecatedframeProcessId
Integer DeprecatedframeRoutingId
Integer Deprecated
当任何 frame (包括 main) 开始导航时触发。
Event: 'will-redirect'
返回:
details
Event<>url
string - The URL the frame is navigating to.isSameDocument
boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.isMainFrame
boolean - True if the navigation is taking place in a main frame.frame
WebFrameMain | null - The frame to be navigated. May benull
if accessed after the frame has either navigated or been destroyed.initiator
WebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.open
with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
url
string DeprecatedisInPlace
boolean DeprecatedisMainFrame
boolean DeprecatedframeProcessId
Integer DeprecatedframeRoutingId
Integer Deprecated
当一个服务器端的重定向导航时触发。 例如,302 重定向。
事件在 did-start-navigation
之后,总是在 did-redirect-navigation
之前触发。
调用 event.preventDefault()
将阻止导航 (不仅仅是重定向)。
Event: 'did-redirect-navigation'
返回:
details
Event<>url
string - The URL the frame is navigating to.isSameDocument
boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation.isMainFrame
boolean - True if the navigation is taking place in a main frame.frame
WebFrameMain | null - The frame to be navigated. May benull
if accessed after the frame has either navigated or been destroyed.initiator
WebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.open
with a frame's name), or null if the navigation was not initiated by a frame. This can also be null if the initiating frame was deleted before the event was emitted.
url
string DeprecatedisInPlace
boolean DeprecatedisMainFrame
boolean DeprecatedframeProcessId
Integer DeprecatedframeRoutingId
Integer Deprecated
导航期间发生服务端重定向之后后触发。 例如,302 重定向。
这个事件不能被阻止,如果你想要阻止重定向,你应该在 will-redirect
事件之中处理。
Event: 'did-navigate'
返回:
event
Eventurl
stringhttpResponseCode
Integer - -1 代表非 HTTP 导航。httpStatusText
string - 非 HTTP 导航为空。
当 main frame 导航完成时触发。
事件在页面内导航不会触发,例如点击锚点或更新 window.location.hash
。 可使用 did-navigate-in-page
事件。
Event: 'did-frame-navigate'
返回:
event
Eventurl
stringhttpResponseCode
Integer - -1 代表非 HTTP 导航。httpStatusText
string - 使用非 HTTP 导航时为空isMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
当任意 frame 导航完成后触发。
事件在页面内导航不会触发,例如点击锚点或更新 window.location.hash
。 可使用 did-navigate-in-page
事件。
Event: 'did-navigate-in-page'
返回:
event
Eventurl
stringisMainFrame
booleanframeProcessId
IntegerframeRoutingId
Integer
页面内任意 frame 发生导航时触发。
当发生页内导航时,虽然页面地址发生变化,但它并没有导航到其它页面。 例如,点击锚点链接,或者DOM的 hashchange
事件被触发时,都会触发该事件。
Event: 'will-prevent-unload'
返回:
event
Event
当 beforeunload
事件尝试取消页面 unload 时触发。
调用 event.preventDefault()
将忽略 beforeunload
事件处理,同时允许页面 卸载(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
的每一个 规范 联系起来。
事件: 'render-process-gone'
返回:
event
Eventdetails
RenderProcessGoneDetails
渲染器进程意外消失时触发。 这种情况通常因为进程崩溃或被杀死。
事件: 'unresponsive'
网页变得未响应时触发
事件: 'responsive'
未响应的页面变成响应时触发
Event: 'plugin-crashed'
返回:
event
Eventname
stringversion
string
当有插件进程崩溃时触发
Event: 'destroyed'
当webContents
被销毁时,触发该事件。
Event: 'input-event'
返回:
event
EventinputEvent
InputEvent
Emitted when an input event is sent to the 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[] - See InputEvent.modifiers.
在页面中调度 keydown
和 keyup
之前触发。 调用 event.preventDefault
将阻止页面内 keydown
/keyup
事件和菜单快捷键。
仅阻止菜单快捷键, 使用 setIgnoreMenuShortcuts
:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-input-event', (event, input) => {
// 例如, 当 Ctrl/Cmd are down 被按下,仅开启应用程序菜单键盘快捷键。
win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta)
})
事件: '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
是窗口的第一响应者,因为每个窗口的第一响应者不会更改,所以在窗口之间切换焦点是不会出发 WebContents
的 focus
和 blur
事件的。
WebContents
的 focus
和 blur
事件应该仅用于检测同一窗口中不同 WebContents
和 BrowserView
之间的焦点变化。
Event: 'devtools-open-url'
返回:
event
Eventurl
string -被单击或选中的链接的 URL。
Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu.
Event: 'devtools-search-query'
返回:
event
Eventquery
string - text to query for.
Emitted when 'Search' is selected for text in its context menu.
Event: 'devtools-opened'
当开发者工具被打开时,触发该事件。
Event: 'devtools-closed'
当开发者工具被关闭时,触发该事件。
Event: 'devtools-focused'
当开发者工具被选中/打开时,触发该事件。
事件: 'certificate-error'
返回:
event
Eventurl
stringerror
string - 错误码。certificate
Certificatecallback
FunctionisTrusted
boolean - 表示证书是否视为可信任的。
isMainFrame
boolean
证书
的链接
验证失败时,触发该事件。
The usage is the same with the certificate-error
event of app
.
事件: 'select-client-certificate'
返回:
event
Eventurl
URLcertificateList
Certificate[]callback
Functioncertificate
Certificate - Must be a certificate from the given list.
当一个客户证书被请求的时候发出。
使用方式与app
的select-client-certificate
的事件相同。
事件: "login"
返回:
event
EventauthenticationResponseDetails
Objecturl
URL
authInfo
ObjectisProxy
booleanscheme
stringhost
stringport
Integerrealm
string
callback
Functionusername
string (可选)password
string (可选)
当 webContents
要进行基本身份验证时触发。
The usage is the same with the login
event of app
.
Event: 'found-in-page'
返回:
event
Eventresult
ObjectrequestId
IntegeractiveMatchOrdinal
Integer - 当前匹配位置。matches
Integer - 符合匹配条件的元素个数。selectionArea
Rectangle - 第一个匹配到区域的坐标。finalUpdate
boolean
Emitted when a result is available for webContents.findInPage
request.
Event: 'media-started-playing'
多媒体开始播放时,触发该事件。
Event: 'media-paused'
当媒体文件暂停或播放完成的时候触发
Event: 'audio-state-changed'
返回:
event
Event<>audible
boolean - True if one or more frames or childwebContents
are emitting audio.
Emitted when media becomes audible or inaudible.
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
当鼠标滑到,或者键盘切换到a连接时,触发该事件。
Event: 'cursor-changed'
返回:
event
Eventtype
stringimage
NativeImage (optional)scale
Float (可选) - 自定义鼠标指针的缩放比例系数。size
Size (optional) - the size of theimage
.hotspot
Point (optional) - coordinates of the custom cursor's 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
.
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'
返回:
event
Eventparams
Objectx
Integer - x 坐标。y
Integer - y 坐标。frame
WebFrameMain | null - Frame from which the context menu was invoked. May benull
if accessed after the frame has either navigated or been destroyed.linkURL
string - URL of the link that encloses the node the context menu was invoked on.linkText
string - Text associated with the link. 如果链接的内容是图片,则可能为空的 string。pageURL
string - URL of the top level page that the context menu was invoked on.frameURL
string - URL of the subframe that the context menu was invoked on.srcURL
string - Source URL for the element that the context menu was invoked on. Elements 源 URLs 是 图片、音频 和 视频。mediaType
string - Type of the node the context menu was invoked on. 可以是none
,image
,audio
,video
,canvas
,file
或plugin
。hasImageContents
boolean - Whether the context menu was invoked on an image which has non-empty contents.isEditable
boolean - 上下文内容是否可编辑。selectionText
string - Text of the selection that the context menu was invoked on.titleText
string - Title text of the selection that the context menu was invoked on.altText
string - Alt text of the selection that the context menu was invoked on.suggestedFilename
string - Suggested filename to be used when saving file through 'Save Link As' option of context menu.selectionRect
Rectangle - Rect representing the coordinates in the document space of the selection.selectionStartOffset
number - Start position of the selection text.referrerPolicy
Referrer - The referrer policy of the frame on which the menu is invoked.misspelledWord
string - The misspelled word under the cursor, if any.dictionarySuggestions
string[] - An array of suggested words to show the user to replace themisspelledWord
. 仅当单词拼写错误且启用了拼写检查器时可用。frameCharset
string - The character encoding of the frame on which the menu was invoked.formControlType
string - The source that the context menu was invoked on. Possible values includenone
,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
, andtext-area
,spellcheckEnabled
boolean - If the context is editable, whether or not spellchecking is enabled.menuSourceType
string - Input source that invoked the context menu. Can benone
,mouse
,keyboard
,touch
,touchMenu
,longPress
,longTap
,touchHandle
,stylus
,adjustSelection
, oradjustSelectionReset
.mediaFlags
Object - 调用菜单的媒体 element 的标志。inError
boolean - Whether the media element has crashed.isPaused
boolean - Whether the media element is paused.isMuted
boolean - Whether the media element is muted.hasAudio
boolean - Whether the media element has audio.isLooping
boolean - Whether the media element is looping.isControlsVisible
boolean - Whether the media element's controls are visible.canToggleControls
boolean - Whether the media element's controls are toggleable.canPrint
boolean - Whether the media element can be printed.canSave
boolean - Whether or not the media element can be downloaded.canShowPictureInPicture
boolean - Whether the media element can show picture-in-picture.isShowingPictureInPicture
boolean - Whether the media element is currently showing picture-in-picture.canRotate
boolean - Whether the media element can be rotated.canLoop
boolean - Whether the media element can be looped.
editFlags
Object - 这些标志表示渲染进程是否认为能够执行相应操作行为。canUndo
boolean - Whether the renderer believes it can undo.canRedo
boolean - Whether the renderer believes it can redo.canCut
boolean - Whether the renderer believes it can cut.canCopy
boolean - Whether the renderer believes it can copy.canPaste
boolean - Whether the renderer believes it can paste.canDelete
boolean - Whether the renderer believes it can delete.canSelectAll
boolean - Whether the renderer believes it can select all.canEditRichly
boolean - Whether the renderer believes it can edit text richly.
当新的上下文菜单需要处理时触发。
事件: 'select-bluetooth-device'
返回:
event
Eventdevices
BluetoothDevice[]callback
FunctiondeviceId
string 设备Id
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 an event listener is not added for this event, or if event.preventDefault
is not called when handling this event, the first available device will be automatically selected.
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'
返回:
details
Event<>texture
OffscreenSharedTexture (optional) Experimental - The GPU shared texture of the frame, whenwebPreferences.offscreen.useSharedTexture
istrue
.
dirtyRect
Rectangleimage
NativeImage - The image data of the whole frame.
当一个新的帧被创建时触发。 Only the dirty area is passed in the buffer.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ webPreferences: { offscreen: true } })
win.webContents.on('paint', (event, dirty, image) => {
// updateBitmap(dirty, image.getBitmap())
})
win.loadURL('https://github.com')
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.
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.
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.
// For example: https://github.com/electron/electron/tree/main/spec/fixtures/native-addon/osr-gpu
// 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'
当在开发者工具中命令webContents重新加载时,触发该事件。
Event: 'will-attach-webview'
返回:
event
EventwebPreferences
WebPreferences - The web preferences that will be used by the guest page. 可以修改此对象以调整访客页面的首选项。params
Record<string, string> - The other<webview>
parameters such as thesrc
URL. 可以修改此对象以调整访客页面的首选项。
当 <webview>
的 web contents 开始附加到当前 web contents 时触发。 调用 event.preventDefault()
将销毁访客页面。
此事件可以用来在加载前为 <webview>
的 webContents
配置 webPreferences
,并提供设置无法通过 <webview>
属性设置的功能。
Event: 'did-attach-webview'
返回:
event
EventwebContents
WebContents -<webview>
使用的 web contents。
当<webview>
被挂载到页面内容中时,触发该事件。
Event: 'console-message'
返回:
event
Eventlevel
Integer - 日志级别,从0到3。 按顺序匹配verbose
,info
,warning
和error
.message
string - 实际控制台消息line
Integer - 触发控制台消息的源代码行号。sourceId
string
当相关联的窗口记录一条控制台消息时触发。
Event: 'preload-error'
返回:
event
EventpreloadPath
stringerror
Error
当预加载脚本的 preloadPath
引发未处理的异常 error
时触发。
Event: 'ipc-message'
返回:
event
IpcMainEventchannel
string...args
any[]
当渲染器进程通过 ipcRenderer.send()
发送异步消息时触发。
See also webContents.ipc
, which provides an IpcMain
-like interface for responding to IPC messages specifically from this WebContents.
Event: 'ipc-message-sync'
返回:
event
IpcMainEventchannel
string...args
any[]
当渲染进程通过 ipcRenderer.sendSync()
发送同步消息时触发。
See also webContents.ipc
, which provides an IpcMain
-like interface for responding to IPC messages specifically from this WebContents.
Event: 'preferred-size-changed'
返回:
event
EventpreferredSize
Size - The minimum size needed to contain the layout of the document—without requiring scrolling.
当 WebContents
preferred size 改变时触发。
此事件仅在 webPreferences
中的 enablePreferredSizeMode
设置为 true
时才会触发。
Event: 'frame-created'
返回:
event
Eventdetails
Objectframe
WebFrameMain | null - The created frame. May benull
if accessed after the frame has either navigated or been destroyed.
Emitted when the mainFrame, an <iframe>
, or a nested <iframe>
is loaded within the page.
实例方法
contents.loadURL(url[, options])
url
string
Returns Promise<void>
- the promise will resolve when the page has finished loading (see did-finish-load
), and rejects if the page fails to load (see did-fail-load
). 附加一个无操作的 rejection 处理。可以避免 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
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 文件路径。 例如,像如下应用程序目录结构:
| root
| - package.json
| - src
| - main.js
| - index.html
需要运行以下代码:
const win = new BrowserWindow()
win.loadFile('src/index.html')
contents.downloadURL(url[, options])
url
string
Initiates a download of the resource at url
without navigating. 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 - if true, fire thebeforeunload
event before closing the page. If the page prevents the unload, the WebContents will not be closed. Thewill-prevent-unload
will be fired if the page requests prevention of unload.
Closes the page, as if the web content had called window.close()
.
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()
页面聚焦
contents.isFocused()
返回 boolean
- 网页是否具有焦点。
contents.isLoading()
返回 boolean
- 网页是否仍在加载资源。
contents.isLoadingMainFrame()
Returns boolean
- Whether the main frame (and not just iframes or frames within it) is still loading.
contents.isWaitingForResponse()
返回 boolean
- 网页是否正在等待当前页主资源的第一个响应。
contents.stop()
停止任何待处理的导航。
contents.reload()
刷新当前页面
contents.reloadIgnoringCache()
忽略缓存强制刷新页面
contents.canGoBack()
Deprecated
History
Version(s) | Changes |
---|---|
None | API DEPRECATED |
返回 boolean
- 浏览器是否可以后退到前一页面。
Deprecated: Should use the new contents.navigationHistory.canGoBack
API.
contents.canGoForward()
Deprecated
History
Version(s) | Changes |
---|---|
None | API DEPRECATED |
返回 boolean
- 浏览器是否可以前进到下一页面。
Deprecated: Should use the new contents.navigationHistory.canGoForward
API.
contents.canGoToOffset(offset)
Deprecated
History
Version(s) | Changes |
---|---|
None | API DEPRECATED |
offset
Integer
Returns boolean
- 浏览器是否可以跳转到 offset
页面。
Deprecated: Should use the new contents.navigationHistory.canGoToOffset
API.
contents.clearHistory()
Deprecated
History
Version(s) | Changes |
---|---|
None | API DEPRECATED |
清除浏览器导航历史记录
Deprecated: Should use the new contents.navigationHistory.clear
API.
contents.goBack()
Deprecated
History
Version(s) | Changes |
---|---|
None | API DEPRECATED |
使浏览器回退到上一个页面。
Deprecated: Should use the new contents.navigationHistory.goBack
API.
contents.goForward()
Deprecated
History
Version(s) | Changes |
---|---|
None | API DEPRECATED |
使浏览器前进到下一个页面。
Deprecated: Should use the new contents.navigationHistory.goForward
API.
contents.goToIndex(index)
Deprecated
History
Version(s) | Changes |
---|---|
None | API DEPRECATED |
index
Integer
将浏览器导航到指定的绝对页面索引。
Deprecated: Should use the new contents.navigationHistory.goToIndex
API.
contents.goToOffset(offset)
Deprecated
History
Version(s) | Changes |
---|---|
None | API DEPRECATED |
offset
Integer
定位到相对于“当前入口”的指定的偏移。
Deprecated: Should use the new contents.navigationHistory.goToOffset
API.
contents.isCrashed()
Returns boolean
- Whether the renderer process has crashed.
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
重写该页面的user agent
contents.getUserAgent()
返回 string
- 当前页面的 user agent。
contents.insertCSS(css[, options])
css
string
返回 Promise<string>
- 为插入css的promise,resolves 一个 key ,在这之后可以使用 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
string
Returns Promise<void>
- Resolves if the removal was successful.
Removes the inserted CSS from the current web page. 样式由 contents.insertCSS(css)
返回的 key 来标识。
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
。
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
。
在浏览器窗口中,一些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 的 world 的 ID,0
是默认 world,999
是 ElectroncontextIsolation
的 world 特征。 You can provide any integer here.scripts
WebSource[]userGesture
boolean (可选) - 默认为false
。
Returns Promise<any>
- A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise.
Works like executeJavaScript
but evaluates scripts
in an isolated context.
contents.setIgnoreMenuShortcuts(ignore)
ignore
boolean
在此有焦点的 web contents 中,忽略应用程序菜单快捷键。
contents.setWindowOpenHandler(handler)
-
handler
Function<WindowOpenHandlerResponse>details
Objecturl
string -window.open()
传入的 resolved 的URL。 例如,使用window.open('foo')
打开一个窗口,将产生类似值https://the-origin/the/current/path/foo
。frameName
string -window.open()
提供的窗口的名称。features
string -window.open()
提供 逗号 分割的窗口特征列表。disposition
string - Can bedefault
,foreground-tab
,background-tab
,new-window
orother
.referrer
Referrer - The referrer that will be passed to the new window. 可能会也可能不会发送Referer
头,取决于 referrer 策略。postBody
PostBody (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. 如果没有 post 数据被发送,值将为null
。 仅当窗口从 form 并设置target=_blank
时创建,才会被定义。
Returns
WindowOpenHandlerResponse
- When set to{ action: 'deny' }
cancels the creation of the new window.{ action: 'allow' }
将允许新窗口被创建。 返回无法识别的值 ,例如 null,undefined,或 一个没有 action 成员的对象, 控制同将输出错误,同时与返回{action: 'deny'}
效果相同。
渲染进程中请求创建一个新窗口之前被调用,例如 window.open()
, 带 target="_blank"
的链接,按shift 点击链接,或使用 <form target="_blank">
提交一个表单。 See window.open()
for more details and how to use this in conjunction with did-create-window
.
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
boolean
使当前页面音频静音
contents.isAudioMuted()
返回 boolean
- 页面是否被静音。
contents.isCurrentlyAudible()
返回 boolean
- 是否正在播放音频。
contents.setZoomFactor(factor)
factor
双倍缩放倍数;默认值为1.0。
更改缩放倍数。 缩放系数是缩放百分比除以 100,即 300% = 3.0。
系数必须大于0.0。
contents.getZoomFactor()
返回 number
- 当前的缩放比例。
contents.setZoomLevel(level)
level
number - 缩放等级。
更改缩放等级。 原始尺寸为 0,每升高或将顶代表缩放20%,大和小限制默认分区为 300% 和 50%。 The formula for this is scale := 1.2 ^ level
.
注意: Chromium 级别的缩放策略是同源的,这意味着特定域的缩放级别将传播到具有相同域的所有窗口实例。 区分窗口 URL 将使缩放操作工作在每一个窗口。
contents.getZoomLevel()
返回 number
- 当前的缩放等级。
contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevel
numbermaximumLevel
number
返回 Promise<void>
设置最大和最小缩放级别。
NOTE: 在 Electron 中 Visual 缩放 默认被禁止。 重新开启,调用:
const win = new BrowserWindow()
win.webContents.setVisualZoomLevelLimits(1, 3)
contents.undo()
在页面中执行undo
编辑命令。
contents.redo()
在页面中执行redo
编辑命令。
contents.cut()
在页面中执行cut
编辑命令。
contents.copy()
在页面中执行copy
编辑命令。
contents.centerSelection()
Centers the current text selection in web page.
contents.copyImageAt(x, y)
x
Integery
Integer
将给定位置的图像复制到剪贴板。
contents.paste()
在页面中执行paste
编辑命令。
contents.pasteAndMatchStyle()
在页面中执行pasteAndMatchStyle
编辑命令。
contents.delete()
在页面中执行delete
编辑命令。
contents.selectAll()
在页面中执行selectAll
编辑命令。
contents.unselect()
在页面中执行unselect
编辑命令。
contents.scrollToTop()
Scrolls to the top of the current webContents
.
contents.scrollToBottom()
Scrolls to the bottom of the current webContents
.
contents.adjustSelection(options)
选项
对象start
Number (optional) - Amount to shift the start index of the current selection.end
Number (optional) - Amount to shift the end index of the current selection.
Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document.
示例:
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
在页面中执行replace
编辑命令。
contents.replaceMisspelling(text)
text
string
在页面中执行replaceMisspelling
编辑命令。
contents.insertText(text)
text
string
返回 Promise<void>
插入text
到焦点元素
contents.findInPage(text[, options])
text
string - 要搜索的内容,必须非空。
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.
以提供的 action
停止 webContents
的任何 findInPage
。
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 (optional) - The area of the page to be captured.opts
Object (optional)stayHidden
boolean (可选) - 使页面保持隐藏而不是可见。 默认值为false
.stayAwake
boolean (可选) - 使系统保持唤醒状态,而不是让它处于睡眠状态。 默认值为false
.
Returns Promise<NativeImage>
- Resolves with a NativeImage
在 rect
内捕获页面的快照。 省略 rect
将捕获整个可见页面。 The page is considered visible when its browser window is hidden and the capturer count is non-zero. 如果你想要页面保持隐藏状态,则应确保 stayHidden
设置为 true。
contents.isBeingCaptured()
返回 boolean
- 是否页面正常捕获。 It returns true when the capturer count is greater than 0.
contents.getPrintersAsync()
获取系统打印机列表
Returns Promise<PrinterInfo[]>
- Resolves with a PrinterInfo[]
contents.print([options], [callback])
callback
Function (可选)success
boolean - 表示调用打印成功。failureReason
string - 如果打印失败,则回调错误说明。
当一个自定义 pageSize
被传入,Chromium 会尝试验证 width_microns
和 height_microns
指定平台的最小值。 宽度和高度必须都至少为 353 微米,但在某些操作系统上可能更高。
打印窗口的页面。 当 silent
设置为 true
,如果 deviceName
为空,Electron 将采用系统默认打印机,且使用默认设置打印。
使用 page-break-before: always;
CSS 样式强制打印到新页面。
示例:
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)
选项
对象landscape
boolean (optional) - Paper orientation.true
for landscape,false
for portrait. 默认值为 false.displayHeaderFooter
boolean (optional) - Whether to display header and footer. 默认值为 false.printBackground
boolean (optional) - Whether to print background graphics. 默认值为 false.scale
number(optional) - Scale of the webpage rendering. Defaults to 1.pageSize
string | Size (optional) - Specify page size of the generated PDF. Can beA0
,A1
,A2
,A3
,A4
,A5
,A6
,Legal
,Letter
,Tabloid
,Ledger
, or an Object containingheight
andwidth
in inches. 默认值为Letter
。margins
Object (可选)top
number (optional) - Top margin in inches. Defaults to 1cm (~0.4 inches).bottom
number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches).left
number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches).right
number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches).
pageRanges
string (optional) - Page ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.headerTemplate
string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them:date
(formatted print date),title
(document title),url
(document location),pageNumber
(current page number) andtotalPages
(total pages in the document). For example,<span class=title></span>
would generate span containing the title.footerTemplate
string (optional) - HTML template for the print footer. Should use the same format as theheaderTemplate
.preferCSSPageSize
boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.generateTaggedPDF
boolean (optional) Experimental - Whether or not to generate a tagged (accessible) PDF. 默认值为 false. As this property is experimental, the generated PDF may not adhere fully to PDF/UA and WCAG standards.generateDocumentOutline
boolean (optional) Experimental - Whether or not to generate a PDF document outline from content headers. 默认值为 false.
返回 Promise<Buffer>
- 使用生成 PDF 的数据解决。
Prints the window's web page as PDF.
如 @page
CSS 规则在页面使用,landscape
将被忽略。
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
添加指定的路径到 DevTools 工作区。 必须在 DevTools 创建后使用:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname)
})
contents.removeWorkSpace(path)
path
string
从 DevTools 工作区中删除指定的路径。
contents.setDevToolsWebContents(devToolsWebContents)
devToolsWebContents
WebContents
使用 devToolsWebContents
作为目标 WebContents
来显示 devtools。
devToolsWebContents
不得进行任何导航,并且在调用后不应该用于其它目的。
默认情况下,Electron 通过本地视频创建的内部 WebContents
来管理 devtools,开发者仅有有限地控制能力。 使用 setDevToolsWebContents
方便,开发者可以使用任何 WebContents
来显示其中的 devtools, 包括 BrowserWindow
, BrowserView
和 <webview>
tag.
注意: 关闭 devtools 不会销毁 devToolsWebContents
,销毁 devToolsWebContents
是调用方责任。
在 <webview>
标签中显示 devtools 示例:
<html>
<head>
<style type="text/css">
* { margin: 0; }
#browser { height: 70%; }
#devtools { height: 30%; }
</style>
</head>
<body>
<webview id="browser" src="https://github.com"></webview>
<webview id="devtools" src="about:blank"></webview>
<script>
const { ipcRenderer } = require('electron')
const emittedOnce = (element, eventName) => new Promise(resolve => {
element.addEventListener(eventName, event => resolve(event), { once: true })
})
const browserView = document.getElementById('browser')
const devtoolsView = document.getElementById('devtools')
const browserReady = emittedOnce(browserView, 'dom-ready')
const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready')
Promise.all([browserReady, devtoolsReady]).then(() => {
const targetId = browserView.getWebContentsId()
const devtoolsId = devtoolsView.getWebContentsId()
ipcRenderer.send('open-devtools', targetId, devtoolsId)
})
</script>
</body>
</html>
// Main process
const { ipcMain, webContents } = require('electron')
ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => {
const target = webContents.fromId(targetContentsId)
const devtools = webContents.fromId(devtoolsContentsId)
target.setDevToolsWebContents(devtools)
target.openDevTools()
})
在 BrowserWindow
中显示 devtools 示例:
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])
打开开发者工具。
当contents
是<webview>
标签时,mode
将默认detach
,显式传递空的mode
,可以强制使用上次的 dock state.
在 Windows 系统中, 如果 Windows Control Overlay 开启,Devtools 将使用 mode: 'detach'
模式打开.
contents.closeDevTools()
关闭开发者工具。
contents.isDevToolsOpened()
返回boolean
- 开发者工具是否处于开启状态。
contents.isDevToolsFocused()
返回boolean
- 开发者工具是否处于当前执行状态。
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()
切换开发工具
contents.inspectElement(x, y)
x
Integery
Integer
开始检查位于(x
, y
) 的元素。
contents.inspectSharedWorker()
以 shared worker 上下文打开开发者工具。
contents.inspectSharedWorkerById(workerId)
workerId
string
基于 shared worker 的 ID 检查。
contents.getAllSharedWorkers()
Returns SharedWorkerInfo[] - Information about all Shared Workers.
contents.inspectServiceWorker()
以 service worker 上下文打开开发者工具。
contents.send(channel, ...args)
channel
string...args
any[]
由经 channel
向渲染进程发送异步带参消息。 Arguments will be serialized with the Structured Clone Algorithm, just like postMessage
, so prototype chains will not be included. 发送 Functions, Promises, Symbols, WeakMaps, 或 WeakSets 将抛出异常
:::警告
注意:发送非标准JavaScript类型,例如DOM对象或特殊Electron对象,将抛出异常。
:::
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[]
通过 channel
发送一个带参数的异步消息到渲染进程里指定的 frame。 参数使用 Structured Clone Algorithm 序列化,就像 postMessage
,所以不包括原型链。 发送 Functions,Promises,Symbols,WeakMaps,或 WeakSets 将抛出异常。
注意: 发送非标准的 JavaScript 类型,如DOM 对象或特殊Electron 对象将会抛出异常。
The renderer process can handle the message by listening to channel
with the ipcRenderer
module.
如果你想要获取指定渲染进程上下文的 frameId
,应使用 webFrame.routingId
的值。 如下:
// In a renderer process
console.log('My frameId is:', require('electron').webFrame.routingId)
您也可以从主进程中所有传入的 IPC 消息中读取 frameId
。
// In the main process
ipcMain.on('ping', (event) => {
console.info('Message came from frameId:', event.frameId)
})
contents.postMessage(channel, message, [transfer])
channel
stringmessage
anytransfer
MessagePortMain[] (可选)
Send a message to the renderer process, optionally transferring ownership of zero or more MessagePortMain
objects.
被传递 MessagePortMain
对像,在渲染进程中可用来访问触发事件的 ports
属性。 当传入渲染进程,将转为 DOM 原生 MessagePort
对象。
例如:
// 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 - 指定要模拟的屏幕类型 (默认值:desktop
):desktop
- 桌面屏幕类型。mobile
- 移动设备屏幕类型。
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 - 设置设备的比例 (如果为默认0,则为原始设备比例) (默认:0
)。viewSize
Size - Set the emulated view size (empty means no override)scale
Float - 可用空间内被模拟视图的比例 (不适用视图模式) (默认:1
)。
允许设备模拟给定参数。
contents.disableDeviceEmulation()
禁止webContents.enableDeviceEmulation
允许的模拟设备
contents.sendInputEvent(inputEvent)
inputEvent
MouseInputEvent | MouseWheelInputEvent | KeyboardInputEvent
Sends an input event
to the page. Note: The BrowserWindow
containing the contents needs to be focused for sendInputEvent()
to work.
contents.beginFrameSubscription([onlyDirty ,]callback)
onlyDirty
boolean (可选) - 默认值为false
.callback
Functionimage
NativeImagedirtyRect
Rectangle
开始订阅展现事件,同时捕获帧数据,当有一个展现事件,callback
将使用 callback(image, dirtyRect)
被调用。
The image
is an instance of NativeImage that stores the captured frame.
dirtyRect
是一个带有 x, y, width, height
属性的对象,描述重绘的区域。 如果 onlyDirty
设置为 true
,image
仅包含重绘的区域。 onlyDirty
默认为 false
。
contents.endFrameSubscription()
结束订阅帧展示事件。
contents.startDrag(item)
item
Objectfile
string - 开始拖动的文件的路径。files
string[] (可选) - 开始拖动的文件数组。 (files
将被file
字段覆盖)icon
NativeImage | string - The image must be non-empty on macOS.
设置 item
作为当前的拖放操作项,file
是被拖拽文件的绝对路径,icon
是拖拽时显示在鼠标指针上的图像。
contents.savePage(fullPath, saveType)
fullPath
string - 绝对文件路径。saveType
string - 指定的保存类型。HTMLOnly
- 仅保存页面的 HTML。HTMLComplete
- 保存完全的 HTML 页面。MHTML
- 保存完全的 HTML 页面到 MHTML。
返回 Promise<void>
- 如果页面被保存,则解决。
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
- 是否启用_离屏渲染_ 。
contents.startPainting()
如果_离屏渲染_启用且没绘制,则开始绘制。
contents.stopPainting()
如果_离屏渲染_开启且正在绘制,则停止绘制。
contents.isPainting()
返回 boolean
- 如果_离屏渲染_启动,则返回当前是否在绘制。
contents.setFrameRate(fps)
fps
Integer
如果_离屏渲染_开启,则设置帧率为指定的数字。 仅接受介于 1 和 240 之间的值。
contents.getFrameRate()
返回 Integer
- 如果 离屏渲染 开启,返回当前帧率。
contents.invalidate()
安排 web contents 所在窗口的完整绘制。
如果_离屏渲染_ 启用,则使帧失效,同时通过 'paint'
事件生成新的帧。
contents.getWebRTCIPHandlingPolicy()
返回 string
- 返回 WebRTC IP 处理策略。
contents.setWebRTCIPHandlingPolicy(policy)
policy
string - 指定 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 处理策略,允许您控制哪些 IP 通过 WebRTC 暴露。 更多详细信息,请参阅 BrowserLeaks。
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. Note: To reset to an unrestricted port range this value should be set to { min: 0, max: 0 }
.
contents.getMediaSourceId(requestWebContents)
requestWebContents
WebContents - Id 注册到的 Web contents。
Returns string
- WebContents 流的标识。 标识可以被 navigator.mediaDevices.getUserMedia
利用 chromeMediaSource
r的 tab
来使用。 该标识局限于被注册的 web contents,且仅 10 秒有效。
contents.getOSProcessId()
返回 Integer
- 渲染进程关联的操作系统 pid
。
contents.getProcessId()
返回 Integer
- 渲染进程关联的 Chromium 内部pid
。 可以通过 frame 特定的导航事件来比较 frameProcessId
(例如 did-frame-navigate
)。
contents.takeHeapSnapshot(filePath)
filePath
string - 输出文件路径
返回 Promise<void>
- 指明快捷方式是否被成功创建。
获取V8堆快照并保存到 filePath
contents.getBackgroundThrottling()
返回 boolean
- 当页面置于后台时,此 WebContents 是否会限制动画和计时器。 这也会影响 Page Visibility API。
contents.setBackgroundThrottling(allowed)
History
allowed
boolean
控制当页面置于后台时,此 WebContents 是否会限制动画和计时器。 这也会影响 Page Visibility API。
contents.getType()
Returns string
- webContent 的类型。 可以是 backgroundPage
,window
,browserView
,remote
,webview
或 offscreen
。
contents.setImageAnimationPolicy(policy)
policy
string - 可以是animate
、animateOnce
或noAnimation
。
设置 webContents 的图片动画策略。 该策略仅影响_新_ 图片,当前活跃的已存在图片不受影响。 这是 Chromium 中的已知限制,您可以使用 img.src = img.src
强制图片重新计算,这结果就是没有网络请求但会更新动画策略。
这类似于,Chromium 中的辅助功能 animationPolicy。
实例属性
contents.ipc
只读
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
一个 boolean
属性,页面是否静音。
contents.userAgent
一个 string
属性,页面的 user agent。
contents.zoomLevel
一个 number
属性, web contents 的缩放等级。
原始尺寸为 0,每升高或将顶代表缩放20%,大和小限制默认分区为 300% 和 50%。 公式为 scale := 1.2 ^ level
。
contents.zoomFactor
一个 number
属性,web contents 的缩放系数。
缩放系数是缩放百分比除以 100,即 300% = 3.0。
contents.frameRate
一 Integer
属性,设置 web contents 的帧率为指定数字。 仅接受介于 1 和 240 之间的值。
仅适用,离屏渲染 启用。
contents.id
只读
Integer
类型,代表WebContents的唯一标识(unique ID)。 每个 ID 在整个 Electron 应用程序的 WebContents
实例中都是唯一的。
contents.session
只读
A Session
used by this webContents.
contents.navigationHistory
只读
A NavigationHistory
used by this webContents.
contents.hostWebContents
只读
A WebContents
instance that might own this WebContents
.
contents.devToolsWebContents
只读
一个 WebContents | null
属性,表示与指定 WebContents
相关联的 DevTools 的 WebContents
。
注意: 永远不应该存储此对象,因为当 DevTools 关闭时,它可能会 null
。
contents.debugger
只读
A Debugger
instance for this webContents.
contents.backgroundThrottling
History
一个 boolean
属性,当页面置于后台时,此 WebContents 是否会限制动画和计时器。 这也会影响 Page Visibility API。
contents.mainFrame
只读
A WebFrameMain
property that represents the top frame of the page's frame hierarchy.
contents.opener
只读
A WebFrameMain
property that represents the frame that opened this WebContents, either with open(), or by navigating a link with a target attribute.