网页内容 | webContents
呈现和控制网页。
Process: Main
webContents是一个EventEmitter。它负责渲染和控制网页,并且是该BrowserWindow对象的属性。访问该webContents对象的示例:
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 1500})
win.loadURL('http://github.com')
let contents = win.webContents
console.log(contents)方法
这些方法可以从webContents模块访问:
const {webContents} = require('electron')
console.log(webContents)webContents.getAllWebContents()
返回WebContents[]- 所有WebContents实例的数组。这将包含所有窗口,网页浏览,已打开的devtools和devtools扩展背景页面的网页内容。
webContents.getFocusedWebContents()
返回WebContents- 在此应用程序中关注的Web内容,否则返回null。
webContents.fromId(id)
id整数
返回WebContents- 具有给定ID的WebContents实例。
类:WebContents
渲染并控制BrowserWindow实例的内容。
过程:主
实例事件
Event: ‘did-finish-load’
导航完成onload时发出,即选项卡的旋转器已停止旋转,并且事件已发送。
Event: ‘did-fail-load’
返回:
eventEventerrorCodeIntegererrorDescriptionStringvalidatedURLStringisMainFrameBoolean
这个事件就像是did-finish-load在加载失败或被取消时发出的,例如window.stop()被调用。错误代码的完整列表及其含义可在此处找到。
Event: ‘did-frame-finish-load’
返回:
eventEventisMainFrameBoolean
当一个框架完成导航时发射。
Event: ‘did-start-loading’
对应于选项卡的旋转器开始旋转时的时间点。
Event: ‘did-stop-loading’
对应于标签的旋转器停止旋转的时间点。
Event: ‘did-get-response-details’
返回:
eventEventstatusBooleannewURLStringoriginalURLStringhttpResponseCodeIntegerrequestMethodStringreferrerStringheadersObjectresourceTypeString
当有关所请求资源的详细信息可用时发出。status指示下载资源的套接字连接。
Event: ‘did-get-redirect-request’
返回:
eventEventoldURLStringnewURLStringisMainFrameBooleanhttpResponseCodeIntegerrequestMethodStringreferrerStringheadersObject
在请求资源时收到重定向时发出。
Event: ‘dom-ready’
返回:
eventEvent
加载给定帧中的文档时发出。
Event: ‘page-favicon-updated’
返回:
eventEventfaviconsString[] - Array of URLs
网页收到图标网址时发送。
Event: ‘new-window’
返回:
event事件url串frameName串disposition字符串-可以是default,foreground-tab,background-tab,new-window,save-to-disk和other。options对象 - 将用于创建新的选项BrowserWindow。additionalFeatures字符串[] - 给予的非标准功能(未由Chromium或Electron处理的功能)window.open()。
当页面请求打开一个新的窗口时发出url。它可以通过window.open或外部链接请求<a target='_blank'>。
默认情况下,BrowserWindow将为该创建一个新的url。
调用event.preventDefault()将阻止Electron自动创建新的BrowserWindow。如果您调用event.preventDefault()并手动创建新的,BrowserWindow则必须设置event.newGuest为引用新BrowserWindow实例,否则可能会导致意外行为。例如:
myBrowserWindow.webContents.on('new-window', (event, url) => {
event.preventDefault()
const win = new BrowserWindow({show: false})
win.once('ready-to-show', () => win.show())
win.loadURL(url)
event.newGuest = win
})Event: ‘will-navigate’
返回:
eventEventurlString
当用户或页面想要开始导航时发射。当window.location对象发生更改或用户单击页面中的链接时可能会发生这种情况。
当导航以API webContents.loadURL和类似的API编程启动时,此事件不会发出webContents.back。
它也不会用于页内导航,例如单击锚链接或更新window.location.hash。 为此,请使用did-navigate-in-page事件。
调用event.preventDefault()将阻止导航。
Event: ‘did-navigate’
返回:
eventEventurlString
导航完成时发射。
此事件不是用于页内导航的,例如单击锚链接或更新window.location.hash。 为此,请使用did-navigate-in-page事件。
Event: ‘did-navigate-in-page’
返回:
eventEventurlStringisMainFrameBoolean
发生页内导航时发出。
当页内导航发生时,页面URL会发生变化,但不会导致页面外的导航。发生这种情况的例子是当锚点链接被点击或DOM hashchange事件被触发时。
Event: ‘will-prevent-unload’
返回:
eventEvent
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.showMessageBox(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()
}
})Event: ‘crashed’
返回:
eventEventkilledBoolean
渲染器进程崩溃或被杀时发出。
Event: ‘plugin-crashed’
返回:
eventEventnameStringversionString
插件进程崩溃时发出。
Event: ‘destroyed’
webContents被销毁时被发射。
Event: ‘before-input-event’
返回:
event事件input对象 - 输入属性type字符串 -keyUp或者keyDownkey字符串 - 相当于KeyboardEvent.keycode字符串 - 相当于KeyboardEvent.codeisAutoRepeat布尔值 - 等同于KeyboardEvent.repeatshift布尔值 - 等同于KeyboardEvent.shiftKeycontrol布尔值 - 相当于KeyboardEvent.controlKeyalt布尔值 - 等同于KeyboardEvent.altKeymeta布尔值 - 相当于KeyboardEvent.metaKey
分派前发射keydown和keyup活动页面。调用event.preventDefault将阻止页面keydown/ keyup事件和菜单快捷方式。
要仅禁止菜单快捷方式,请使用setIgnoreMenuShortcuts:
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 600})
win.webContents.on('before-input-event', (event, input) => {
// For example, only enable application menu keyboard shortcuts when
// Ctrl/Cmd are down.
win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta)
})Event: ‘devtools-opened’
DevTools打开时发出。
Event: ‘devtools-closed’
当DevTools关闭时发出。
Event: ‘devtools-focused’
在DevTools关注/打开时发出。
Event: ‘certificate-error’
返回:
event事件url串error字符串 - 错误代码certificate证书callback功能isTrusted布尔值 - 指示证书是否可以被视为可信
当无法验证发射certificate的url。
用法与certificate-error事件相同app。
Event: ‘select-client-certificate’
返回:
eventEventurlURLcertificateListCertificate[]callbackFunctioncertificateCertificate - Must be a certificate from the given list
在请求客户端证书时发送。
用法与app的select-client-certificate事件相同。
Event: ‘login’
返回:
eventEventrequestObjectmethodStringurlURLreferrerURL
authInfoObjectisProxyBooleanschemeStringhostStringportIntegerrealmString
callbackFunctionusernameStringpasswordString
在webContents想要进行基本身份验证时发出。
用法与app的登录事件相同。
Event: ‘found-in-page’
返回:
event事件result目的requestId整数activeMatchOrdinal整数 - 活动比赛的位置。matches整数 - 匹配数。selectionArea对象 - 第一个匹配区域的坐标。finalUpdate布尔
当结果可用于webContents.findInPage请求时发出。
Event: ‘media-started-playing’
媒体开始播放时发射。
Event: ‘media-paused’
媒体暂停播放或播放完毕时播放。
Event: ‘did-change-theme-color’
页面主题颜色改变时发出。这通常是由于遇到元标记:
<meta name='theme-color' content='#ff0000'>Event: ‘update-target-url’
返回:
eventEventurlString
鼠标移过链接或键盘将焦点移动到链接时发出。
Event: ‘cursor-changed’
返回:
eventEventtypeStringimageNativeImage (optional)scaleFloat (optional) - scaling factor for the custom cursorsizeSize (optional) - the size of theimagehotspotPoint (optional) - coordinates of the custom cursor’s hotspot
当游标类型改变时发射。所述type参数可以是default,crosshair,pointer,text,wait,help,e-resize,n-resize,ne-resize,nw-resize,s-resize,se-resize,sw-resize,w-resize,ns-resize,ew-resize,nesw-resize,nwse-resize,col-resize,row-resize,m-panning,e-panning,n-panning,ne-panning,nw-panning,s-panning,se-panning,sw-panning,w-panning,move,vertical-text,cell,context-menu,alias,progress,nodrop,copy,none,not-allowed,zoom-in,zoom-out,grab,grabbing,custom。
如果type参数是custom,该image参数将举行自定义光标图像中NativeImage,和scale,size以及hotspot将举行有关自定义光标的附加信息。
Event: ‘context-menu’
返回:
event事件params目的x整数 - x坐标y整数 - 并协调linkURL字符串 - 封装调用上下文菜单的节点的链接的URL。linkText字符串 - 与链接关联的文本。如果链接的内容是图像,可能是空字符串。pageURL字符串 - 调用上下文菜单的顶级页面的URL。frameURL字符串 - 调用上下文菜单的子帧的URL。srcURL字符串 - 调用上下文菜单的元素的源URL。包含来源网址的元素是图片,音频和视频。mediaTypeString - 上下文菜单被调用的节点的类型。可以none,image,audio,video,canvas,file或plugin。hasImageContentsBoolean - 在具有非空内容的图像上是否调用上下文菜单。isEditable布尔型 - 上下文是否可编辑。selectionText字符串 - 上下文菜单被调用的选择文本。titleText字符串 - 上下文被调用的选择的标题或替代文本。misspelledWord字符串 - 光标下的拼写错误的单词(如果有)。frameCharset字符串 - 调用菜单的框架的字符编码。inputFieldType字符串 - 如果上下文菜单在输入字段上被调用,则该字段的类型。可能的值是none,plainText,password,other。menuSourceType字符串 - 调用上下文菜单的输入源。可以none,mouse,keyboard,touch,touchMenu。mediaFlagsObject - 调用上下文菜单的media元素的标志。inError布尔值 - 媒体元素是否已崩溃。isPaused布尔值 - 媒体元素是否已暂停。isMuted布尔值 - 媒体元素是否被静音。hasAudio布尔值 - 媒体元素是否具有音频。isLooping布尔值 - 媒体元素是否正在循环。isControlsVisible布尔值 - 媒体元素的控件是否可见。canToggleControls布尔值 - 媒体元素的控件是否可切换。canRotate布尔值 - 媒体元素是否可以旋转。
- `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action.
- `canUndo` Boolean - Whether the renderer believes it can undo.
- `canRedo` Boolean - Whether the renderer believes it can redo.
- `canCut` Boolean - Whether the renderer believes it can cut.
- `canCopy` Boolean - Whether the renderer believes it can copy
- `canPaste` Boolean - Whether the renderer believes it can paste.
- `canDelete` Boolean - Whether the renderer believes it can delete.
- `canSelectAll` Boolean - Whether the renderer believes it can select all.当需要处理新的上下文菜单时发出。
Event: ‘select-bluetooth-device’
返回:
event事件devicesBluetoothDevice类[]callback功能deviceId串
在调用时需要选择蓝牙设备时发射navigator.bluetooth.requestDevice。应该启用使用navigator.bluetoothAPI webBluetooth。如果event.preventDefault未被调用,则将选择第一个可用设备。callback应该被调用deviceId来选择,传递空字符串callback将取消请求。
const {app, webContents} = require('electron')
app.commandLine.appendSwitch('enable-web-bluetooth')
app.on('ready', () => {
webContents.on('select-bluetooth-device', (event, deviceList, callback) => {
event.preventDefault()
let result = deviceList.find((device) => {
return device.deviceName === 'test'
})
if (!result) {
callback('')
} else {
callback(result.deviceId)
}
})
})Event: ‘paint’
返回:
eventEventdirtyRectRectangleimageNativeImage - The image data of the whole frame.
生成新帧时发射。只有脏区域被传入缓冲区。
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({webPreferences: {offscreen: true}})
win.webContents.on('paint', (event, dirty, image) => {
// updateBitmap(dirty, image.getBitmap())
})
win.loadURL('http://github.com')Event: ‘devtools-reload-page’
当devtools窗口指示webContents重新加载时发出
Event: ‘will-attach-webview’
返回:
event事件webPreferences对象 - 将由访客页面使用的Web首选项。可以修改此对象以调整访客页面的首选项。params对象 - 其他<webview>参数,如srcURL。可以修改此对象以调整访客页面的参数。
当<webview>网站内容附加到网站内容时发送。通话event.preventDefault()将破坏访客页面。
此事件可用于配置webPreferences的webContents的<webview>的加载在它之前,并提供了设置无法通过设置设置的功能<webview>属性。
注意:指定的preload脚本选项将显示为preloadURL(不preload)在webPreferences此事件发出的对象中。
实例方法
contents.loadURL(url[, options])
url串options对象(可选)httpReferrer字符串(可选) - HTTP引荐网址。userAgent字符串(可选) - 发起请求的用户代理。extraHeaders字符串(可选) - 额外的标题由“\ n”分隔postData(UploadRawData [] | UploadFile [] | UploadFileSystem [] | UploadBlob []) - (可选)baseURLForDataURL字符串(可选) - 基础URL(带尾随路径分隔符)用于由数据URL加载的文件。只有当指定的url是数据url并需要加载其他文件时,才需要此选项。
在窗口中加载网址。 该网址必须包含协议前缀,例如 http://或file://。 如果负载应该绕过http缓存,那么使用pragma头来实现它。
const {webContents} = require('electron')
const options = {extraHeaders: 'pragma: no-cache\n'}
webContents.loadURL('https://github.com', options)contents.downloadURL(url)
url串
在url无需导航的情况下启动资源下载。该will-download事件session将被触发。
contents.getURL()
返回String- 当前网页的URL。
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('http://github.com')
let currentURL = win.webContents.getURL()
console.log(currentURL)contents.getTitle()
返回String- 当前网页的标题。
contents.isDestroyed()
返回Boolean- 网页是否被销毁。
contents.focus()
专注于网页。
contents.isFocused()
返回Boolean- 网页是否关注。
contents.isLoading()
返回Boolean- 网页是否仍在加载资源。
contents.isLoadingMainFrame()
返回Boolean- 主框架(不仅仅是内部框架或框架中的框架)是否仍在加载。
contents.isWaitingForResponse()
返回Boolean- 网页是否正在等待来自页面主资源的第一个响应。
contents.stop()
停止任何挂起的导航。
contents.reload()
重新加载当前网页。
contents.reloadIgnoringCache()
重新加载当前页面并忽略缓存。
contents.canGoBack()
返回Boolean- 浏览器是否可以返回到之前的网页。
contents.canGoForward()
返回Boolean- 浏览器是否可以转到下一个网页。
contents.canGoToOffset(offset)
offsetInteger
返回Boolean- 网页是否可以进入offset。
contents.clearHistory()
清除导航历史记录。
contents.goBack()
使浏览器返回一个网页。
contents.goForward()
使浏览器前进一个网页。
contents.goToIndex(index)
indexInteger
将浏览器导航到指定的绝对网页索引。
contents.goToOffset(offset)
offsetInteger
导航到“当前条目”的指定偏移量。
contents.isCrashed()
返回Boolean- 渲染器进程是否崩溃。
contents.setUserAgent(userAgent)
userAgentString
覆盖此网页的用户代理。
contents.getUserAgent()
返回String- 此网页的用户代理。
contents.insertCSS(css)
cssString
将CSS注入当前网页。
contents.executeJavaScript(code[, userGesture, callback])
code串userGesture布尔(可选) - 默认是false。callback功能(可选) - 脚本执行后调用。result任何
返回Promise- 一种以执行代码的结果解决的承诺,或者如果代码的结果是被拒绝的承诺,则被拒绝。
code在页面中进行评估。
在浏览器窗口requestFullScreen中,只能通过用户的手势调用某些HTML API 。设置userGesture为true将删除此限制。
如果执行的代码的结果是promise,则回调结果将是promise的解析值。我们建议您使用返回的Promise来处理导致Promise的代码。
contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true)
.then((result) => {
console.log(result) // Will be the JSON object from the fetch call
})contents.setIgnoreMenuShortcuts(ignore) Experimental
ignoreBoolean
此Web内容的焦点时忽略应用程序菜单快捷方式。
contents.setAudioMuted(muted)
mutedBoolean
将当前网页上的音频静音。
contents.isAudioMuted()
返回Boolean- 此页面是否已被静音。
contents.setZoomFactor(factor)
factorNumber - Zoom factor.
将缩放系数更改为指定的系数。缩放系数是缩放百分比除以100,所以300%= 3.0。
contents.getZoomFactor(callback)
callbackFunctionzoomFactorNumber
发送请求以获取当前缩放因子,callback将会使用该参数调用callback(zoomFactor)。
contents.setZoomLevel(level)
levelNumber - Zoom level
将缩放级别更改为指定级别。原始大小为0,每个增量高于或低于分别代表缩小20%或更小,分别默认为原始大小的300%和50%。
contents.getZoomLevel(callback)
callbackFunctionzoomLevelNumber
发送请求以获取当前缩放级别,callback将会使用该级别调用callback(zoomLevel)。
contents.setZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevelNumbermaximumLevelNumber
弃用:setVisualZoomLevelLimits改为调用可视缩放级别限制。Electron 2.0将删除此方法。
contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevelNumbermaximumLevelNumber
设置最大和最小捏缩放级别。
contents.setLayoutZoomLevelLimits(minimumLevel, maximumLevel)
minimumLevelNumbermaximumLevelNumber
设置最大和最小布局(即非可视)缩放级别。
contents.undo()
执行undo网页中的编辑命令。
contents.redo()
执行redo网页中的编辑命令。
contents.cut()
执行cut网页中的编辑命令。
contents.copy()
执行copy网页中的编辑命令。
contents.copyImageAt(x, y)
xIntegeryInteger
将给定位置的图像复制到剪贴板。
contents.paste()
执行paste网页中的编辑命令。
contents.pasteAndMatchStyle()
执行pasteAndMatchStyle网页中的编辑命令。
contents.delete()
执行delete网页中的编辑命令。
contents.selectAll()
执行selectAll网页中的编辑命令。
contents.unselect()
执行unselect网页中的编辑命令。
contents.replace(text)
textString
执行replace网页中的编辑命令。
contents.replaceMisspelling(text)
textString
执行replaceMisspelling网页中的编辑命令。
contents.insertText(text)
textString
插入text到被聚焦的元素。
contents.findInPage(text[, options])
text字符串 - 要搜索的内容不能为空。options对象(可选)forward布尔值 - (可选)是向前还是向后搜索,默认值为true。findNext布尔值 - (可选)操作是第一次请求还是后续操作,默认为false。matchCase布尔值 - (可选)搜索是否区分大小写,默认为false。wordStart布尔 - (可选)是否仅查看单词的开头。默认为false。medialCapitalAsWordStart布尔值 - (可选)结合使用时wordStart,如果匹配以大写字母后跟小写字母或非字母开头,则接受单词中间的匹配。接受其他几个词内匹配,默认为false。
开始请求查找text网页中的所有匹配项,并返回一个Integer表示请求使用的请求ID。请求的结果可以通过订阅found-in-page事件来获得。
contents.stopFindInPage(action)
action字符串 - 指定结束webContents.findInPage请求时要执行的操作。clearSelection- 清除选择。keepSelection- 将选择转换为正常选择。activateSelection- 重点并单击选择节点。
使用提供的操作停止webContents的任何findInPage请求。
const {webContents} = require('electron')
webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
})
const requestId = webContents.findInPage('api')
console.log(requestId)contents.capturePage([rect, ]callback)
rect矩形(可选) - 要捕获的页面区域callback功能imageNativeImage
捕获内部页面的快照rect。完成callback后将被称为callback(image)。image是一个存储快照数据的NativeImage实例。省略rect将捕捉整个可见页面。
contents.hasServiceWorker(callback)
callback功能hasWorker布尔
检查是否有ServiceWorker注册并返回一个布尔值作为响应callback。
contents.unregisterServiceWorker(callback)
callback功能success布尔
取消注册任何ServiceWorker(如果存在),并返回一个布尔值作为对callbackJS承诺何时执行的响应,或当JS承诺被拒绝时返回false。
contents.getPrinters()
获取系统打印机列表。
返回 PrinterInfo[]
contents.print([options])
options对象(可选)silent布尔(可选) - 不要求用户进行打印设置。默认是false。printBackground布尔(可选) - 还打印网页的背景颜色和图像。默认是false。deviceName字符串(可选) - 设置要使用的打印机设备名称。默认是''。
打印窗口的网页。如果silent设置为true,Electron将选择系统的默认打印机(如果deviceName为空)以及打印的默认设置。
调用window.print()网页等同于调用webContents.print({silent: false, printBackground: false, deviceName: ''})。
使用page-break-before: always;CSS样式强制打印到新页面。
contents.printToPDF(options, callback)
options对象marginsType整数 - (可选)指定要使用的边距类型。默认边距使用0,无边距使用1,最小边距使用2。pageSize字符串 - (可选)指定生成的PDF的页面大小。可以A3,A4,A5,Legal,Letter,Tabloid或包含对象height,并width在微米。printBackground布尔值 - (可选)是否打印CSS背景。printSelectionOnly布尔值 - (可选)是否仅打印选择。landscape布尔 - (可选)true横向,false纵向。
callback功能error错误data缓冲
使用Chromium的预览打印自定义设置将窗口的网页打印为PDF。
回调将在回调(错误,数据)完成时调用。 数据是包含生成的PDF数据的缓冲区。
如果在网页中使用@page CSS at-rule,则该景观将被忽略。
默认情况下,空白options将被视为:
{
marginsType: 0,
printBackground: false,
printSelectionOnly: false,
landscape: false
}使用page-break-before: always;CSS样式强制打印到新页面。
一个webContents.printToPDF例子:
const {BrowserWindow} = require('electron')
const fs = require('fs')
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('http://github.com')
win.webContents.on('did-finish-load', () => {
// Use default printing options
win.webContents.printToPDF({}, (error, data) => {
if (error) throw error
fs.writeFile('/tmp/print.pdf', data, (error) => {
if (error) throw error
console.log('Write PDF successfully.')
})
})
})contents.addWorkSpace(path)
pathString
将指定的路径添加到DevTools工作区。必须在DevTools创建后使用:
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname)
})contents.removeWorkSpace(path)
pathString
从DevTools工作区中删除指定的路径。
contents.openDevTools([options])
options对象(可选)mode字符串-打开与指定的停靠状态devtools,可以是right,bottom,undocked,detach。默认为上次使用的码头状态。在undocked模式下可以停靠。在detach模式中不是。
打开devtools。
contents.closeDevTools()
关闭devtools。
contents.isDevToolsOpened()
返回Boolean- devtools是否被打开。
contents.isDevToolsFocused()
返回Boolean- devtools视图是否集中。
contents.toggleDevTools()
切换开发人员工具。
contents.inspectElement(x, y)
xIntegeryInteger
在位置(x,y)开始检查元素。
contents.inspectServiceWorker()
打开服务工作者上下文的开发人员工具。
contents.send(channel[, arg1][, arg2][, ...])
channelString...argsany[]
通过向渲染器进程发送异步消息channel,您还可以发送任意参数。参数将在JSON内部序列化,因此不会包含函数或原型链。
渲染过程可以通过监听处理消息channel与ipcRenderer模块。
从主进程向渲染进程发送消息的示例:
// In the main process.
const {app, BrowserWindow} = require('electron')
let win = null
app.on('ready', () => {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.on('did-finish-load', () => {
win.webContents.send('ping', 'whoooooooh!')
})
})<!-- index.html -->
<html>
<body>
<script>
require('electron').ipcRenderer.on('ping', (event, message) => {
console.log(message) // Prints 'whoooooooh!'
})
</script>
</body>
</html>contents.enableDeviceEmulation(parameters)
parameters对象screenPosition字符串-指定的屏幕类型效仿(默认值:desktop)desktop- 桌面屏幕类型mobile- 屏幕类型
- `screenSize` [Size](../structures/size/index) - Set the emulated screen size (screenPosition == mobile)
- `viewPosition` [Point](../structures/point/index) - 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](../structures/size/index) - Set the emulated view size (empty means no override)
- `fitToView` Boolean - Whether emulated view should be scaled down if necessary to fit into available space (default: `false`)
- `offset` [Point](../structures/point/index) - Offset of the emulated view inside available space (not in fit to view mode) (default: `{x: 0, y: 0}`)
- `scale` Float - Scale of emulated view inside available space (not in fit to view mode) (default: `1`)使用给定参数启用设备仿真。
contents.disableDeviceEmulation()
禁用启用的设备仿真webContents.enableDeviceEmulation。
contents.sendInputEvent(event)
event目的type串(所需) -的事件的类型,可以是mouseDown,mouseUp,mouseEnter,mouseLeave,contextMenu,mouseWheel,mouseMove,keyDown,keyUp,char。modifiers串[] -事件的改性剂组成的数组,可以包括shift,control,alt,meta,isKeypad,isAutoRepeat,leftButtonDown,middleButtonDown,rightButtonDown,capsLock,numLock,left,right。
将输入发送event到页面。注:本BrowserWindow包含内容需要集中的sendInputEvent()工作。
对于键盘事件,该event对象还具有以下属性:
keyCode字符串(必需) - 将作为键盘事件发送的字符。只应使用加速器中的有效密钥代码。
对于鼠标事件,该event对象还具有以下属性:
x整数(必需)y整数(必需)button字符串-按下按钮,可以left,middle,rightglobalX整数globalY整数movementX整数movementY整数clickCount整数
对于该mouseWheel事件,该event对象还具有以下属性:
deltaX整数deltaY整数wheelTicksX整数wheelTicksY整数accelerationRatioX整数accelerationRatioY整数hasPreciseScrollingDeltas布尔canScroll布尔
contents.beginFrameSubscription([onlyDirty ,]callback)
onlyDirty布尔(可选) - 默认为falsecallback功能frameBuffer缓冲dirtyRect长方形
开始订阅演示文稿事件和捕获的帧,当有演示事件时callback将被callback(frameBuffer, dirtyRect)调用。
这frameBuffer是一个Buffer包含原始像素数据。在大多数机器上,像素数据以32位BGRA格式有效存储,但实际表示取决于处理器的字节顺序(大多数现代处理器是小端,在具有高端处理器的机器上,数据采用32位ARGB格式) 。
dirtyRect是一个具有x,y,width,height属性的对象,用于描述页面的哪一部分已重新绘制。 如果仅将dirty设置为true,则frameBuffer将只包含重绘区域。 只有脏的默认值为false。
contents.endFrameSubscription()
结束订阅帧展示事件。
contents.startDrag(item)
item对象file字符串或files数组 - 被拖动的文件的路径。iconNativeImage - macOS上的图像必须是非空的。
设置item为当前拖放操作的拖动项目,file是要拖动的文件的绝对路径,拖动icon时显示在光标下的图像。
contents.savePage(fullPath, saveType, callback)
fullPath字符串 - 完整的文件路径。saveType字符串 - 指定保存类型。HTMLOnly- 只保存页面的HTML。HTMLComplete- 保存完整的HTML页面。MHTML- 将完整的html页面保存为MHTML。
callback功能 -(error) => {}。error错误
返回Boolean- 如果保存页面的过程已成功启动,则为true。
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.on('did-finish-load', () => {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete', (error) => {
if (!error) console.log('Save page successfully')
})
})contents.showDefinitionForSelection() macOS
显示用于搜索页面上所选单词的弹出式字典。
contents.setSize(options)
设置页面的大小。这仅适用于<webview>访客内容。
options目的normal对象(可选) - 页面的正常大小。这可以与该disableguestresize属性结合使用以手动调整webview客人内容的大小。width整数height整数
contents.isOffscreen()
返回Boolean- 指示是否启用离线渲染。
contents.startPainting()
如果离线渲染启用而不是绘画,请开始绘画。
contents.stopPainting()
如果屏幕外渲染已启用并且绘画,请停止绘画。
contents.isPainting()
返回Boolean- 如果启用了屏幕外渲染,则返回它是否正在绘制。
contents.setFrameRate(fps)
fpsInteger
如果启用了屏幕外渲染,则将帧速率设置为指定的数字。只有1到60之间的值才被接受。
contents.getFrameRate()
返回Integer- 如果启用了屏幕外渲染,则返回当前帧速率。
contents.invalidate()
计划对该网页内容所在的窗口进行完整重绘。
如果启用了屏幕外渲染,则会使该帧无效并通过该'paint'事件生成新的。
contents.getWebRTCIPHandlingPolicy()
返回String- 返回WebRTC IP处理策略。
contents.setWebRTCIPHandlingPolicy(policy)
policy字符串 - 指定WebRTC IP处理策略。default- 公开用户的公共和本地IP。这是默认行为。使用此策略时,WebRTC有权枚举所有接口并绑定它们以发现公共接口。default_public_interface_only- 公开用户的公共IP,但不公开用户的本地IP。使用此策略时,WebRTC应仅使用http使用的默认路由。这不会公开任何本地地址。default_public_and_private_interfaces- 公开用户的公共和本地IP。使用此策略时,WebRTC应仅使用http使用的默认路由。这也暴露了相关的默认私人地址。默认路由是OS在多宿主端点上选择的路由。disable_non_proxied_udp- 不公开或本地IP。使用此策略时,除非代理服务器支持UDP,否则WebRTC应仅使用TCP联系对等或服务器。
通过设置WebRTC IP处理策略,您可以控制哪些IP通过WebRTC公开。有关更多详细信息,请参阅BrowserLeaks。
contents.getOSProcessId()
返回Integer- pid关联的渲染器进程的。
实例属性
contents.id
Integer表示此WebContents的唯一ID。
contents.session
一个Session由此webContents使用的。
contents.hostWebContents
一个WebContents可能拥有这个的实例WebContents。
contents.devToolsWebContents
一个WebContentsDevTools为此WebContents。
注意:用户不应该存储这个对象,因为null当DevTools关闭时它可能会变成。
contents.debugger
此webContents的调试器实例。
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

