webContents
渲染和控制网页。
¥Render and control web pages.
进程:主进程
¥Process: Main
webContents 是 EventEmitter。它负责渲染和控制网页,是 BrowserWindow 对象的属性。访问 webContents 对象的示例:
¥webContents is an EventEmitter.
It is responsible for rendering and controlling a web page and is a property of
the BrowserWindow object. An example of accessing the
webContents object:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 1500 })
win.loadURL('https://github.com')
const contents = win.webContents
console.log(contents)
导航事件
¥Navigation Events
可以使用多个事件来监视 webContents 中发生的导航。
¥Several events can be used to monitor navigations as they occur within a webContents.
文档导航
¥Document Navigations
当 webContents 导航到另一个页面(与 页内导航 相对)时,将触发以下事件。
¥When a webContents navigates to another page (as opposed to an in-page navigation), the following events will be fired.
-
will-navigate(仅在主框架导航时触发)¥
will-navigate(only fired when main frame navigates) -
will-redirect(仅在导航期间发生重定向时触发)¥
will-redirect(only fired when a redirect happens during navigation) -
did-redirect-navigation(仅在导航期间发生重定向时触发)¥
did-redirect-navigation(only fired when a redirect happens during navigation) -
did-navigate(仅在主框架导航时触发)¥
did-navigate(only fired when main frame navigates)
如果对任何可取消事件调用 event.preventDefault(),则后续事件将不会触发。
¥Subsequent events will not fire if event.preventDefault() is called on any of the cancellable events.
页内导航
¥In-page Navigation
页内导航不会导致页面重新加载,而是导航到当前页面内的某个位置。这些活动不可取消。对于页内导航,将按此顺序触发以下事件:
¥In-page navigations don't cause the page to reload, but instead navigate to a location within the current page. These events are not cancellable. For an in-page navigations, the following events will fire in this order:
框架导航
¥Frame Navigation
will-navigate 和 did-navigate 事件仅在 mainFrame 导航时触发。如果你还想观察 <iframe> 中的导航,请使用 will-frame-navigate 和 did-frame-navigate 事件。
¥The will-navigate and did-navigate events only fire when the mainFrame navigates.
If you want to also observe navigations in <iframe>s, use will-frame-navigate and did-frame-navigate events.
方法
¥Methods
可以从 webContents 模块访问这些方法:
¥These methods can be accessed from the webContents module:
const { webContents } = require('electron')
console.log(webContents)
webContents.getAllWebContents()
返回 WebContents[] - 所有 WebContents 实例的数组。这将包含所有窗口、Web 视图、打开的 devtools 和 devtools 扩展背景页面的 Web 内容。
¥Returns WebContents[] - An array of all WebContents instances. This will contain web contents
for all windows, webviews, opened devtools, and devtools extension background pages.
webContents.getFocusedWebContents()
返回 WebContents | null - 该应用关注的网页内容,否则返回 null。
¥Returns WebContents | null - The web contents that is focused in this application, otherwise
returns null.
webContents.fromId(id)
-
id整数¥
idInteger
返回 WebContents | undefined - 具有给定 ID 的 WebContents 实例,如果没有与给定 ID 关联的 WebContents,则为 undefined。
¥Returns WebContents | undefined - A WebContents instance with the given ID, or
undefined if there is no WebContents associated with the given ID.
webContents.fromFrame(frame)
-
frameWeb 框架主¥
frameWebFrameMain
返回 WebContents | undefined - 具有给定 WebFrameMain 的 WebContents 实例,如果没有与给定 WebFrameMain 关联的 WebContents,则为 undefined。
¥Returns WebContents | undefined - A WebContents instance with the given WebFrameMain, or
undefined if there is no WebContents associated with the given WebFrameMain.
webContents.fromDevToolsTargetId(targetId)
-
targetId字符串 - 与 WebContents 实例关联的 Chrome DevTools 协议 目标 ID。¥
targetIdstring - The Chrome DevTools Protocol TargetID associated with the WebContents instance.
返回 WebContents | undefined - 具有给定 TargetID 的 WebContents 实例,如果没有与给定 TargetID 关联的 WebContents,则为 undefined。
¥Returns WebContents | undefined - A WebContents instance with the given TargetID, or
undefined if there is no WebContents associated with the given TargetID.
与 Chrome 开发者工具协议 通信时,根据分配的 TargetID 查找 WebContents 实例会很有用。
¥When communicating with the Chrome DevTools Protocol, it can be useful to lookup a WebContents instance based on its assigned TargetID.
async function lookupTargetId (browserWindow) {
const wc = browserWindow.webContents
await wc.debugger.attach('1.3')
const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo')
const { targetId } = targetInfo
const targetWebContents = await wc.fromDevToolsTargetId(targetId)
}
类:WebContents
¥Class: WebContents
渲染并控制 BrowserWindow 实例的内容。
¥Render and control the contents of a BrowserWindow instance.
进程:主进程
该类不是从 'electron' 模块导出的。它仅可用作 Electron API 中其他方法的返回值。
¥Process: Main
This class is not exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.
实例事件
¥Instance Events
事件:'did-finish-load'
¥Event: 'did-finish-load'
导航完成时发出,即选项卡的旋转器停止旋转,并且调度 onload 事件。
¥Emitted when the navigation is done, i.e. the spinner of the tab has stopped
spinning, and the onload event was dispatched.
事件:'did-fail-load'
¥Event: 'did-fail-load'
返回:
¥Returns:
-
event事件¥
eventEvent -
errorCode整数¥
errorCodeInteger -
errorDescription字符串¥
errorDescriptionstring -
validatedURL字符串¥
validatedURLstring -
isMainFrame布尔值¥
isMainFrameboolean -
frameProcessId整数¥
frameProcessIdInteger -
frameRoutingId整数¥
frameRoutingIdInteger
此事件类似于 did-finish-load,但在加载失败时发出。错误代码及其含义的完整列表可在 此处 中找到。
¥This event is like did-finish-load but emitted when the load failed.
The full list of error codes and their meaning is available here.
事件:'did-fail-provisional-load'
¥Event: 'did-fail-provisional-load'
返回:
¥Returns:
-
event事件¥
eventEvent -
errorCode整数¥
errorCodeInteger -
errorDescription字符串¥
errorDescriptionstring -
validatedURL字符串¥
validatedURLstring -
isMainFrame布尔值¥
isMainFrameboolean -
frameProcessId整数¥
frameProcessIdInteger -
frameRoutingId整数¥
frameRoutingIdInteger
该事件类似于 did-fail-load,但在取消加载时发出(例如调用 window.stop())。
¥This event is like did-fail-load but emitted when the load was cancelled
(e.g. window.stop() was invoked).
事件:'did-frame-finish-load'
¥Event: 'did-frame-finish-load'
返回:
¥Returns:
-
event事件¥
eventEvent -
isMainFrame布尔值¥
isMainFrameboolean -
frameProcessId整数¥
frameProcessIdInteger -
frameRoutingId整数¥
frameRoutingIdInteger
当框架完成导航时发出。
¥Emitted when a frame has done navigation.
事件:'did-start-loading'
¥Event: 'did-start-loading'
对应于选项卡的旋转器开始旋转的时间点。
¥Corresponds to the points in time when the spinner of the tab started spinning.
事件:'did-stop-loading'
¥Event: 'did-stop-loading'
对应于选项卡的旋转器停止旋转的时间点。
¥Corresponds to the points in time when the spinner of the tab stopped spinning.
事件:'dom-ready'
¥Event: 'dom-ready'
当加载顶层框架中的文档时发出。
¥Emitted when the document in the top-level frame is loaded.
事件:'page-title-updated'
¥Event: 'page-title-updated'
返回:
¥Returns:
-
event事件¥
eventEvent -
title字符串¥
titlestring -
explicitSet布尔值¥
explicitSetboolean
在导航期间设置页面标题时触发。当标题是从文件 url 合成时,explicitSet 为 false。
¥Fired when page title is set during navigation. explicitSet is false when
title is synthesized from file url.
事件:'page-favicon-updated'
¥Event: 'page-favicon-updated'
返回:
¥Returns:
-
event事件¥
eventEvent -
favicons字符串[] - URL 数组。¥
faviconsstring[] - Array of URLs.
当页面收到 favicon url 时发出。
¥Emitted when page receives favicon urls.
事件:'content-bounds-updated'
¥Event: 'content-bounds-updated'
返回:
¥Returns:
当页面调用 window.moveTo、window.resizeTo 或相关 API 时发出。
¥Emitted when the page calls window.moveTo, window.resizeTo or related APIs.
默认情况下,这将移动窗口。为了防止这种行为,请致电 event.preventDefault()。
¥By default, this will move the window. To prevent that behavior, call
event.preventDefault().
事件:'did-create-window'
¥Event: 'did-create-window'
返回:
¥Returns:
-
windowBrowserWindow -
details对象¥
detailsObject-
url字符串 - 创建的窗口的 URL。¥
urlstring - URL for the created window. -
frameName字符串 - 在window.open()调用中为创建的窗口指定的名称。¥
frameNamestring - Name given to the created window in thewindow.open()call. -
referrer推荐人 - 将传递到新窗口的引荐来源网址。可能会也可能不会导致发送Referer标头,具体取决于引荐来源网址策略。¥
referrerReferrer - The referrer that will be passed to the new window. May or may not result in theRefererheader being sent, depending on the referrer policy. -
postBodyPostBody(可选) - 将发送到新窗口的发布数据以及将设置的适当标头。如果不发送 post 数据,则该值为null。仅当窗口由设置target=_blank的表单创建时才定义。¥
postBodyPostBody (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will benull. Only defined when the window is being created by a form that settarget=_blank. -
disposition字符串 - 可以是default、foreground-tab、background-tab、new-window或other。¥
dispositionstring - Can bedefault,foreground-tab,background-tab,new-windoworother.
-
在渲染器中通过 window.open 成功创建窗口后发出。如果从 webContents.setWindowOpenHandler 取消窗口的创建,则不会发出。
¥Emitted after successful creation of a window via window.open in the renderer.
Not emitted if the creation of the window is canceled from
webContents.setWindowOpenHandler.
有关更多详细信息以及如何将其与 webContents.setWindowOpenHandler 结合使用,请参阅 window.open()。
¥See window.open() for more details and how to use this in conjunction with webContents.setWindowOpenHandler.
事件:'will-navigate'
¥Event: 'will-navigate'
返回:
¥Returns:
-
details事件<>¥
detailsEvent<>-
url字符串 - 框架导航到的 URL。¥
urlstring - The URL the frame is navigating to. -
isSameDocument布尔值 - 使用 window.history api 和参考片段导航的相同文档导航不会触发此事件。对于此事件,此属性始终设置为false。¥
isSameDocumentboolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set tofalsefor this event. -
isMainFrame布尔值 - 如果导航发生在主框架中,则为 true。¥
isMainFrameboolean - True if the navigation is taking place in a main frame. -
frameWebFrameMain | null - 要导航的框架。如果在框架导航或被销毁后访问,则可能是null。¥
frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed. -
initiatorWebFrameMain | null(可选) - 发起导航的框架,可以是父框架(例如,通过带有框架名称的window.open),如果导航不是由框架发起的,则为 null。如果在事件发出之前删除了启动帧,则该值也可以为 null。¥
initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith 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字符串 已弃用¥
urlstring Deprecated -
isInPlace布尔值 已弃用¥
isInPlaceboolean Deprecated -
isMainFrame布尔值 已弃用¥
isMainFrameboolean Deprecated -
frameProcessId整数 已弃用¥
frameProcessIdInteger Deprecated -
frameRoutingId整数 已弃用¥
frameRoutingIdInteger Deprecated
当用户或页面想要在主框架上开始导航时发出。当 window.location 对象更改或用户单击页面中的链接时,可能会发生这种情况。
¥Emitted when a user or the page wants to start navigation on the main frame. It can happen when
the window.location object is changed or a user clicks a link in the page.
当使用 webContents.loadURL 和 webContents.back 等 API 以编程方式启动导航时,不会发出此事件。
¥This event will not emit when the navigation is started programmatically with
APIs like webContents.loadURL and webContents.back.
页面内导航也不会发出它,例如单击锚链接或更新 window.location.hash。为此目的使用 did-navigate-in-page 事件。
¥It is also not emitted for in-page navigations, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
调用 event.preventDefault() 将阻止导航。
¥Calling event.preventDefault() will prevent the navigation.
事件:'will-frame-navigate'
¥Event: 'will-frame-navigate'
返回:
¥Returns:
-
details事件<>¥
detailsEvent<>-
url字符串 - 框架导航到的 URL。¥
urlstring - The URL the frame is navigating to. -
isSameDocument布尔值 - 使用 window.history api 和参考片段导航的相同文档导航不会触发此事件。对于此事件,此属性始终设置为false。¥
isSameDocumentboolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set tofalsefor this event. -
isMainFrame布尔值 - 如果导航发生在主框架中,则为 true。¥
isMainFrameboolean - True if the navigation is taking place in a main frame. -
frameWebFrameMain | null - 要导航的框架。如果在框架导航或被销毁后访问,则可能是null。¥
frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed. -
initiatorWebFrameMain | null(可选) - 发起导航的框架,可以是父框架(例如,通过带有框架名称的window.open),如果导航不是由框架发起的,则为 null。如果在事件发出之前删除了启动帧,则该值也可以为 null。¥
initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith 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.
-
当用户或页面想要在任何框架中开始导航时发出。当 window.location 对象更改或用户单击页面中的链接时,可能会发生这种情况。
¥Emitted when a user or the page wants to start navigation in any frame. It can happen when
the window.location object is changed or a user clicks a link in the page.
与 will-navigate 不同,当主框架或其任何子框架尝试导航时,会触发 will-frame-navigate。当导航事件来自主框架时,isMainFrame 将是 true。
¥Unlike will-navigate, will-frame-navigate is fired when the main frame or any of its subframes attempts to navigate. When the navigation event comes from the main frame, isMainFrame will be true.
当使用 webContents.loadURL 和 webContents.back 等 API 以编程方式启动导航时,不会发出此事件。
¥This event will not emit when the navigation is started programmatically with
APIs like webContents.loadURL and webContents.back.
页面内导航也不会发出它,例如单击锚链接或更新 window.location.hash。为此目的使用 did-navigate-in-page 事件。
¥It is also not emitted for in-page navigations, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
调用 event.preventDefault() 将阻止导航。
¥Calling event.preventDefault() will prevent the navigation.
事件:'did-start-navigation'
¥Event: 'did-start-navigation'
返回:
¥Returns:
-
details事件<>¥
detailsEvent<>-
url字符串 - 框架导航到的 URL。¥
urlstring - The URL the frame is navigating to. -
isSameDocument布尔值 - 是否在不更改文档的情况下进行导航。相同文档导航的示例包括参考片段导航、pushState/replaceState 和相同页面历史记录导航。¥
isSameDocumentboolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. -
isMainFrame布尔值 - 如果导航发生在主框架中,则为 true。¥
isMainFrameboolean - True if the navigation is taking place in a main frame. -
frameWebFrameMain | null - 要导航的框架。如果在框架导航或被销毁后访问,则可能是null。¥
frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed. -
initiatorWebFrameMain | null(可选) - 发起导航的框架,可以是父框架(例如,通过带有框架名称的window.open),如果导航不是由框架发起的,则为 null。如果在事件发出之前删除了启动帧,则该值也可以为 null。¥
initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith 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字符串 已弃用¥
urlstring Deprecated -
isInPlace布尔值 已弃用¥
isInPlaceboolean Deprecated -
isMainFrame布尔值 已弃用¥
isMainFrameboolean Deprecated -
frameProcessId整数 已弃用¥
frameProcessIdInteger Deprecated -
frameRoutingId整数 已弃用¥
frameRoutingIdInteger Deprecated
当任何框架(包括主框架)开始导航时发出。
¥Emitted when any frame (including main) starts navigating.
事件:'will-redirect'
¥Event: 'will-redirect'
返回:
¥Returns:
-
details事件<>¥
detailsEvent<>-
url字符串 - 框架导航到的 URL。¥
urlstring - The URL the frame is navigating to. -
isSameDocument布尔值 - 是否在不更改文档的情况下进行导航。相同文档导航的示例包括参考片段导航、pushState/replaceState 和相同页面历史记录导航。¥
isSameDocumentboolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. -
isMainFrame布尔值 - 如果导航发生在主框架中,则为 true。¥
isMainFrameboolean - True if the navigation is taking place in a main frame. -
frameWebFrameMain | null - 要导航的框架。如果在框架导航或被销毁后访问,则可能是null。¥
frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed. -
initiatorWebFrameMain | null(可选) - 发起导航的框架,可以是父框架(例如,通过带有框架名称的window.open),如果导航不是由框架发起的,则为 null。如果在事件发出之前删除了启动帧,则该值也可以为 null。¥
initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith 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字符串 已弃用¥
urlstring Deprecated -
isInPlace布尔值 已弃用¥
isInPlaceboolean Deprecated -
isMainFrame布尔值 已弃用¥
isMainFrameboolean Deprecated -
frameProcessId整数 已弃用¥
frameProcessIdInteger Deprecated -
frameRoutingId整数 已弃用¥
frameRoutingIdInteger Deprecated
当导航期间发生服务器端重定向时发出。例如 302 重定向。
¥Emitted when a server side redirect occurs during navigation. For example a 302 redirect.
对于同一导航,此事件将在 did-start-navigation 之后且始终在 did-redirect-navigation 事件之前发出。
¥This event will be emitted after did-start-navigation and always before the
did-redirect-navigation event for the same navigation.
调用 event.preventDefault() 将阻止导航(而不仅仅是重定向)。
¥Calling event.preventDefault() will prevent the navigation (not just the
redirect).
事件:'did-redirect-navigation'
¥Event: 'did-redirect-navigation'
返回:
¥Returns:
-
details事件<>¥
detailsEvent<>-
url字符串 - 框架导航到的 URL。¥
urlstring - The URL the frame is navigating to. -
isSameDocument布尔值 - 是否在不更改文档的情况下进行导航。相同文档导航的示例包括参考片段导航、pushState/replaceState 和相同页面历史记录导航。¥
isSameDocumentboolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment navigations, pushState/replaceState, and same page history navigation. -
isMainFrame布尔值 - 如果导航发生在主框架中,则为 true。¥
isMainFrameboolean - True if the navigation is taking place in a main frame. -
frameWebFrameMain | null - 要导航的框架。如果在框架导航或被销毁后访问,则可能是null。¥
frameWebFrameMain | null - The frame to be navigated. May benullif accessed after the frame has either navigated or been destroyed. -
initiatorWebFrameMain | null(可选) - 发起导航的框架,可以是父框架(例如,通过带有框架名称的window.open),如果导航不是由框架发起的,则为 null。如果在事件发出之前删除了启动帧,则该值也可以为 null。¥
initiatorWebFrameMain | null (optional) - The frame which initiated the navigation, which can be a parent frame (e.g. viawindow.openwith 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字符串 已弃用¥
urlstring Deprecated -
isInPlace布尔值 已弃用¥
isInPlaceboolean Deprecated -
isMainFrame布尔值 已弃用¥
isMainFrameboolean Deprecated -
frameProcessId整数 已弃用¥
frameProcessIdInteger Deprecated -
frameRoutingId整数 已弃用¥
frameRoutingIdInteger Deprecated
在导航期间发生服务器端重定向后发出。例如 302 重定向。
¥Emitted after a server side redirect occurs during navigation. For example a 302 redirect.
此事件无法阻止,如果你想阻止重定向,你应该查看上面的 will-redirect 事件。
¥This event cannot be prevented, if you want to prevent redirects you should
checkout out the will-redirect event above.
事件:'did-navigate'
¥Event: 'did-navigate'
返回:
¥Returns:
-
event事件¥
eventEvent -
url字符串¥
urlstring -
httpResponseCode整数 - -1 表示非 HTTP 导航¥
httpResponseCodeInteger - -1 for non HTTP navigations -
httpStatusText字符串 - 对于非 HTTP 导航为空¥
httpStatusTextstring - empty for non HTTP navigations
当主框架导航完成时发出。
¥Emitted when a main frame navigation is done.
页面内导航不会发出此事件,例如单击锚链接或更新 window.location.hash。为此目的使用 did-navigate-in-page 事件。
¥This event is not emitted for in-page navigations, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
事件:'did-frame-navigate'
¥Event: 'did-frame-navigate'
返回:
¥Returns:
-
event事件¥
eventEvent -
url字符串¥
urlstring -
httpResponseCode整数 - -1 表示非 HTTP 导航¥
httpResponseCodeInteger - -1 for non HTTP navigations -
httpStatusText字符串 - 对于非 HTTP 导航为空,¥
httpStatusTextstring - empty for non HTTP navigations, -
isMainFrame布尔值¥
isMainFrameboolean -
frameProcessId整数¥
frameProcessIdInteger -
frameRoutingId整数¥
frameRoutingIdInteger
当任何帧导航完成时发出。
¥Emitted when any frame navigation is done.
页面内导航不会发出此事件,例如单击锚链接或更新 window.location.hash。为此目的使用 did-navigate-in-page 事件。
¥This event is not emitted for in-page navigations, such as clicking anchor links
or updating the window.location.hash. Use did-navigate-in-page event for
this purpose.
事件:'did-navigate-in-page'
¥Event: 'did-navigate-in-page'
返回:
¥Returns:
-
event事件¥
eventEvent -
url字符串¥
urlstring -
isMainFrame布尔值¥
isMainFrameboolean -
frameProcessId整数¥
frameProcessIdInteger -
frameRoutingId整数¥
frameRoutingIdInteger
当任何框架中发生页内导航时发出。
¥Emitted when an in-page navigation happened in any frame.
当发生页内导航时,页面 URL 发生变化,但不会导致页外导航。发生这种情况的示例包括单击锚链接或触发 DOM hashchange 事件时。
¥When in-page navigation happens, the page URL changes but does not cause
navigation outside of the page. Examples of this occurring are when anchor links
are clicked or when the DOM hashchange event is triggered.
事件:'will-prevent-unload'
¥Event: 'will-prevent-unload'
返回:
¥Returns:
-
event事件¥
eventEvent
当 beforeunload 事件处理程序尝试取消页面卸载时发出。
¥Emitted when a beforeunload event handler is attempting to cancel a page unload.
调用 event.preventDefault() 将忽略 beforeunload 事件处理程序并允许卸载页面。
¥Calling event.preventDefault() will ignore the beforeunload event handler
and allow the page to be unloaded.
const { BrowserWindow, dialog } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('will-prevent-unload', (event) => {
const choice = dialog.showMessageBoxSync(win, {
type: 'question',
buttons: ['Leave', 'Stay'],
title: 'Do you want to leave this site?',
message: 'Changes you made may not be saved.',
defaultId: 0,
cancelId: 1
})
const leave = (choice === 0)
if (leave) {
event.preventDefault()
}
})
[!NOTE] 这将针对
BrowserViews发出,但不会被遵守。 - 这是因为我们选择不将BrowserView生命周期与其所属的 BrowserWindow 绑定在一起(如果 specification 存在一个生命周期)。¥[!NOTE] This will be emitted for
BrowserViewsbut will not be respected - this is because we have chosen not to tie theBrowserViewlifecycle to its owning BrowserWindow should one exist per the specification.
事件:'render-process-gone'
¥Event: 'render-process-gone'
返回:
¥Returns:
-
event事件¥
eventEvent -
details渲染进程消失详细信息¥
detailsRenderProcessGoneDetails
当渲染器进程意外消失时发出。这通常是因为它坠毁或死亡。
¥Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed.
事件:'unresponsive'
¥Event: 'unresponsive'
当网页变得无响应时发出。
¥Emitted when the web page becomes unresponsive.
事件:'responsive'
¥Event: 'responsive'
当无响应的网页再次响应时发出。
¥Emitted when the unresponsive web page becomes responsive again.
事件:'destroyed'
¥Event: 'destroyed'
当 webContents 被销毁时发出。
¥Emitted when webContents is destroyed.
事件:'input-event'
¥Event: 'input-event'
返回:
¥Returns:
-
event事件¥
eventEvent -
inputEventInputEvent
当输入事件发送到 WebContents 时发出。详情请参见 InputEvent。
¥Emitted when an input event is sent to the WebContents. See InputEvent for details.
事件:'before-input-event'
¥Event: 'before-input-event'
返回:
¥Returns:
-
event事件¥
eventEvent -
input对象 - 输入属性。¥
inputObject - Input properties.-
type字符串 -keyUp或keyDown。¥
typestring - EitherkeyUporkeyDown. -
key字符串 - 相当于 KeyboardEvent.key。¥
keystring - Equivalent to KeyboardEvent.key. -
code字符串 - 相当于 KeyboardEvent.code。¥
codestring - Equivalent to KeyboardEvent.code. -
isAutoRepeat布尔值 - 相当于 KeyboardEvent.repeat。¥
isAutoRepeatboolean - Equivalent to KeyboardEvent.repeat. -
isComposing布尔值 - 相当于 KeyboardEvent.isComposing。¥
isComposingboolean - Equivalent to KeyboardEvent.isComposing. -
shift布尔值 - 相当于 KeyboardEvent.shiftKey。¥
shiftboolean - Equivalent to KeyboardEvent.shiftKey. -
control布尔值 - 相当于 KeyboardEvent.controlKey。¥
controlboolean - Equivalent to KeyboardEvent.controlKey. -
alt布尔值 - 相当于 KeyboardEvent.altKey。¥
altboolean - Equivalent to KeyboardEvent.altKey. -
meta布尔值 - 相当于 KeyboardEvent.metaKey。¥
metaboolean - Equivalent to KeyboardEvent.metaKey. -
location数字 - 相当于 KeyboardEvent.location。¥
locationnumber - Equivalent to KeyboardEvent.location. -
modifiers字符串[] - 参见 InputEvent.modifiers。¥
modifiersstring[] - See InputEvent.modifiers.
-
在分派页面中的 keydown 和 keyup 事件之前发出。调用 event.preventDefault 将阻止页面 keydown/keyup 事件和菜单快捷方式。
¥Emitted before dispatching the keydown and keyup events in the page.
Calling event.preventDefault will prevent the page keydown/keyup events
and the menu shortcuts.
要仅阻止菜单快捷方式,请使用 setIgnoreMenuShortcuts:
¥To only prevent the menu shortcuts, use
setIgnoreMenuShortcuts:
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-input-event', (event, input) => {
// Enable application menu keyboard shortcuts when Ctrl/Cmd are down.
win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta)
})
})
事件:'before-mouse-event'
¥Event: 'before-mouse-event'
返回:
¥Returns:
-
event事件¥
eventEvent -
mouse鼠标输入事件¥
mouseMouseInputEvent
在页面中调度鼠标事件之前发出。
¥Emitted before dispatching mouse events in the page.
调用 event.preventDefault 将阻止页面鼠标事件。
¥Calling event.preventDefault will prevent the page mouse events.
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 800, height: 600 })
win.webContents.on('before-mouse-event', (event, mouse) => {
// Prevent mouseDown events.
if (mouse.type === 'mouseDown') {
console.log(mouse)
/*
{
type: 'mouseDown',
clickCount: 1,
movementX: 0,
movementY: 0,
button: 'left',
x: 632.359375,
y: 480.6875,
globalX: 168.359375,
globalY: 193.6875
}
*/
event.preventDefault()
}
})
})
事件:'enter-html-full-screen'
¥Event: 'enter-html-full-screen'
当窗口进入由 HTML API 触发的全屏状态时发出。
¥Emitted when the window enters a full-screen state triggered by HTML API.
事件:'leave-html-full-screen'
¥Event: 'leave-html-full-screen'
当窗口离开由 HTML API 触发的全屏状态时发出。
¥Emitted when the window leaves a full-screen state triggered by HTML API.
事件:'zoom-changed'
¥Event: 'zoom-changed'
返回:
¥Returns:
-
event事件¥
eventEvent -
zoomDirection字符串 - 可以是in或out。¥
zoomDirectionstring - Can beinorout.
当用户请求使用鼠标滚轮更改缩放级别时发出。
¥Emitted when the user is requesting to change the zoom level using the mouse wheel.
事件:'blur'
¥Event: 'blur'
当 WebContents 失去焦点时发出。
¥Emitted when the WebContents loses focus.
事件:'focus'
¥Event: 'focus'
当 WebContents 获得焦点时发出。
¥Emitted when the WebContents gains focus.
请注意,在 macOS 上,获得焦点意味着 WebContents 是窗口的第一响应者,因此在窗口之间切换焦点不会触发 WebContents 的 focus 和 blur 事件,因为每个窗口的第一响应者都不会改变。
¥Note that on macOS, having focus means the WebContents is the first responder
of window, so switching focus between windows would not trigger the focus and
blur events of WebContents, as the first responder of each window is not
changed.
WebContents 的 focus 和 blur 事件只能用于检测同一窗口中不同 WebContents 和 BrowserView 之间的焦点变化。
¥The focus and blur events of WebContents should only be used to detect
focus change between different WebContents and BrowserView in the same
window.
事件:'devtools-open-url'
¥Event: 'devtools-open-url'
返回:
¥Returns:
-
event事件¥
eventEvent -
url字符串 - 单击或选择的链接的 URL。¥
urlstring - URL of the link that was clicked or selected.
在 DevTools 中单击链接或在其上下文菜单中为链接选择 '在新选项卡中打开' 时发出。
¥Emitted when a link is clicked in DevTools or 'Open in new tab' is selected for a link in its context menu.
事件:'devtools-search-query'
¥Event: 'devtools-search-query'
返回:
¥Returns:
-
event事件¥
eventEvent -
query字符串 - 要查询的文本。¥
querystring - text to query for.
当在上下文菜单中选择 '搜索' 作为文本时发出。
¥Emitted when 'Search' is selected for text in its context menu.
事件:'devtools-opened'
¥Event: 'devtools-opened'
打开 DevTools 时发出。
¥Emitted when DevTools is opened.
事件:'devtools-closed'
¥Event: 'devtools-closed'
当 DevTools 关闭时发出。
¥Emitted when DevTools is closed.
事件:'devtools-focused'
¥Event: 'devtools-focused'
当 DevTools 聚焦/打开时发出。
¥Emitted when DevTools is focused / opened.
事件:'certificate-error'
¥Event: 'certificate-error'
返回:
¥Returns:
-
event事件¥
eventEvent -
url字符串¥
urlstring -
error字符串 - 错误代码。¥
errorstring - The error code. -
certificate证书¥
certificateCertificate -
callback函数¥
callbackFunction-
isTrusted布尔值 - 指示证书是否可以被视为可信。¥
isTrustedboolean - Indicates whether the certificate can be considered trusted.
-
-
isMainFrame布尔值¥
isMainFrameboolean
当无法验证 certificate 和 url 时发出。
¥Emitted when failed to verify the certificate for url.
用法与 app 的 certificate-error 事件 相同。
¥The usage is the same with the certificate-error event of app.
事件:'select-client-certificate'
¥Event: 'select-client-certificate'
返回:
¥Returns:
-
event事件¥
eventEvent -
urlURL -
certificateListCertificate[] -
callback函数¥
callbackFunction-
certificate证书 - 必须是给定列表中的证书。¥
certificateCertificate - Must be a certificate from the given list.
-
请求客户端证书时发出。
¥Emitted when a client certificate is requested.
用法与 app 的 select-client-certificate 事件 相同。
¥The usage is the same with the select-client-certificate event of app.
事件:'login'
¥Event: 'login'
返回:
¥Returns:
-
event事件¥
eventEvent -
authenticationResponseDetails对象¥
authenticationResponseDetailsObjecturlURL
-
authInfo对象¥
authInfoObject-
isProxy布尔值¥
isProxyboolean -
scheme字符串¥
schemestring -
host字符串¥
hoststring -
port整数¥
portInteger -
realm字符串¥
realmstring
-
-
callback函数¥
callbackFunction-
username字符串(可选)¥
usernamestring (optional) -
password字符串(可选)¥
passwordstring (optional)
-
当 webContents 想要进行基本身份验证时发出。
¥Emitted when webContents wants to do basic auth.
用法与 app 的 login 事件 相同。
¥The usage is the same with the login event of app.
事件:'found-in-page'
¥Event: 'found-in-page'
返回:
¥Returns:
-
event事件¥
eventEvent -
result对象¥
resultObject-
requestId整数¥
requestIdInteger -
activeMatchOrdinal整数 - 当前比赛的位置。¥
activeMatchOrdinalInteger - Position of the active match. -
matches整数 - 比赛次数。¥
matchesInteger - Number of Matches. -
selectionArea长方形 - 第一个匹配区域的坐标。¥
selectionAreaRectangle - Coordinates of first match region. -
finalUpdate布尔值¥
finalUpdateboolean
-
当 webContents.findInPage 请求有结果可用时发出。
¥Emitted when a result is available for
webContents.findInPage request.
事件:'media-started-playing'
¥Event: 'media-started-playing'
当媒体开始播放时发出。
¥Emitted when media starts playing.
事件:'media-paused'
¥Event: 'media-paused'
当媒体暂停或播放完毕时发出。
¥Emitted when media is paused or done playing.
事件:'audio-state-changed'
¥Event: 'audio-state-changed'
返回:
¥Returns:
-
event事件<>¥
eventEvent<>-
audible布尔值 - 如果一个或多个帧或子webContents正在发出音频,则为 True。¥
audibleboolean - True if one or more frames or childwebContentsare emitting audio.
-
当媒体变得可听见或不可听见时发出。
¥Emitted when media becomes audible or inaudible.
事件:'did-change-theme-color'
¥Event: 'did-change-theme-color'
返回:
¥Returns:
-
event事件¥
eventEvent -
color(string | null) - 主题颜色的格式为 '#rrggbb'。未设置主题色时为null。¥
color(string | null) - Theme color is in format of '#rrggbb'. It isnullwhen no theme color is set.
当页面的主题颜色更改时发出。这通常是由于遇到元标记:
¥Emitted when a page's theme color changes. This is usually due to encountering a meta tag:
<meta name='theme-color' content='#ff0000'>
事件:'update-target-url'
¥Event: 'update-target-url'
返回:
¥Returns:
-
event事件¥
eventEvent -
url字符串¥
urlstring
当鼠标移动到链接上或键盘将焦点移动到链接时发出。
¥Emitted when mouse moves over a link or the keyboard moves the focus to a link.
事件:'cursor-changed'
¥Event: 'cursor-changed'
返回:
¥Returns:
-
event事件¥
eventEvent -
type字符串¥
typestring -
imageNativeImage(可选)¥
imageNativeImage (optional) -
scale浮动(可选) - 自定义光标的缩放因子。¥
scaleFloat (optional) - scaling factor for the custom cursor. -
size尺寸(可选) -image的尺寸。¥
sizeSize (optional) - the size of theimage. -
hotspot观点(可选) - 自定义光标热点的坐标。¥
hotspotPoint (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。
¥Emitted when the cursor's type changes. The type parameter can be pointer,
crosshair, hand, text, wait, help, e-resize, n-resize, ne-resize,
nw-resize, s-resize, se-resize, sw-resize, w-resize, ns-resize, ew-resize,
nesw-resize, nwse-resize, col-resize, row-resize, m-panning, m-panning-vertical,
m-panning-horizontal, e-panning, n-panning, ne-panning, nw-panning, s-panning,
se-panning, sw-panning, w-panning, move, vertical-text, cell, context-menu,
alias, progress, nodrop, copy, none, not-allowed, zoom-in, zoom-out, grab,
grabbing, custom, null, drag-drop-none, drag-drop-move, drag-drop-copy,
drag-drop-link, ns-no-resize, ew-no-resize, nesw-no-resize, nwse-no-resize,
or default.
如果 type 参数为 custom,则 image 参数将在 NativeImage 中保存自定义光标图片,而 scale、size 和 hotspot 将保存有关自定义光标的附加信息。
¥If the type parameter is custom, the image parameter will hold the custom
cursor image in a NativeImage, and scale, size and hotspot will hold
additional information about the custom cursor.
事件:'context-menu'
¥Event: 'context-menu'
返回:
¥Returns:
-
event事件¥
eventEvent -
params对象¥
paramsObject-
x整数 - x 坐标。¥
xInteger - x coordinate. -
y整数 - y 坐标。¥
yInteger - y coordinate. -
frameWebFrameMain | null - 调用上下文菜单的框架。如果在框架导航或被销毁后访问,则可能是null。¥
frameWebFrameMain | null - Frame from which the context menu was invoked. May benullif accessed after the frame has either navigated or been destroyed. -
linkURL字符串 - 包含调用上下文菜单的节点的链接的 URL。¥
linkURLstring - URL of the link that encloses the node the context menu was invoked on. -
linkText字符串 - 与链接关联的文本。如果链接的内容是图片,则可能是空字符串。¥
linkTextstring - Text associated with the link. May be an empty string if the contents of the link are an image. -
pageURL字符串 - 调用上下文菜单的顶层页面的 URL。¥
pageURLstring - URL of the top level page that the context menu was invoked on. -
frameURL字符串 - 调用上下文菜单的子框架的 URL。¥
frameURLstring - URL of the subframe that the context menu was invoked on. -
srcURL字符串 - 调用上下文菜单的元素的源 URL。具有源 URL 的元素是图片、音频和视频。¥
srcURLstring - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. -
mediaType字符串 - 调用上下文菜单的节点的类型。可以是none、image、audio、video、canvas、file或plugin。¥
mediaTypestring - Type of the node the context menu was invoked on. Can benone,image,audio,video,canvas,fileorplugin. -
hasImageContents布尔值 - 是否在具有非空内容的图片上调用上下文菜单。¥
hasImageContentsboolean - Whether the context menu was invoked on an image which has non-empty contents. -
isEditable布尔值 - 上下文是否可编辑。¥
isEditableboolean - Whether the context is editable. -
selectionText字符串 - 调用上下文菜单的选择文本。¥
selectionTextstring - Text of the selection that the context menu was invoked on. -
titleText字符串 - 调用上下文菜单的选项的标题文本。¥
titleTextstring - Title text of the selection that the context menu was invoked on. -
altText字符串 - 调用上下文菜单的选项的替代文本。¥
altTextstring - Alt text of the selection that the context menu was invoked on. -
suggestedFilename字符串 - 通过上下文菜单的 '保存链接为' 选项保存文件时建议使用的文件名。¥
suggestedFilenamestring - Suggested filename to be used when saving file through 'Save Link As' option of context menu. -
selectionRect长方形 - 表示所选内容在文档空间中的坐标的矩形。¥
selectionRectRectangle - Rect representing the coordinates in the document space of the selection. -
selectionStartOffset数字 - 选择文本的起始位置。¥
selectionStartOffsetnumber - Start position of the selection text. -
referrerPolicy推荐人 - 调用菜单的框架的引用策略。¥
referrerPolicyReferrer - The referrer policy of the frame on which the menu is invoked. -
misspelledWord字符串 - 光标下拼写错误的单词(如果有)。¥
misspelledWordstring - The misspelled word under the cursor, if any. -
dictionarySuggestions字符串[] - 一系列建议单词,以显示用户替换misspelledWord。仅当存在拼写错误的单词并且启用了拼写检查器时才可用。¥
dictionarySuggestionsstring[] - An array of suggested words to show the user to replace themisspelledWord. Only available if there is a misspelled word and spellchecker is enabled. -
frameCharset字符串 - 调用菜单的帧的字符编码。¥
frameCharsetstring - The character encoding of the frame on which the menu was invoked. -
formControlType字符串 - 调用上下文菜单的源。可能的值包括none、button-button、field-set、input-button、input-checkbox、input-color、input-date、input-datetime-local、input-email、input-file、input-hidden、input-image、input-month、input-number、input-password、input-radio、input-range、input-reset、input-search、input-submit、input-telephone、input-text、input-time、input-url、input-week、output、reset-button、select-list、select-list、select-multiple、select-one、submit-button和text-area,¥
formControlTypestring - 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布尔值 - 如果上下文可编辑,则无论是否启用拼写检查。¥
spellcheckEnabledboolean - If the context is editable, whether or not spellchecking is enabled. -
menuSourceType字符串 - 调用上下文菜单的输入源。可以是none、mouse、keyboard、touch、touchMenu、longPress、longTap、touchHandle、stylus、adjustSelection或adjustSelectionReset。¥
menuSourceTypestring - Input source that invoked the context menu. Can benone,mouse,keyboard,touch,touchMenu,longPress,longTap,touchHandle,stylus,adjustSelection, oradjustSelectionReset. -
mediaFlags对象 - 调用上下文菜单的媒体元素的标志。¥
mediaFlagsObject - The flags for the media element the context menu was invoked on.-
inError布尔值 - 媒体元素是否崩溃。¥
inErrorboolean - Whether the media element has crashed. -
isPaused布尔值 - 媒体元素是否暂停。¥
isPausedboolean - Whether the media element is paused. -
isMuted布尔值 - 媒体元素是否静音。¥
isMutedboolean - Whether the media element is muted. -
hasAudio布尔值 - 媒体元素是否有音频。¥
hasAudioboolean - Whether the media element has audio. -
isLooping布尔值 - 媒体元素是否循环。¥
isLoopingboolean - Whether the media element is looping. -
isControlsVisible布尔值 - 媒体元素的控件是否可见。¥
isControlsVisibleboolean - Whether the media element's controls are visible. -
canToggleControls布尔值 - 媒体元素的控件是否可切换。¥
canToggleControlsboolean - Whether the media element's controls are toggleable. -
canPrint布尔值 - 是否可以打印媒体元素。¥
canPrintboolean - Whether the media element can be printed. -
canSave布尔值 - 媒体元素是否可以下载。¥
canSaveboolean - Whether or not the media element can be downloaded. -
canShowPictureInPicture布尔值 - 媒体元素是否可以显示画中画。¥
canShowPictureInPictureboolean - Whether the media element can show picture-in-picture. -
isShowingPictureInPicture布尔值 - 媒体元素当前是否显示画中画。¥
isShowingPictureInPictureboolean - Whether the media element is currently showing picture-in-picture. -
canRotate布尔值 - 媒体元素是否可以旋转。¥
canRotateboolean - Whether the media element can be rotated. -
canLoop布尔值 - 媒体元素是否可以循环播放。¥
canLoopboolean - Whether the media element can be looped.
-
-
editFlags对象 - 这些标志指示渲染器是否认为它能够执行相应的操作。¥
editFlagsObject - These flags indicate whether the renderer believes it is able to perform the corresponding action.-
canUndo布尔值 - 渲染器是否相信它可以撤消。¥
canUndoboolean - Whether the renderer believes it can undo. -
canRedo布尔值 - 渲染器是否相信它可以重做。¥
canRedoboolean - Whether the renderer believes it can redo. -
canCut布尔值 - 渲染器是否相信它可以剪切。¥
canCutboolean - Whether the renderer believes it can cut. -
canCopy布尔值 - 渲染器是否相信它可以复制。¥
canCopyboolean - Whether the renderer believes it can copy. -
canPaste布尔值 - 渲染器是否认为可以粘贴。¥
canPasteboolean - Whether the renderer believes it can paste. -
canDelete布尔值 - 渲染器是否相信它可以删除。¥
canDeleteboolean - Whether the renderer believes it can delete. -
canSelectAll布尔值 - 渲染器是否相信它可以选择全部。¥
canSelectAllboolean - Whether the renderer believes it can select all. -
canEditRichly布尔值 - 渲染器是否相信它可以丰富地编辑文本。¥
canEditRichlyboolean - Whether the renderer believes it can edit text richly.
-
-
当有需要处理的新上下文菜单时发出。
¥Emitted when there is a new context menu that needs to be handled.
事件:'select-bluetooth-device'
¥Event: 'select-bluetooth-device'
返回:
¥Returns:
-
event事件¥
eventEvent -
devicesBluetoothDevice[] -
callback函数¥
callbackFunction-
deviceId字符串¥
deviceIdstring
-
当调用 navigator.bluetooth.requestDevice 时需要选择蓝牙设备时发出。应使用要选择的设备的 deviceId 来调用 callback。将空字符串传递给 callback 将取消请求。
¥Emitted when a bluetooth device needs to be selected when a call to
navigator.bluetooth.requestDevice is made. callback should be called with
the deviceId of the device to be selected. Passing an empty string to
callback will cancel the request.
如果没有为此事件添加事件监听器,则所有蓝牙请求都将被取消。
¥If no event listener is added for this event, all bluetooth requests will be cancelled.
如果在处理此事件时未调用 event.preventDefault,则将自动选择第一个可用设备。
¥If event.preventDefault is not called when handling this event, the first available
device will be automatically selected.
由于蓝牙的性质,调用 navigator.bluetooth.requestDevice 时扫描设备可能需要一些时间,并且会导致 select-bluetooth-device 多次触发,直到使用设备 ID 或空字符串调用 callback 来取消请求。
¥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)
}
})
})
事件:'paint'
¥Event: 'paint'
返回:
¥Returns:
-
details事件<>¥
detailsEvent<>-
textureOffscreenSharedTexture(可选)实验性 - 当webPreferences.offscreen.useSharedTexture为true时,帧的 GPU 共享纹理。¥
textureOffscreenSharedTexture (optional) Experimental - The GPU shared texture of the frame, whenwebPreferences.offscreen.useSharedTextureistrue.
-
-
dirtyRect长方形¥
dirtyRectRectangle -
imageNativeImage - 整帧的图片数据。¥
imageNativeImage - The image data of the whole frame.
生成新帧时发出。缓冲区中仅传递脏区。
¥Emitted when a new frame is generated. Only the dirty area is passed in the buffer.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ webPreferences: { offscreen: true } })
win.webContents.on('paint', (event, dirty, image) => {
// updateBitmap(dirty, image.toBitmap())
})
win.loadURL('https://github.com')
使用共享纹理(将 webPreferences.offscreen.useSharedTexture 设置为 true)功能时,你可以将纹理句柄传递给外部渲染管道,而无需在 CPU 和 GPU 内存之间复制数据的开销,并借助 Chromium 的硬件加速支持。此功能对于高性能渲染场景很有帮助。
¥When using shared texture (set webPreferences.offscreen.useSharedTexture to true) feature, you can pass the texture handle to external rendering pipeline without the overhead of
copying data between CPU and GPU memory, with Chromium's hardware acceleration support. This feature is helpful for high-performance rendering scenarios.
只能同时存在有限数量的纹理,因此在处理完纹理后立即调用 texture.release() 非常重要。通过自己管理纹理生命周期,你可以安全地通过 IPC 将 texture.textureInfo 传递给其他进程。
¥Only a limited number of textures can exist at the same time, so it's important that you call texture.release() as soon as you're done with the texture.
By managing the texture lifecycle by yourself, you can safely pass the texture.textureInfo to other processes through IPC.
更多详细信息请参阅 离屏渲染教程。要了解如何在原生代码中处理纹理,请参阅 离屏渲染代码文档。。
¥More details can be found in the offscreen rendering tutorial. To learn about how to handle the texture in native code, refer to offscreen rendering's code documentation..
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ webPreferences: { offscreen: { useSharedTexture: true } } })
win.webContents.on('paint', async (e, dirty, image) => {
if (e.texture) {
// By managing lifecycle yourself, you can handle the event in async handler or pass the `e.texture.textureInfo`
// to other processes (not `e.texture`, the `e.texture.release` function is not passable through IPC).
await new Promise(resolve => setTimeout(resolve, 50))
// You can send the native texture handle to native code for importing into your rendering pipeline.
// Read more at https://github.com/electron/electron/blob/main/shell/browser/osr/README.md
// importTextureHandle(dirty, e.texture.textureInfo)
// You must call `e.texture.release()` as soon as possible, before the underlying frame pool is drained.
e.texture.release()
}
})
win.loadURL('https://github.com')
事件:'devtools-reload-page'
¥Event: 'devtools-reload-page'
当 devtools 窗口指示 webContents 重新加载时发出
¥Emitted when the devtools window instructs the webContents to reload
事件:'will-attach-webview'
¥Event: 'will-attach-webview'
返回:
¥Returns:
-
event事件¥
eventEvent -
webPreferencesWebPreferences - 访客页面将使用的网络首选项。可以修改此对象以调整访客页面的首选项。¥
webPreferencesWebPreferences - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page. -
params记录<字符串,字符串> - 其他<webview>参数,例如srcURL。可以修改该对象来调整访客页面的参数。¥
paramsRecord<string, string> - The other<webview>parameters such as thesrcURL. This object can be modified to adjust the parameters of the guest page.
当 <webview> 的网页内容附加到此网页内容时发出。调用 event.preventDefault() 将破坏访客页面。
¥Emitted when a <webview>'s web contents is being attached to this web
contents. Calling event.preventDefault() will destroy the guest page.
此事件可用于在加载 <webview> 之前为 <webview> 的 webContents 配置 webPreferences,并提供设置无法通过 <webview> 属性设置的设置的功能。
¥This event can be used to configure webPreferences for the webContents
of a <webview> before it's loaded, and provides the ability to set settings
that can't be set via <webview> attributes.
事件:'did-attach-webview'
¥Event: 'did-attach-webview'
返回:
¥Returns:
-
event事件¥
eventEvent -
webContentsWebContents -<webview>使用的访客 Web 内容。¥
webContentsWebContents - The guest web contents that is used by the<webview>.
当 <webview> 附加到此 Web 内容时发出。
¥Emitted when a <webview> has been attached to this web contents.
事件:'console-message'
¥Event: 'console-message'
返回:
¥Returns:
-
details事件<>¥
detailsEvent<>-
message字符串 - 消息文本¥
messagestring - Message text -
level字符串 - 消息严重性可能的值包括info、warning、error和debug。¥
levelstring - Message severity Possible values includeinfo,warning,error, anddebug. -
lineNumber整数 - 日志源中的行号¥
lineNumberInteger - Line number in the log source -
sourceId字符串 - 日志源的 URL¥
sourceIdstring - URL of the log source -
frameWeb 框架主 - 记录消息的框架¥
frameWebFrameMain - Frame that logged the message
-
-
level整数 已弃用 - 日志级别,从 0 到 3。按照顺序,它匹配verbose、info、warning和error。¥
levelInteger Deprecated - The log level, from 0 to 3. In order it matchesverbose,info,warninganderror. -
message字符串 已弃用 - 实际的控制台消息¥
messagestring Deprecated - The actual console message -
line整数 已弃用 - 触发此控制台消息的源的行号¥
lineInteger Deprecated - The line number of the source that triggered this console message -
sourceId字符串 已弃用¥
sourceIdstring Deprecated
当关联的窗口记录控制台消息时发出。
¥Emitted when the associated window logs a console message.
事件:'preload-error'
¥Event: 'preload-error'
返回:
¥Returns:
-
event事件¥
eventEvent -
preloadPath字符串¥
preloadPathstring -
error错误¥
errorError
当预加载脚本 preloadPath 抛出未处理的异常 error 时发出。
¥Emitted when the preload script preloadPath throws an unhandled exception error.
事件:'ipc-message'
¥Event: 'ipc-message'
返回:
¥Returns:
-
eventIpc 主事件¥
eventIpcMainEvent -
channel字符串¥
channelstring -
...args任何[]¥
...argsany[]
当渲染器进程通过 ipcRenderer.send() 发送异步消息时发出。
¥Emitted when the renderer process sends an asynchronous message via ipcRenderer.send().
另请参见 webContents.ipc,它提供了类似 IpcMain 的接口,用于专门响应来自此 WebContents 的 IPC 消息。
¥See also webContents.ipc, which provides an IpcMain-like interface for responding to IPC messages specifically from this WebContents.
事件:'ipc-message-sync'
¥Event: 'ipc-message-sync'
返回:
¥Returns:
-
eventIpc 主事件¥
eventIpcMainEvent -
channel字符串¥
channelstring -
...args任何[]¥
...argsany[]
当渲染器进程通过 ipcRenderer.sendSync() 发送同步消息时发出。
¥Emitted when the renderer process sends a synchronous message via ipcRenderer.sendSync().
另请参见 webContents.ipc,它提供了类似 IpcMain 的接口,用于专门响应来自此 WebContents 的 IPC 消息。
¥See also webContents.ipc, which provides an IpcMain-like interface for responding to IPC messages specifically from this WebContents.
事件:'preferred-size-changed'
¥Event: 'preferred-size-changed'
返回:
¥Returns:
-
event事件¥
eventEvent -
preferredSize尺寸 - 包含文档布局所需的最小尺寸(无需滚动)。¥
preferredSizeSize - The minimum size needed to contain the layout of the document—without requiring scrolling.
当 WebContents 首选大小更改时发出。
¥Emitted when the WebContents preferred size has changed.
仅当 webPreferences 中的 enablePreferredSizeMode 设置为 true 时才会发出此事件。
¥This event will only be emitted when enablePreferredSizeMode is set to true
in webPreferences.
事件:'frame-created'
¥Event: 'frame-created'
返回:
¥Returns:
-
event事件¥
eventEvent -
details对象¥
detailsObject-
frameWebFrameMain | null - 创建的框架。如果在框架导航或被销毁后访问,则可能是null。¥
frameWebFrameMain | null - The created frame. May benullif accessed after the frame has either navigated or been destroyed.
-
当 mainFrame、<iframe> 或嵌套 <iframe> 在页面内加载时发出。
¥Emitted when the mainFrame, an <iframe>, or a nested <iframe> is loaded within the page.
实例方法
¥Instance Methods
contents.loadURL(url[, options])
-
url字符串¥
urlstring
返回 Promise<void> - 当页面加载完成时,promise 将解析(参见 did-finish-load),如果页面加载失败,则拒绝(参见 did-fail-load)。已附加 noop 拒绝处理程序,这可以避免未处理的拒绝错误。
¥Returns Promise<void> - the promise will resolve when the page has finished loading
(see did-finish-load), and rejects
if the page fails to load (see
did-fail-load). A noop rejection handler is already attached, which avoids unhandled rejection errors.
在窗口中加载 url。url 必须包含协议前缀,例如 http:// 或 file://。如果负载应绕过 http 缓存,则使用 pragma 标头来实现。
¥Loads the url in the window. The url must contain the protocol prefix,
e.g. the http:// or file://. If the load should bypass http cache then
use the pragma header to achieve it.
const win = new BrowserWindow()
const options = { extraHeaders: 'pragma: no-cache\n' }
win.webContents.loadURL('https://github.com', options)
contents.loadFile(filePath[, options])
-
filePath字符串¥
filePathstring
返回 Promise<void> - 当页面加载完成时,promise 将解析(参见 did-finish-load),如果页面加载失败,则拒绝(参见 did-fail-load)。
¥Returns Promise<void> - the promise will resolve when the page has finished loading
(see did-finish-load), and rejects
if the page fails to load (see did-fail-load).
在窗口中加载给定文件,filePath 应该是相对于应用根目录的 HTML 文件的路径。例如这样的应用结构:
¥Loads the given file in the window, filePath should be a path to
an HTML file relative to the root of your application. For instance
an app structure like this:
| root
| - package.json
| - src
| - main.js
| - index.html
需要这样的代码
¥Would require code like this
const win = new BrowserWindow()
win.loadFile('src/index.html')
contents.downloadURL(url[, options])
-
url字符串¥
urlstring
无需导航即可启动 url 处资源的下载。session 的 will-download 事件将被触发。
¥Initiates a download of the resource at url without navigating. The
will-download event of session will be triggered.
contents.getURL()
返回 string - 当前网页的 URL。
¥Returns string - The URL of the current web page.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com').then(() => {
const currentURL = win.webContents.getURL()
console.log(currentURL)
})
contents.getTitle()
返回 string - 当前网页的标题。
¥Returns string - The title of the current web page.
contents.isDestroyed()
返回 boolean - 网页是否被破坏。
¥Returns boolean - Whether the web page is destroyed.
contents.close([opts])
-
opts对象(可选)¥
optsObject (optional)-
waitForBeforeUnload布尔值 - 如果为 true,则在关闭页面之前触发beforeunload事件。如果页面阻止卸载,则 WebContents 将不会关闭。如果页面请求阻止卸载,则will-prevent-unload将被触发。¥
waitForBeforeUnloadboolean - if true, fire thebeforeunloadevent before closing the page. If the page prevents the unload, the WebContents will not be closed. Thewill-prevent-unloadwill be fired if the page requests prevention of unload.
-
关闭页面,就像网页内容名为 window.close() 一样。
¥Closes the page, as if the web content had called window.close().
如果页面成功关闭(即页面未阻止卸载,或者 waitForBeforeUnload 为 false 或未指定),则 WebContents 将被销毁并且不再可用。将发出 destroyed 事件。
¥If the page is successfully closed (i.e. the unload is not prevented by the
page, or waitForBeforeUnload is false or unspecified), the WebContents will
be destroyed and no longer usable. The destroyed event
will be emitted.
contents.focus()
聚焦网页。
¥Focuses the web page.
contents.isFocused()
返回 boolean - 网页是否获得焦点。
¥Returns boolean - Whether the web page is focused.
contents.isLoading()
返回 boolean - 网页是否仍在加载资源。
¥Returns boolean - Whether web page is still loading resources.
contents.isLoadingMainFrame()
返回 boolean - 主框架(而不仅仅是 iframe 或其中的框架)是否仍在加载。
¥Returns boolean - Whether the main frame (and not just iframes or frames within it) is
still loading.
contents.isWaitingForResponse()
返回 boolean - 网页是否正在等待页面主资源的第一响应。
¥Returns boolean - Whether the web page is waiting for a first-response from the main
resource of the page.
contents.stop()
停止任何挂起的导航。
¥Stops any pending navigation.
contents.reload()
重新加载当前网页。
¥Reloads the current web page.
contents.reloadIgnoringCache()
重新加载当前页面并忽略缓存。
¥Reloads current page and ignores cache.
contents.canGoBack() 已弃用
¥contents.canGoBack() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
返回 boolean - 浏览器是否可以返回上一个网页。
¥Returns boolean - Whether the browser can go back to previous web page.
已弃用:应该使用新的 contents.navigationHistory.canGoBack API。
¥Deprecated: Should use the new contents.navigationHistory.canGoBack API.
contents.canGoForward() 已弃用
¥contents.canGoForward() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
返回 boolean - 浏览器是否可以前进到下一个网页。
¥Returns boolean - Whether the browser can go forward to next web page.
已弃用:应该使用新的 contents.navigationHistory.canGoForward API。
¥Deprecated: Should use the new contents.navigationHistory.canGoForward API.
contents.canGoToOffset(offset) 已弃用
¥contents.canGoToOffset(offset) Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
-
offset整数¥
offsetInteger
返回 boolean - 网页是否可以转到 offset。
¥Returns boolean - Whether the web page can go to offset.
已弃用:应该使用新的 contents.navigationHistory.canGoToOffset API。
¥Deprecated: Should use the new contents.navigationHistory.canGoToOffset API.
contents.clearHistory() 已弃用
¥contents.clearHistory() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
清除导航历史记录。
¥Clears the navigation history.
已弃用:应该使用新的 contents.navigationHistory.clear API。
¥Deprecated: Should use the new contents.navigationHistory.clear API.
contents.goBack() 已弃用
¥contents.goBack() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
使浏览器返回网页。
¥Makes the browser go back a web page.
已弃用:应该使用新的 contents.navigationHistory.goBack API。
¥Deprecated: Should use the new contents.navigationHistory.goBack API.
contents.goForward() 已弃用
¥contents.goForward() Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
使浏览器前进一个网页。
¥Makes the browser go forward a web page.
已弃用:应该使用新的 contents.navigationHistory.goForward API。
¥Deprecated: Should use the new contents.navigationHistory.goForward API.
contents.goToIndex(index) 已弃用
¥contents.goToIndex(index) Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
-
index整数¥
indexInteger
将浏览器导航到指定的绝对网页索引。
¥Navigates browser to the specified absolute web page index.
已弃用:应该使用新的 contents.navigationHistory.goToIndex API。
¥Deprecated: Should use the new contents.navigationHistory.goToIndex API.
contents.goToOffset(offset) 已弃用
¥contents.goToOffset(offset) Deprecated
History
| Version(s) | Changes |
|---|---|
None | API DEPRECATED |
-
offset整数¥
offsetInteger
导航到距 "当前条目" 的指定偏移量。
¥Navigates to the specified offset from the "current entry".
已弃用:应该使用新的 contents.navigationHistory.goToOffset API。
¥Deprecated: Should use the new contents.navigationHistory.goToOffset API.
contents.isCrashed()
返回 boolean - 渲染器进程是否崩溃。
¥Returns boolean - Whether the renderer process has crashed.
contents.forcefullyCrashRenderer()
强制终止当前托管此 webContents 的渲染器进程。这将导致 render-process-gone 事件与 reason=killed || reason=crashed 一起发出。请注意,某些 webContents 共享渲染器进程,因此调用此方法也可能导致其他 webContents 的主机进程崩溃。
¥Forcefully terminates the renderer process that is currently hosting this
webContents. This will cause the render-process-gone event to be emitted
with the reason=killed || reason=crashed. Please note that some webContents share renderer
processes and therefore calling this method may also crash the host process
for other webContents as well.
调用此方法后立即调用 reload() 将强制在新进程中进行重新加载。当该进程不稳定或不可用时,应使用此方法,例如为了从 unresponsive 事件中恢复。
¥Calling reload() immediately after calling this
method will force the reload to occur in a new process. This should be used
when this process is unstable or unusable, for instance in order to recover
from the unresponsive event.
const win = new BrowserWindow()
win.webContents.on('unresponsive', async () => {
const { response } = await dialog.showMessageBox({
message: 'App X has become unresponsive',
title: 'Do you want to try forcefully reloading the app?',
buttons: ['OK', 'Cancel'],
cancelId: 1
})
if (response === 0) {
win.webContents.forcefullyCrashRenderer()
win.webContents.reload()
}
})
contents.setUserAgent(userAgent)
-
userAgent字符串¥
userAgentstring
覆盖此网页的用户代理。
¥Overrides the user agent for this web page.
contents.getUserAgent()
返回 string - 该网页的用户代理。
¥Returns string - The user agent for this web page.
contents.insertCSS(css[, options])
-
css字符串¥
cssstring
返回 Promise<string> - 一个使用插入 CSS 的密钥进行解析的 promise,稍后可以使用该密钥通过 contents.removeInsertedCSS(key) 删除 CSS。
¥Returns Promise<string> - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via contents.removeInsertedCSS(key).
将 CSS 注入当前网页并返回插入样式表的唯一键。
¥Injects CSS into the current web page and returns a unique key for the inserted stylesheet.
const win = new BrowserWindow()
win.webContents.on('did-finish-load', () => {
win.webContents.insertCSS('html, body { background-color: #f00; }')
})
contents.removeInsertedCSS(key)
-
key字符串¥
keystring
返回 Promise<void> - 解决是否删除成功。
¥Returns Promise<void> - Resolves if the removal was successful.
从当前网页中删除插入的 CSS。样式表由其键标识,该键从 contents.insertCSS(css) 返回。
¥Removes the inserted CSS from the current web page. The stylesheet is identified
by its key, which is returned from contents.insertCSS(css).
const win = new BrowserWindow()
win.webContents.on('did-finish-load', async () => {
const key = await win.webContents.insertCSS('html, body { background-color: #f00; }')
win.webContents.removeInsertedCSS(key)
})
contents.executeJavaScript(code[, userGesture])
-
code字符串¥
codestring -
userGesture布尔值(可选) - 默认为false。¥
userGestureboolean (optional) - Default isfalse.
返回 Promise<any> - 根据执行代码的结果进行解析的 Promise,或者如果代码的结果是被拒绝的 Promise,则被拒绝。
¥Returns Promise<any> - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
评估页面中的 code。
¥Evaluates code in page.
在浏览器窗口中,某些 HTML API(例如 requestFullScreen)只能通过用户的手势来调用。将 userGesture 设置为 true 将消除此限制。
¥In the browser window some HTML APIs like requestFullScreen can only be
invoked by a gesture from the user. Setting userGesture to true will remove
this limitation.
代码执行将暂停,直到网页停止加载。
¥Code execution will be suspended until web page stop loading.
const win = new BrowserWindow()
win.webContents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true)
.then((result) => {
console.log(result) // Will be the JSON object from the fetch call
})
contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])
-
worldId整数 - 运行 javascript 的世界的 ID,0是默认世界,999是 Electron 的contextIsolation功能使用的世界。你可以在此处提供任何整数。¥
worldIdInteger - The ID of the world to run the javascript in,0is the default world,999is the world used by Electron'scontextIsolationfeature. You can provide any integer here. -
scriptsWebSource[] -
userGesture布尔值(可选) - 默认为false。¥
userGestureboolean (optional) - Default isfalse.
返回 Promise<any> - 根据执行代码的结果进行解析的 Promise,或者如果代码的结果是被拒绝的 Promise,则被拒绝。
¥Returns Promise<any> - A promise that resolves with the result of the executed code
or is rejected if the result of the code is a rejected promise.
与 executeJavaScript 类似,但在孤立的上下文中评估 scripts。
¥Works like executeJavaScript but evaluates scripts in an isolated context.
contents.setIgnoreMenuShortcuts(ignore)
-
ignore布尔值¥
ignoreboolean
当此 Web 内容获得焦点时,忽略应用菜单快捷方式。
¥Ignore application menu shortcuts while this web contents is focused.
contents.setWindowOpenHandler(handler)
-
handlerFunction<WindowOpenHandlerResponse>-
details对象¥
detailsObject-
url字符串 - 传递给window.open()的 URL 的解析版本。例如 用window.open('foo')打开一个窗口将产生类似https://the-origin/the/current/path/foo的结果。¥
urlstring - The resolved version of the URL passed towindow.open(). e.g. opening a window withwindow.open('foo')will yield something likehttps://the-origin/the/current/path/foo. -
frameName字符串 -window.open()中提供的窗口名称¥
frameNamestring - Name of the window provided inwindow.open() -
features字符串 - 提供给window.open()的以逗号分隔的窗口功能列表。¥
featuresstring - Comma separated list of window features provided towindow.open(). -
disposition字符串 - 可以是default、foreground-tab、background-tab、new-window或other。¥
dispositionstring - Can bedefault,foreground-tab,background-tab,new-windoworother. -
referrer推荐人 - 将传递到新窗口的引荐来源网址。可能会也可能不会导致发送Referer标头,具体取决于引荐来源网址策略。¥
referrerReferrer - The referrer that will be passed to the new window. May or may not result in theRefererheader being sent, depending on the referrer policy. -
postBodyPostBody(可选) - 将发送到新窗口的发布数据以及将设置的适当标头。如果不发送 post 数据,则该值为null。仅当窗口由设置target=_blank的表单创建时才定义。¥
postBodyPostBody (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will benull. Only defined when the window is being created by a form that settarget=_blank.
-
返回
WindowOpenHandlerResponse- 设置为{ action: 'deny' }时,将取消新窗口的创建。{ action: 'allow' }将允许创建新窗口。返回无法识别的值(例如 null、未定义或没有识别的 'action' 值的对象)将导致控制台错误,并且与返回{action: 'deny'}具有相同的效果。¥Returns
WindowOpenHandlerResponse- When set to{ action: 'deny' }cancels the creation of the new window.{ action: 'allow' }will allow the new window to be created. Returning an unrecognized value such as a null, undefined, or an object without a recognized 'action' value will result in a console error and have the same effect as returning{action: 'deny'}. -
在创建窗口之前调用,渲染器请求新窗口,例如 通过 window.open()、target="_blank" 的链接、Shift+单击链接或通过 <form target="_blank"> 提交表单。有关更多详细信息以及如何将其与 did-create-window 结合使用,请参阅 window.open()。
¥Called before creating a window a new window is requested by the renderer, e.g.
by window.open(), a link with target="_blank", shift+clicking on a link, or
submitting a form with <form target="_blank">. See
window.open() for more details and how to use this in
conjunction with did-create-window.
一个示例,展示如何自定义新 BrowserWindow 创建过程,以便将 BrowserView 附加到主窗口:
¥An example showing how to customize the process of new BrowserWindow creation to be BrowserView attached to main window instead:
const { BrowserView, BrowserWindow } = require('electron')
const mainWindow = new BrowserWindow()
mainWindow.webContents.setWindowOpenHandler((details) => {
return {
action: 'allow',
createWindow: (options) => {
const browserView = new BrowserView(options)
mainWindow.addBrowserView(browserView)
browserView.setBounds({ x: 0, y: 0, width: 640, height: 480 })
return browserView.webContents
}
}
})
contents.setAudioMuted(muted)
-
muted布尔值¥
mutedboolean
将当前网页的音频静音。
¥Mute the audio on the current web page.
contents.isAudioMuted()
返回 boolean - 该页面是否已静音。
¥Returns boolean - Whether this page has been muted.
contents.isCurrentlyAudible()
返回 boolean - 当前是否正在播放音频。
¥Returns boolean - Whether audio is currently playing.
contents.setZoomFactor(factor)
-
factor双倍的 - 变焦倍数;默认值为 1.0。¥
factorDouble - Zoom factor; default is 1.0.
将缩放系数更改为指定系数。缩放系数是缩放百分比除以 100,因此 300% = 3.0。
¥Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0.
该系数必须大于 0.0。
¥The factor must be greater than 0.0.
contents.getZoomFactor()
返回 number - 当前的缩放系数。
¥Returns number - the current zoom factor.
contents.setZoomLevel(level)
-
level数字 - 缩放级别。¥
levelnumber - Zoom level.
将缩放级别更改为指定级别。原始大小为 0,上方或下方的每个增量表示放大或缩小 20%,分别达到原始大小的 300% 和 50% 的默认限制。其公式为 scale := 1.2 ^ level。
¥Changes the zoom level to the specified level. The original size is 0 and each
increment above or below represents zooming 20% larger or smaller to default
limits of 300% and 50% of original size, respectively. The formula for this is
scale := 1.2 ^ level.
[!NOTE] Chromium 级别的缩放策略是同源的,这意味着特定域的缩放级别会传播到同一域的所有窗口实例。区分窗口 URL 将使缩放针对每个窗口起作用。
¥[!NOTE] The zoom policy at the Chromium level is same-origin, meaning that the zoom level for a specific domain propagates across all instances of windows with the same domain. Differentiating the window URLs will make zoom work per-window.
contents.getZoomLevel()
返回 number - 当前的缩放级别。
¥Returns number - the current zoom level.
contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)
-
minimumLevel数字¥
minimumLevelnumber -
maximumLevel数字¥
maximumLevelnumber
返回 Promise<void>
¥Returns Promise<void>
设置最大和最小捏合缩放级别。
¥Sets the maximum and minimum pinch-to-zoom level.
[!NOTE] Electron 默认禁用视觉缩放。要重新启用它,请调用:
¥[!NOTE] Visual zoom is disabled by default in Electron. To re-enable it, call:
const win = new BrowserWindow()
win.webContents.setVisualZoomLevelLimits(1, 3)
contents.undo()
在网页中执行编辑命令 undo。
¥Executes the editing command undo in web page.
contents.redo()
在网页中执行编辑命令 redo。
¥Executes the editing command redo in web page.
contents.cut()
在网页中执行编辑命令 cut。
¥Executes the editing command cut in web page.
contents.copy()
在网页中执行编辑命令 copy。
¥Executes the editing command copy in web page.
contents.centerSelection()
将当前文本选择在网页中居中。
¥Centers the current text selection in web page.
contents.copyImageAt(x, y)
-
x整数¥
xInteger -
y整数¥
yInteger
将给定位置的图片复制到剪贴板。
¥Copy the image at the given position to the clipboard.
contents.paste()
在网页中执行编辑命令 paste。
¥Executes the editing command paste in web page.
contents.pasteAndMatchStyle()
在网页中执行编辑命令 pasteAndMatchStyle。
¥Executes the editing command pasteAndMatchStyle in web page.
contents.delete()
在网页中执行编辑命令 delete。
¥Executes the editing command delete in web page.
contents.selectAll()
在网页中执行编辑命令 selectAll。
¥Executes the editing command selectAll in web page.
contents.unselect()
在网页中执行编辑命令 unselect。
¥Executes the editing command unselect in web page.
contents.scrollToTop()
滚动到当前 webContents 的顶部。
¥Scrolls to the top of the current webContents.
contents.scrollToBottom()
滚动到当前 webContents 的底部。
¥Scrolls to the bottom of the current webContents.
contents.adjustSelection(options)
将焦点框中当前文本选择的起点和终点调整给定的量。负值会将所选内容移向文档的开头,正值会将所选内容移向文档的末尾。
¥Adjusts the current text selection starting and ending points in the focused frame by the given amounts. A negative amount moves the selection towards the beginning of the document, and a positive amount moves the selection towards the end of the document.
示例:
¥Example:
const win = new BrowserWindow()
// Adjusts the beginning of the selection 1 letter forward,
// and the end of the selection 5 letters forward.
win.webContents.adjustSelection({ start: 1, end: 5 })
// Adjusts the beginning of the selection 2 letters forward,
// and the end of the selection 3 letters backward.
win.webContents.adjustSelection({ start: 2, end: -3 })
对于 win.webContents.adjustSelection({ start: 1, end: 5 }) 的调用
¥For a call of win.webContents.adjustSelection({ start: 1, end: 5 })
前:
¥Before:
后:
¥After:
contents.replace(text)
-
text字符串¥
textstring
在网页中执行编辑命令 replace。
¥Executes the editing command replace in web page.
contents.replaceMisspelling(text)
-
text字符串¥
textstring
在网页中执行编辑命令 replaceMisspelling。
¥Executes the editing command replaceMisspelling in web page.
contents.insertText(text)
-
text字符串¥
textstring
返回 Promise<void>
¥Returns Promise<void>
将 text 插入到焦点元素中。
¥Inserts text to the focused element.
contents.findInPage(text[, options])
-
text字符串 - 要搜索的内容,不能为空。¥
textstring - Content to be searched, must not be empty.
返回 Integer - 用于请求的请求 ID。
¥Returns Integer - The request id used for the request.
启动请求以查找网页中 text 的所有匹配项。请求的结果可以通过订阅 found-in-page 事件来获取。
¥Starts a request to find all matches for the text in the web page. The result of the request
can be obtained by subscribing to found-in-page event.
contents.stopFindInPage(action)
-
action字符串 - 指定结束webContents.findInPage请求时要执行的操作。¥
actionstring - Specifies the action to take place when endingwebContents.findInPagerequest.-
clearSelection- 清除选择。¥
clearSelection- Clear the selection. -
keepSelection- 将选择转换为正常选择。¥
keepSelection- Translate the selection into a normal selection. -
activateSelection- 聚焦并单击选择节点。¥
activateSelection- Focus and click the selection node.
-
使用提供的 action 停止对 webContents 的任何 findInPage 请求。
¥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长方形(可选) - 要捕获的页面区域。¥
rectRectangle (optional) - The area of the page to be captured. -
opts对象(可选)¥
optsObject (optional)-
stayHidden布尔值(可选) - 保持页面隐藏而不是可见。默认为false。¥
stayHiddenboolean (optional) - Keep the page hidden instead of visible. Default isfalse. -
stayAwake布尔值(可选) - 保持系统清醒而不是让它休眠。默认为false。¥
stayAwakeboolean (optional) - Keep the system awake instead of allowing it to sleep. Default isfalse.
-
返回 Promise<NativeImage> - 用 NativeImage 解决
¥Returns Promise<NativeImage> - Resolves with a NativeImage
捕获 rect 内页面的快照。省略 rect 将捕获整个可见页面。当浏览器窗口隐藏且捕获器计数非零时,页面被视为可见。如果你希望页面保持隐藏状态,则应确保 stayHidden 设置为 true。
¥Captures a snapshot of the page within rect. Omitting rect will capture the whole visible page.
The page is considered visible when its browser window is hidden and the capturer count is non-zero.
If you would like the page to stay hidden, you should ensure that stayHidden is set to true.
contents.isBeingCaptured()
返回 boolean - 该页面是否正在被捕获。当捕获器计数大于 0 时,它返回 true。
¥Returns boolean - Whether this page is being captured. It returns true when the capturer count
is greater than 0.
contents.getPrintersAsync()
获取系统打印机列表。
¥Get the system printer list.
返回 Promise<PrinterInfo[]> - 用 PrinterInfo[] 解决
¥Returns Promise<PrinterInfo[]> - Resolves with a PrinterInfo[]
contents.print([options], [callback])
-
callback功能(可选)¥
callbackFunction (optional)-
success布尔值 - 表明打印调用成功。¥
successboolean - Indicates success of the print call. -
failureReason字符串 - 打印失败回调的错误描述。¥
failureReasonstring - Error description called back if the print fails.
-
当自定义 pageSize 被传递时,Chromium 会尝试验证 width_microns 和 height_microns 的平台特定最小值。宽度和高度必须至少为 353 微米,但在某些操作系统上可能会更高。
¥When a custom pageSize is passed, Chromium attempts to validate platform specific minimum values for width_microns and height_microns. Width and height must both be minimum 353 microns but may be higher on some operating systems.
打印窗口的网页。当 silent 设置为 true 时,如果 deviceName 为空,Electron 将选择系统默认打印机并使用默认设置进行打印。
¥Prints window's web page. When silent is set to true, Electron will pick
the system's default printer if deviceName is empty and the default settings for printing.
一些可能导致打印失败的 failureReason 事件包括:
¥Some possible failureReasons for print failure include:
-
"打印机设置无效"
¥"Invalid printer settings"
-
"打印作业已取消"
¥"Print job canceled"
-
"打印作业失败"
¥"Print job failed"
使用 page-break-before: always; CSS 样式强制打印到新页面。
¥Use page-break-before: always; CSS style to force to print to a new page.
用法示例:
¥Example usage:
const win = new BrowserWindow()
const options = {
silent: true,
deviceName: 'My-Printer',
pageRanges: [{
from: 0,
to: 1
}]
}
win.webContents.print(options, (success, errorType) => {
if (!success) console.log(errorType)
})
contents.printToPDF(options)
返回 Promise<Buffer> - 使用生成的 PDF 数据进行解析。
¥Returns Promise<Buffer> - Resolves with the generated PDF data.
将窗口的网页打印为 PDF。
¥Prints the window's web page as PDF.
如果网页中使用了 @page CSS at 规则,则 landscape 将被忽略。
¥The landscape will be ignored if @page CSS at-rule is used in the web page.
webContents.printToPDF 的一个例子:
¥An example of webContents.printToPDF:
const { app, BrowserWindow } = require('electron')
const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')
app.whenReady().then(() => {
const win = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.on('did-finish-load', () => {
// Use default printing options
const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf')
win.webContents.printToPDF({}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
})
})
请参阅 Page.printToPdf 了解更多信息。
¥See Page.printToPdf for more information.
contents.addWorkSpace(path)
-
path字符串¥
pathstring
将指定路径添加到 DevTools 工作区。必须在创建 DevTools 后使用:
¥Adds the specified path to DevTools workspace. Must be used after DevTools creation:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
win.webContents.addWorkSpace(__dirname)
})
contents.removeWorkSpace(path)
-
path字符串¥
pathstring
从 DevTools 工作区中删除指定的路径。
¥Removes the specified path from DevTools workspace.
contents.setDevToolsWebContents(devToolsWebContents)
devToolsWebContentsWebContents
使用 devToolsWebContents 作为目标 WebContents 来显示开发工具。
¥Uses the devToolsWebContents as the target WebContents to show devtools.
devToolsWebContents 不得进行任何导航,且通话后不得用于其他用途。
¥The devToolsWebContents must not have done any navigation, and it should not
be used for other purposes after the call.
默认情况下,Electron 通过创建具有原生视图的内部 WebContents 来管理开发工具,开发者对此的控制非常有限。通过 setDevToolsWebContents 方法,开发者可以使用任何 WebContents 来显示其中的 devtools,包括 BrowserWindow、BrowserView 和 <webview> 标签。
¥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.
请注意,关闭开发工具不会破坏 devToolsWebContents,调用者有责任破坏 devToolsWebContents。
¥Note that closing the devtools does not destroy the devToolsWebContents, it
is caller's responsibility to destroy devToolsWebContents.
在 <webview> 标签中显示开发工具的示例:
¥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()
})
在 BrowserWindow 中显示开发工具的示例:
¥An example of showing devtools in a BrowserWindow:
const { app, BrowserWindow } = require('electron')
let win = null
let devtools = null
app.whenReady().then(() => {
win = new BrowserWindow()
devtools = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.setDevToolsWebContents(devtools.webContents)
win.webContents.openDevTools({ mode: 'detach' })
})
contents.openDevTools([options])
打开开发工具。
¥Opens the devtools.
当 contents 是 <webview> 标签时,默认情况下 mode 将是 detach,显式传递空 mode 可以强制使用上次使用的停靠状态。
¥When contents is a <webview> tag, the mode would be detach by default,
explicitly passing an empty mode can force using last used dock state.
在 Windows 上,如果启用了 Windows Control Overlay,Devtools 将使用 mode: 'detach' 打开。
¥On Windows, if Windows Control Overlay is enabled, Devtools will be opened with mode: 'detach'.
contents.closeDevTools()
关闭开发工具。
¥Closes the devtools.
contents.isDevToolsOpened()
返回 boolean - devtools 是否打开。
¥Returns boolean - Whether the devtools is opened.
contents.isDevToolsFocused()
返回 boolean - devtools 视图是否聚焦。
¥Returns boolean - Whether the devtools view is focused .
contents.getDevToolsTitle()
返回 string - DevTools 窗口的当前标题。仅当 DevTools 在 undocked 或 detach 模式下打开时,此信息才可见。
¥Returns string - the current title of the DevTools window. This will only be visible
if DevTools is opened in undocked or detach mode.
contents.setDevToolsTitle(title)
-
title字符串¥
titlestring
将 DevTools 窗口的标题更改为 title。仅当 DevTools 在 undocked 或 detach 模式下打开时,此信息才可见。
¥Changes the title of the DevTools window to title. This will only be visible if DevTools is
opened in undocked or detach mode.
contents.toggleDevTools()
切换开发者工具。
¥Toggles the developer tools.
contents.inspectElement(x, y)
-
x整数¥
xInteger -
y整数¥
yInteger
开始检查位置 (x, y) 处的元素。
¥Starts inspecting element at position (x, y).
contents.inspectSharedWorker()
打开共享工作线程上下文的开发者工具。
¥Opens the developer tools for the shared worker context.
contents.inspectSharedWorkerById(workerId)
-
workerId字符串¥
workerIdstring
根据共享 worker 的 ID 检查共享 worker。
¥Inspects the shared worker based on its ID.
contents.getAllSharedWorkers()
返回 SharedWorkerInfo[] - 有关所有共享工作者的信息。
¥Returns SharedWorkerInfo[] - Information about all Shared Workers.
contents.inspectServiceWorker()
打开服务工作线程上下文的开发者工具。
¥Opens the developer tools for the service worker context.
contents.send(channel, ...args)
-
channel字符串¥
channelstring -
...args任何[]¥
...argsany[]
通过 channel 将异步消息连同参数一起发送到渲染器进程。参数将与 结构化克隆算法 一起序列化,就像 postMessage 一样,因此不会包含原型链。发送函数、Promise、Symbols、WeakMap 或 WeakSet 将引发异常。
¥Send an asynchronous message to the renderer process via channel, along with
arguments. Arguments will be serialized with the Structured Clone Algorithm,
just like postMessage, so prototype chains will not be
included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will
throw an exception.
发送非标准 JavaScript 类型(例如 DOM 对象或特殊 Electron 对象)将引发异常。
¥Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception.
如需更多阅读,请参阅 Electron 的 IPC 指南。
¥For additional reading, refer to Electron's IPC guide.
contents.sendToFrame(frameId, channel, ...args)
-
frameIdInteger | [number, number] - 要发送到的帧的 ID,如果该帧与主帧位于不同的进程中,则为一对[processId, frameId]。¥
frameIdInteger | [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字符串¥
channelstring -
...args任何[]¥
...argsany[]
通过 channel 将异步消息连同参数一起发送到渲染器进程中的特定帧。参数将与 结构化克隆算法 一起序列化,就像 postMessage 一样,因此不会包含原型链。发送函数、Promise、Symbols、WeakMap 或 WeakSet 将引发异常。
¥Send an asynchronous message to a specific frame in a renderer process via
channel, along with arguments. Arguments will be serialized with the
Structured Clone Algorithm, just like postMessage, so prototype
chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or
WeakSets will throw an exception.
注意:发送非标准 JavaScript 类型(例如 DOM 对象或特殊 Electron 对象)将引发异常。
¥NOTE: Sending non-standard JavaScript types such as DOM objects or special Electron objects will throw an exception.
渲染器进程可以通过使用 ipcRenderer 模块监听 channel 来处理消息。
¥The renderer process can handle the message by listening to channel with the
ipcRenderer module.
如果你想获取给定渲染器上下文的 frameId,你应该使用 webFrame.routingId 值。例如。
¥If you want to get the frameId of a given renderer context you should use
the webFrame.routingId value. E.g.
// In a renderer process
console.log('My frameId is:', require('electron').webFrame.routingId)
你还可以从主进程中所有传入的 IPC 消息中读取 frameId。
¥You can also read frameId from all incoming IPC messages in the main process.
// In the main process
ipcMain.on('ping', (event) => {
console.info('Message came from frameId:', event.frameId)
})
contents.postMessage(channel, message, [transfer])
-
channel字符串¥
channelstring -
message任意¥
messageany -
transferMessagePortMain[](可选)¥
transferMessagePortMain[] (optional)
向渲染器进程发送消息,可选择转移零个或多个 MessagePortMain 对象的所有权。
¥Send a message to the renderer process, optionally transferring ownership of
zero or more MessagePortMain objects.
通过访问触发事件的 ports 属性,传输的 MessagePortMain 对象将在渲染器进程中可用。当它们到达渲染器时,它们将是原生 DOM MessagePort 对象。
¥The transferred MessagePortMain objects will be available in the renderer
process by accessing the ports property of the emitted event. When they
arrive in the renderer, they will be native DOM MessagePort objects.
例如:
¥For example:
// Main process
const win = new BrowserWindow()
const { port1, port2 } = new MessageChannelMain()
win.webContents.postMessage('port', { message: 'hello' }, [port1])
// Renderer process
ipcRenderer.on('port', (e, msg) => {
const [port] = e.ports
// ...
})
contents.enableDeviceEmulation(parameters)
-
parameters对象¥
parametersObject-
screenPosition字符串 - 指定要模拟的屏幕类型(默认值:desktop):¥
screenPositionstring - Specify the screen type to emulate (default:desktop):-
desktop- 桌面屏幕类型。¥
desktop- Desktop screen type. -
mobile- 移动屏幕类型。¥
mobile- Mobile screen type.
-
-
screenSize尺寸 - 设置模拟屏幕尺寸(screenPosition == mobile)。¥
screenSizeSize - Set the emulated screen size (screenPosition == mobile). -
viewPosition观点 - 将视图定位在屏幕上(screenPosition == mobile)(默认:{ x: 0, y: 0 }).¥
viewPositionPoint - Position the view on the screen (screenPosition == mobile) (default:{ x: 0, y: 0 }). -
deviceScaleFactor整数 - 设置设备比例因子(如果零默认为原始设备比例因子)(默认值:0).¥
deviceScaleFactorInteger - Set the device scale factor (if zero defaults to original device scale factor) (default:0). -
viewSize尺寸 - 设置模拟视图大小(空表示不覆盖)¥
viewSizeSize - Set the emulated view size (empty means no override) -
scale漂浮 - 可用空间内模拟视图的比例(不适合视图模式)(默认值:1).¥
scaleFloat - Scale of emulated view inside available space (not in fit to view mode) (default:1).
-
使用给定参数启用设备模拟。
¥Enable device emulation with the given parameters.
contents.disableDeviceEmulation()
禁用 webContents.enableDeviceEmulation 启用的设备模拟。
¥Disable device emulation enabled by webContents.enableDeviceEmulation.
contents.sendInputEvent(inputEvent)
-
inputEvent鼠标输入事件 | 鼠标滚轮输入事件 | 键盘输入事件¥
inputEventMouseInputEvent | MouseWheelInputEvent | KeyboardInputEvent
将输入 event 发送到页面。
¥Sends an input event to the page.
[!NOTE] 包含内容的
BrowserWindow需要获得焦点才能使sendInputEvent()正常工作。¥[!NOTE] The
BrowserWindowcontaining the contents needs to be focused forsendInputEvent()to work.
contents.beginFrameSubscription([onlyDirty ,]callback)
-
onlyDirty布尔值(可选) - 默认为false。¥
onlyDirtyboolean (optional) - Defaults tofalse. -
callback函数¥
callbackFunction-
imageNativeImage -
dirtyRect长方形¥
dirtyRectRectangle
-
开始订阅演示事件和捕获的帧,当有演示事件时,callback 将与 callback(image, dirtyRect) 一起调用。
¥Begin subscribing for presentation events and captured frames, the callback
will be called with callback(image, dirtyRect) when there is a presentation
event.
image 是 NativeImage 的一个实例,用于存储捕获的帧。
¥The image is an instance of NativeImage that stores the
captured frame.
dirtyRect 是一个具有 x, y, width, height 属性的对象,用于描述页面的哪一部分被重新绘制。如果 onlyDirty 设置为 true,则 image 将仅包含重绘区域。onlyDirty 默认为 false。
¥The dirtyRect is an object with x, y, width, height properties that
describes which part of the page was repainted. If onlyDirty is set to
true, image will only contain the repainted area. onlyDirty defaults to
false.
contents.endFrameSubscription()
结束对框架渲染事件的订阅。
¥End subscribing for frame presentation events.
contents.startDrag(item)
-
item对象¥
itemObject-
file字符串 - 正在拖动的文件的路径。¥
filestring - The path to the file being dragged. -
files字符串[](可选) - 正在拖动的文件的路径。(files将覆盖file字段)¥
filesstring[] (optional) - The paths to the files being dragged. (fileswill overridefilefield) -
iconNativeImage | 字符串 - 在 macOS 上,该图片必须非空。¥
iconNativeImage | string - The image must be non-empty on macOS.
-
将 item 设置为当前拖拽操作的拖动项,file 为要拖动的文件的绝对路径,icon 为拖动时光标下显示的图片。
¥Sets the item as dragging item for current drag-drop operation, file is the
absolute path of the file to be dragged, and icon is the image showing under
the cursor when dragging.
contents.savePage(fullPath, saveType)
-
fullPath字符串 - 绝对文件路径。¥
fullPathstring - The absolute file path. -
saveType字符串 - 指定保存类型。¥
saveTypestring - Specify the save type.-
HTMLOnly- 仅保存页面的 HTML。¥
HTMLOnly- Save only the HTML of the page. -
HTMLComplete- 保存完整的 html 页面。¥
HTMLComplete- Save complete-html page. -
MHTML- 将完整的 html 页面保存为 MHTML。¥
MHTML- Save complete-html page as MHTML.
-
返回 Promise<void> - 如果保存页面则解决。
¥Returns Promise<void> - resolves if the page is saved.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.loadURL('https://github.com')
win.webContents.on('did-finish-load', async () => {
win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => {
console.log('Page was saved successfully.')
}).catch(err => {
console.log(err)
})
})
contents.showDefinitionForSelection() macOS
显示搜索页面上所选单词的弹出词典。
¥Shows pop-up dictionary that searches the selected word on the page.
contents.isOffscreen()
返回 boolean - 指示是否启用离屏渲染。
¥Returns boolean - Indicates whether offscreen rendering is enabled.
contents.startPainting()
如果离屏渲染已启用且未绘画,则开始绘画。
¥If offscreen rendering is enabled and not painting, start painting.
contents.stopPainting()
如果启用了离屏渲染并进行绘画,请停止绘画。
¥If offscreen rendering is enabled and painting, stop painting.
contents.isPainting()
返回 boolean - 如果启用离屏渲染,则返回当前是否正在绘制。
¥Returns boolean - If offscreen rendering is enabled returns whether it is currently painting.
contents.setFrameRate(fps)
-
fps整数¥
fpsInteger
如果启用离屏渲染,则将帧速率设置为指定的数字。仅接受 1 到 240 之间的值。
¥If offscreen rendering is enabled sets the frame rate to the specified number. Only values between 1 and 240 are accepted.
contents.getFrameRate()
返回 Integer - 如果启用离屏渲染,则返回当前帧速率。
¥Returns Integer - If offscreen rendering is enabled returns the current frame rate.
contents.invalidate()
计划对该网页内容所在的窗口进行完全重绘。
¥Schedules a full repaint of the window this web contents is in.
如果启用离屏渲染,则该帧无效并通过 'paint' 事件生成一个新帧。
¥If offscreen rendering is enabled invalidates the frame and generates a new
one through the 'paint' event.
contents.getWebRTCIPHandlingPolicy()
返回 string - 返回 WebRTC IP 处理策略。
¥Returns string - Returns the WebRTC IP Handling Policy.
contents.setWebRTCIPHandlingPolicy(policy)
-
policy字符串 - 指定 WebRTC IP 处理策略。¥
policystring - Specify the WebRTC IP Handling Policy.-
default- 公开用户的公共和本地 IP。这是默认行为。当使用该策略时,WebRTC 有权枚举所有接口并绑定它们以发现公共接口。¥
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- 暴露用户的公共 IP,但不暴露用户的本地 IP。使用此策略时,WebRTC 应该仅使用 http 使用的默认路由。这不会公开任何本地地址。¥
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- 公开用户的公共和本地 IP。使用此策略时,WebRTC 应该仅使用 http 使用的默认路由。这也公开了关联的默认私有地址。默认路由是多宿主端点上操作系统选择的路由。¥
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- 不暴露公共或本地 IP。使用此策略时,WebRTC 应仅使用 TCP 来联系对等方或服务器,除非代理服务器支持 UDP。¥
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.
-
设置 WebRTC IP 处理策略允许你控制通过 WebRTC 公开哪些 IP。详细信息请参见 BrowserLeaks。
¥Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See BrowserLeaks for more details.
contents.getWebRTCUDPPortRange()
返回 Object:
¥Returns Object:
-
min整数 - WebRTC 应使用的最小 UDP 端口号。¥
minInteger - The minimum UDP port number that WebRTC should use. -
max整数 - WebRTC 应使用的最大 UDP 端口号。¥
maxInteger - The maximum UDP port number that WebRTC should use.
默认情况下,该值为 { min: 0, max: 0 } ,这对 udp 端口范围没有限制。
¥By default this value is { min: 0, max: 0 } , which would apply no restriction on the udp port range.
contents.setWebRTCUDPPortRange(udpPortRange)
-
udpPortRange对象¥
udpPortRangeObject-
min整数 - WebRTC 应使用的最小 UDP 端口号。¥
minInteger - The minimum UDP port number that WebRTC should use. -
max整数 - WebRTC 应使用的最大 UDP 端口号。¥
maxInteger - The maximum UDP port number that WebRTC should use.
-
设置 WebRTC UDP 端口范围允许你限制 WebRTC 使用的 udp 端口范围。默认情况下,端口范围不受限制。
¥Setting the WebRTC UDP Port Range allows you to restrict the udp port range used by WebRTC. By default the port range is unrestricted.
[!NOTE] 要重置为不受限制的端口范围,此值应设置为
{ min: 0, max: 0 }。¥[!NOTE] To reset to an unrestricted port range this value should be set to
{ min: 0, max: 0 }.
contents.getMediaSourceId(requestWebContents)
-
requestWebContentsWebContents - 该 ID 将注册到的 Web 内容。¥
requestWebContentsWebContents - Web contents that the id will be registered to.
返回 string - WebContents 流的标识符。该标识符可以与 navigator.mediaDevices.getUserMedia 一起使用,使用 chromeMediaSource 或 tab。该标识符仅限于其注册的网页内容,且有效期仅 10 秒。
¥Returns string - The identifier of a WebContents stream. This identifier can be used
with navigator.mediaDevices.getUserMedia using a chromeMediaSource of tab.
The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds.
contents.getOSProcessId()
返回 Integer - 相关渲染器进程的操作系统 pid。
¥Returns Integer - The operating system pid of the associated renderer
process.
contents.getProcessId()
返回 Integer - 关联渲染器的 Chromium 内部 pid。可以与帧特定导航事件传递的 frameProcessId 进行比较(例如 did-frame-navigate)
¥Returns Integer - The Chromium internal pid of the associated renderer. Can
be compared to the frameProcessId passed by frame specific navigation events
(e.g. did-frame-navigate)
contents.takeHeapSnapshot(filePath)
-
filePath字符串 - 输出文件的路径。¥
filePathstring - Path to the output file.
返回 Promise<void> - 指示快照是否创建成功。
¥Returns Promise<void> - Indicates whether the snapshot has been created successfully.
拍摄 V8 堆快照并将其保存到 filePath。
¥Takes a V8 heap snapshot and saves it to filePath.
contents.getBackgroundThrottling()
返回 boolean - 当页面变为后台时,此 WebContents 是否会限制动画和计时器。这也会影响页面可见性 API。
¥Returns boolean - whether or not this WebContents will throttle animations and timers
when the page becomes backgrounded. This also affects the Page Visibility API.
contents.setBackgroundThrottling(allowed)
History
-
allowed布尔值¥
allowedboolean
控制当页面变为后台时此 WebContents 是否会限制动画和计时器。这也会影响页面可见性 API。
¥Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API.
contents.getType()
返回 string - webContent 的类型。可以是 backgroundPage、window、browserView、remote、webview 或 offscreen。
¥Returns string - the type of the webContent. Can be backgroundPage, window, browserView, remote, webview or offscreen.
contents.setImageAnimationPolicy(policy)
-
policy字符串 - 可以是animate、animateOnce或noAnimation。¥
policystring - Can beanimate,animateOnceornoAnimation.
设置此 webContents 的图片动画策略。该策略仅影响新图片,当前正在动画化的现有图片不受影响。这是 Chromium 中的一个已知限制,你可以强制使用 img.src = img.src 重新计算图片动画,这将导致没有网络流量,但会更新动画策略。
¥Sets the image animation policy for this webContents. The policy only affects
new images, existing images that are currently being animated are unaffected.
This is a known limitation in Chromium, you can force image animation to be
recalculated with img.src = img.src which will result in no network traffic
but will update the animation policy.
这对应于 Chromium 中的 animationPolicy 辅助功能。
¥This corresponds to the animationPolicy accessibility feature in Chromium.
实例属性
¥Instance Properties
contents.ipc 只读
¥contents.ipc Readonly
IpcMain 的范围仅限于从此 WebContents 发送的 IPC 消息。
¥An IpcMain scoped to just IPC messages sent from this
WebContents.
使用 ipcRenderer.send、ipcRenderer.sendSync 或 ipcRenderer.postMessage 发送的 IPC 消息将按以下顺序传递:
¥IPC messages sent with ipcRenderer.send, ipcRenderer.sendSync or
ipcRenderer.postMessage will be delivered in the following order:
contents.on('ipc-message')contents.mainFrame.on(channel)contents.ipc.on(channel)ipcMain.on(channel)
将按以下顺序检查在 invoke 上注册的处理程序。第一个定义的将被调用,其余的将被忽略。
¥Handlers registered with invoke will be checked in the following order. The
first one that is defined will be called, the rest will be ignored.
contents.mainFrame.handle(channel)contents.handle(channel)ipcMain.handle(channel)
在 WebContents 上注册的处理程序或事件监听器将接收从任何框架(包括子框架)发送的 IPC 消息。大多数情况下,只有主机可以发送 IPC 消息。然而,如果启用了 nodeIntegrationInSubFrames 选项,子帧也可以发送 IPC 消息。在这种情况下,处理程序应检查 IPC 事件的 senderFrame 属性,以确保消息来自预期的帧。或者,直接使用 WebFrameMain.ipc 接口在适当的帧上注册处理程序。
¥A handler or event listener registered on the WebContents will receive IPC
messages sent from any frame, including child frames. In most cases, only the
main frame can send IPC messages. However, if the nodeIntegrationInSubFrames
option is enabled, it is possible for child frames to send IPC messages also.
In that case, handlers should check the senderFrame property of the IPC event
to ensure that the message is coming from the expected frame. Alternatively,
register handlers on the appropriate frame directly using the
WebFrameMain.ipc interface.
contents.audioMuted
确定此页面是否静音的 boolean 属性。
¥A boolean property that determines whether this page is muted.
contents.userAgent
确定此网页的用户代理的 string 属性。
¥A string property that determines the user agent for this web page.
contents.zoomLevel
确定此 Web 内容的缩放级别的 number 属性。
¥A number property that determines the zoom level for this web contents.
原始大小为 0,上方或下方的每个增量表示放大或缩小 20%,分别达到原始大小的 300% 和 50% 的默认限制。其公式为 scale := 1.2 ^ level。
¥The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is scale := 1.2 ^ level.
contents.zoomFactor
确定此 Web 内容的缩放系数的 number 属性。
¥A number property that determines the zoom factor for this web contents.
缩放系数是缩放百分比除以 100,因此 300% = 3.0。
¥The zoom factor is the zoom percent divided by 100, so 300% = 3.0.
contents.frameRate
Integer 属性,将 Web 内容的帧速率设置为指定的数字。仅接受 1 到 240 之间的值。
¥An Integer property that sets the frame rate of the web contents to the specified number.
Only values between 1 and 240 are accepted.
仅当启用离屏渲染时才适用。
¥Only applicable if offscreen rendering is enabled.
contents.id 只读
¥contents.id Readonly
Integer 代表此 WebContents 的唯一 ID。每个 ID 在整个 Electron 应用的所有 WebContents 实例中都是唯一的。
¥A Integer representing the unique ID of this WebContents. Each ID is unique among all WebContents instances of the entire Electron application.
contents.session 只读
¥contents.session Readonly
此 webContents 使用的 Session。
¥A Session used by this webContents.
contents.navigationHistory 只读
¥contents.navigationHistory Readonly
此 webContents 使用的 NavigationHistory。
¥A NavigationHistory used by this webContents.
contents.hostWebContents 只读
¥contents.hostWebContents Readonly
可能拥有此 WebContents 的 WebContents 实例。
¥A WebContents instance that might own this WebContents.
contents.devToolsWebContents 只读
¥contents.devToolsWebContents Readonly
WebContents | null 属性,表示与给定 WebContents 关联的 DevTools WebContents。
¥A WebContents | null property that represents the of DevTools WebContents associated with a given WebContents.
[!NOTE] 用户不应存储此对象,因为关闭 DevTools 后,它可能会变为
null。¥[!NOTE] Users should never store this object because it may become
nullwhen the DevTools has been closed.
contents.debugger 只读
¥contents.debugger Readonly
此 webContents 的 Debugger 实例。
¥A Debugger instance for this webContents.
contents.backgroundThrottling
History
一个 boolean 属性,用于确定当页面变为后台时此 WebContents 是否会限制动画和计时器。这也会影响页面可见性 API。
¥A boolean property that determines whether or not this WebContents will throttle animations and timers
when the page becomes backgrounded. This also affects the Page Visibility API.
contents.mainFrame 只读
¥contents.mainFrame Readonly
WebFrameMain 属性,表示页面框架层次结构的顶部框架。
¥A WebFrameMain property that represents the top frame of the page's frame hierarchy.
contents.opener 只读
¥contents.opener Readonly
WebFrameMain | null 属性,表示使用 open() 或通过使用目标属性导航链接来打开此 WebContents 的框架。
¥A WebFrameMain | null property that represents the frame that opened this WebContents, either
with open(), or by navigating a link with a target attribute.
contents.focusedFrame 只读
¥contents.focusedFrame Readonly
WebFrameMain | null 属性,表示此 WebContents 中当前获得焦点的框架。可以是顶部框架、内部 <iframe> 或 null(如果未获得焦点)。
¥A WebFrameMain | null property that represents the currently focused frame in this WebContents.
Can be the top frame, an inner <iframe>, or null if nothing is focused.