Skip to main content

BrowserWindow

创建和控制浏览器窗口。

¥Create and control browser windows.

进程:主进程

¥Process: Main

app 模块的 ready 事件发出之前,该模块无法使用。

¥This module cannot be used until the ready event of the app module is emitted.

// In the main process.
const { BrowserWindow } = require('electron')

const win = new BrowserWindow({ width: 800, height: 600 })

// Load a remote URL
win.loadURL('https://github.com')

// Or load a local HTML file
win.loadFile('index.html')

窗口定制

¥Window customization

BrowserWindow 类公开了修改应用窗口的外观和行为的各种方法。更多详细信息,请参阅 窗口定制 教程。

¥The BrowserWindow class exposes various ways to modify the look and behavior of your app's windows. For more details, see the Window Customization tutorial.

优雅地展现窗外

¥Showing the window gracefully

当直接在窗口中加载页面时,用户可能会看到页面逐渐加载,这对于原生应用来说不是一个好的体验。为了使窗口显示没有视觉闪烁,针对不同情况有两种解决方案。

¥When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without a visual flash, there are two solutions for different situations.

使用 ready-to-show 事件

¥Using the ready-to-show event

加载页面时,如果窗口尚未显示,渲染器进程第一次渲染页面时将发出 ready-to-show 事件。在此事件之后显示窗口将不会出现视觉闪烁:

¥While loading the page, the ready-to-show event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash:

const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => {
win.show()
})

该事件通常在 did-finish-load 事件之后发出,但对于具有许多远程资源的页面,它可能在 did-finish-load 事件之前发出。

¥This event is usually emitted after the did-finish-load event, but for pages with many remote resources, it may be emitted before the did-finish-load event.

请注意,使用此事件意味着渲染器将被视为 "visible" 并进行绘制,即使 show 为 false。如果你使用 paintWhenInitiallyHidden: false,此事件将永远不会触发

¥Please note that using this event implies that the renderer will be considered "visible" and paint even though show is false. This event will never fire if you use paintWhenInitiallyHidden: false

设置 backgroundColor 属性

¥Setting the backgroundColor property

对于复杂的应用,ready-to-show 事件可能发出得太晚,使应用感觉很慢。在这种情况下,建议立即显示窗口,并使用靠近应用背景的 backgroundColor

¥For a complex app, the ready-to-show event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a backgroundColor close to your app's background:

const { BrowserWindow } = require('electron')

const win = new BrowserWindow({ backgroundColor: '#2e2c29' })
win.loadURL('https://github.com')

请注意,即使对于使用 ready-to-show 事件的应用,仍然建议设置 backgroundColor 以使应用感觉更原生。

¥Note that even for apps that use ready-to-show event, it is still recommended to set backgroundColor to make the app feel more native.

有效 backgroundColor 值的一些示例包括:

¥Some examples of valid backgroundColor values include:

const win = new BrowserWindow()
win.setBackgroundColor('hsl(230, 100%, 50%)')
win.setBackgroundColor('rgb(255, 145, 145)')
win.setBackgroundColor('#ff00a3')
win.setBackgroundColor('blueviolet')

有关这些颜色类型的更多信息,请参阅 win.setBackgroundColor 中的有效选项。

¥For more information about these color types see valid options in win.setBackgroundColor.

父窗口和子窗口

¥Parent and child windows

通过使用 parent 选项,你可以创建子窗口:

¥By using parent option, you can create child windows:

const { BrowserWindow } = require('electron')

const top = new BrowserWindow()
const child = new BrowserWindow({ parent: top })
child.show()
top.show()

child 窗口将始终显示在 top 窗口的顶部。

¥The child window will always show on top of the top window.

¥Modal windows

模态窗口是禁用父窗口的子窗口。要创建模态窗口,你必须设置 parentmodal 选项:

¥A modal window is a child window that disables parent window. To create a modal window, you have to set both the parent and modal options:

const { BrowserWindow } = require('electron')

const top = new BrowserWindow()
const child = new BrowserWindow({ parent: top, modal: true, show: false })
child.loadURL('https://github.com')
child.once('ready-to-show', () => {
child.show()
})

页面可见性

¥Page visibility

页面可见性 API 的工作原理如下:

¥The Page Visibility API works as follows:

  • 在所有平台上,可见性状态都会跟踪窗口是否隐藏/最小化。

    ¥On all platforms, the visibility state tracks whether the window is hidden/minimized or not.

  • 此外,在 macOS 上,可见性状态还跟踪窗口遮挡状态。如果窗口被另一个窗口遮挡(即完全覆盖),则可见性状态将为 hidden。在其他平台上,仅当窗口最小化或使用 win.hide() 显式隐藏时,可见性状态才会为 hidden

    ¥Additionally, on macOS, the visibility state also tracks the window occlusion state. If the window is occluded (i.e. fully covered) by another window, the visibility state will be hidden. On other platforms, the visibility state will be hidden only when the window is minimized or explicitly hidden with win.hide().

  • 如果使用 show: false 创建 BrowserWindow,则尽管窗口实际上处于隐藏状态,但初始可见性状态将为 visible

    ¥If a BrowserWindow is created with show: false, the initial visibility state will be visible despite the window actually being hidden.

  • 如果禁用 backgroundThrottling,则即使窗口最小化、遮挡或隐藏,可见性状态也将保持 visible

    ¥If backgroundThrottling is disabled, the visibility state will remain visible even if the window is minimized, occluded, or hidden.

建议你在可见性状态为 hidden 时暂停昂贵的操作,以最大程度地减少功耗。

¥It is recommended that you pause expensive operations when the visibility state is hidden in order to minimize power consumption.

平台须知

¥Platform notices

  • 在 macOS 上,模式窗口将显示为附加到父窗口的工作表。

    ¥On macOS modal windows will be displayed as sheets attached to the parent window.

  • 在 macOS 上,当父窗口移动时,子窗口将保持与父窗口的相对位置,而在 Windows 和 Linux 上,子窗口不会移动。

    ¥On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move.

  • 在 Linux 上,模式窗口的类型将更改为 dialog

    ¥On Linux the type of modal windows will be changed to dialog.

  • 在 Linux 上,许多桌面环境不支持隐藏模式窗口。

    ¥On Linux many desktop environments do not support hiding a modal window.

类:BrowserWindow 继承自 BaseWindow

¥Class: BrowserWindow extends BaseWindow

创建和控制浏览器窗口。

¥Create and control browser windows.

进程:主进程

¥Process: Main

BrowserWindowEventEmitter

¥BrowserWindow is an EventEmitter.

它创建一个新的 BrowserWindow,其原生属性由 options 设置。

¥It creates a new BrowserWindow with native properties as set by the options.

new BrowserWindow([options])

  • options 浏览器窗口构造函数选项(可选)

    ¥options BrowserWindowConstructorOptions (optional)

    • webPreferences WebPreferences(可选) - 网页功能的设置。

      ¥webPreferences WebPreferences (optional) - Settings of web page's features.

      • devTools 布尔值(可选) - 是否启用 DevTools。如果设置为 false,则无法使用 BrowserWindow.webContents.openDevTools() 打开 DevTools。默认为 true

        ¥devTools boolean (optional) - Whether to enable DevTools. If it is set to false, can not use BrowserWindow.webContents.openDevTools() to open DevTools. Default is true.

      • nodeIntegration 布尔值(可选) - 是否启用节点集成。默认为 false

        ¥nodeIntegration boolean (optional) - Whether node integration is enabled. Default is false.

      • nodeIntegrationInWorker 布尔值(可选) - 是否在 Web Worker 中启用节点集成。默认为 false。有关此内容的更多信息,请参阅 多线程

        ¥nodeIntegrationInWorker boolean (optional) - Whether node integration is enabled in web workers. Default is false. More about this can be found in Multithreading.

      • nodeIntegrationInSubFrames 布尔值(可选) - 用于在 iframe 和子窗口等子框架中启用 Node.js 支持的实验选项。你的所有预加载将为每个 iframe 加载,你可以使用 process.isMainFrame 来确定你是否在主框架中。

        ¥nodeIntegrationInSubFrames boolean (optional) - Experimental option for enabling Node.js support in sub-frames such as iframes and child windows. All your preloads will load for every iframe, you can use process.isMainFrame to determine if you are in the main frame or not.

      • preload 字符串(可选) - 指定将在页面中运行其他脚本之前加载的脚本。无论节点集成是打开还是关闭,该脚本始终可以访问 Node API。该值应该是脚本的绝对文件路径。当节点集成关闭时,预加载脚本可以将节点全局符号重新引入全局作用域。参见示例 此处

        ¥preload string (optional) - Specifies a script that will be loaded before other scripts run in the page. This script will always have access to node APIs no matter whether node integration is turned on or off. The value should be the absolute file path to the script. When node integration is turned off, the preload script can reintroduce Node global symbols back to the global scope. See example here.

      • sandbox 布尔值(可选) - 如果设置,这会将与窗口关联的渲染器沙箱化,使其与 Chromium 操作系统级沙箱兼容并禁用 Node.js 引擎。这与 nodeIntegration 选项不同,预加载脚本可用的 API 更加有限。了解有关选项 此处 的更多信息。

        ¥sandbox boolean (optional) - If set, this will sandbox the renderer associated with the window, making it compatible with the Chromium OS-level sandbox and disabling the Node.js engine. This is not the same as the nodeIntegration option and the APIs available to the preload script are more limited. Read more about the option here.

      • session 会议(可选) - 设置页面使用的会话。你还可以选择使用接受分区字符串的 partition 选项,而不是直接传递 Session 对象。当同时提供 sessionpartition 时,优先选择 session。默认是默认会话。

        ¥session Session (optional) - Sets the session used by the page. Instead of passing the Session object directly, you can also choose to use the partition option instead, which accepts a partition string. When both session and partition are provided, session will be preferred. Default is the default session.

      • partition 字符串(可选) - 根据会话的分区字符串设置页面使用的会话。如果 partitionpersist: 开头,则页面将使用可用于应用中具有相同 partition 的所有页面的持久会话。如果没有 persist: 前缀,页面将使用内存中会话。通过分配相同的 partition,多个页面可以共享同一个会话。默认是默认会话。

        ¥partition string (optional) - Sets the session used by the page according to the session's partition string. If partition starts with persist:, the page will use a persistent session available to all pages in the app with the same partition. If there is no persist: prefix, the page will use an in-memory session. By assigning the same partition, multiple pages can share the same session. Default is the default session.

      • zoomFactor 号码(可选) - 页面默认缩放倍数,3.0 代表 300%。默认为 1.0

        ¥zoomFactor number (optional) - The default zoom factor of the page, 3.0 represents 300%. Default is 1.0.

      • javascript 布尔值(可选) - 启用 JavaScript 支持。默认为 true

        ¥javascript boolean (optional) - Enables JavaScript support. Default is true.

      • webSecurity 布尔值(可选) - 当 false 时,它会禁用同源策略(通常是人们使用测试网站),如果用户没有设置此选项,则将 allowRunningInsecureContent 设置为 true。默认为 true

        ¥webSecurity boolean (optional) - When false, it will disable the same-origin policy (usually using testing websites by people), and set allowRunningInsecureContent to true if this options has not been set by user. Default is true.

      • allowRunningInsecureContent 布尔值(可选) - 允许 https 页面从 http URL 运行 JavaScript、CSS 或插件。默认为 false

        ¥allowRunningInsecureContent boolean (optional) - Allow an https page to run JavaScript, CSS or plugins from http URLs. Default is false.

      • images 布尔值(可选) - 启用图片支持。默认为 true

        ¥images boolean (optional) - Enables image support. Default is true.

      • imageAnimationPolicy 字符串(可选) - 指定如何运行图片动画(例如 GIF)。可以是 animateanimateOncenoAnimation。默认为 animate

        ¥imageAnimationPolicy string (optional) - Specifies how to run image animations (E.g. GIFs). Can be animate, animateOnce or noAnimation. Default is animate.

      • textAreasAreResizable 布尔值(可选) - 使 TextArea 元素可调整大小。默认为 true

        ¥textAreasAreResizable boolean (optional) - Make TextArea elements resizable. Default is true.

      • webgl 布尔值(可选) - 启用 WebGL 支持。默认为 true

        ¥webgl boolean (optional) - Enables WebGL support. Default is true.

      • plugins 布尔值(可选) - 是否应启用插件。默认为 false

        ¥plugins boolean (optional) - Whether plugins should be enabled. Default is false.

      • experimentalFeatures 布尔值(可选) - 启用 Chromium 的实验性功能。默认为 false

        ¥experimentalFeatures boolean (optional) - Enables Chromium's experimental features. Default is false.

      • scrollBounce 布尔值(可选)macOS - 在 macOS 上启用滚动弹跳(橡皮筋)效果。默认为 false

        ¥scrollBounce boolean (optional) macOS - Enables scroll bounce (rubber banding) effect on macOS. Default is false.

      • enableBlinkFeatures 字符串(可选) - 由 , 分隔的功能字符串列表,例如要启用的 CSSVariables,KeyboardEventKey。支持的功能字符串的完整列表可以在 RuntimeEnabledFeatures.json5 文件中找到。

        ¥enableBlinkFeatures string (optional) - A list of feature strings separated by ,, like CSSVariables,KeyboardEventKey to enable. The full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.

      • disableBlinkFeatures 字符串(可选) - 由 , 分隔的功能字符串列表,例如要禁用的 CSSVariables,KeyboardEventKey。支持的功能字符串的完整列表可以在 RuntimeEnabledFeatures.json5 文件中找到。

        ¥disableBlinkFeatures string (optional) - A list of feature strings separated by ,, like CSSVariables,KeyboardEventKey to disable. The full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.

      • defaultFontFamily 对象(可选) - 设置字体系列的默认字体。

        ¥defaultFontFamily Object (optional) - Sets the default font for the font-family.

        • standard 字符串(可选) - 默认为 Times New Roman

          ¥standard string (optional) - Defaults to Times New Roman.

        • serif 字符串(可选) - 默认为 Times New Roman

          ¥serif string (optional) - Defaults to Times New Roman.

        • sansSerif 字符串(可选) - 默认为 Arial

          ¥sansSerif string (optional) - Defaults to Arial.

        • monospace 字符串(可选) - 默认为 Courier New

          ¥monospace string (optional) - Defaults to Courier New.

        • cursive 字符串(可选) - 默认为 Script

          ¥cursive string (optional) - Defaults to Script.

        • fantasy 字符串(可选) - 默认为 Impact

          ¥fantasy string (optional) - Defaults to Impact.

        • math 字符串(可选) - 默认为 Latin Modern Math

          ¥math string (optional) - Defaults to Latin Modern Math.

      • defaultFontSize 整数(可选) - 默认为 16

        ¥defaultFontSize Integer (optional) - Defaults to 16.

      • defaultMonospaceFontSize 整数(可选) - 默认为 13

        ¥defaultMonospaceFontSize Integer (optional) - Defaults to 13.

      • minimumFontSize 整数(可选) - 默认为 0

        ¥minimumFontSize Integer (optional) - Defaults to 0.

      • defaultEncoding 字符串(可选) - 默认为 ISO-8859-1

        ¥defaultEncoding string (optional) - Defaults to ISO-8859-1.

      • backgroundThrottling 布尔值(可选) - 当页面变为背景时是否限制动画和计时器。这也影响了 页面可见性 API。当单个 browserWindow 中显示的至少一个 webContents 禁用了 backgroundThrottling 时,将绘制框架并交换整个窗口及其显示的其他 webContents。默认为 true

        ¥backgroundThrottling boolean (optional) - Whether to throttle animations and timers when the page becomes background. This also affects the Page Visibility API. When at least one webContents displayed in a single browserWindow has disabled backgroundThrottling then frames will be drawn and swapped for the whole window and other webContents displayed by it. Defaults to true.

      • offscreen 布尔值(可选) - 是否为浏览器窗口启用离屏渲染。默认为 false。有关详细信息,请参阅 离屏渲染教程

        ¥offscreen boolean (optional) - Whether to enable offscreen rendering for the browser window. Defaults to false. See the offscreen rendering tutorial for more details.

      • contextIsolation 布尔值(可选) - 是否在单独的 JavaScript 上下文中运行 Electron API 和指定的 preload 脚本。默认为 truepreload 脚本运行的上下文只能访问其自己专用的 documentwindow 全局变量,以及其自己的一组 JavaScript 内置函数(ArrayObjectJSON 等),这些对加载的内容都是不可见的。Electron API 仅在 preload 脚本中可用,在加载的页面中不可用。加载潜在不受信任的远程内容时应使用此选项,以确保加载的内容不会篡改 preload 脚本和正在使用的任何 Electron API。此选项使用与 Chrome 内容脚本 使用的技术相同的技术。你可以通过在控制台选项卡顶部的组合框中选择 'Electron 隔离上下文' 条目来在开发工具中访问此上下文。

        ¥contextIsolation boolean (optional) - Whether to run Electron APIs and the specified preload script in a separate JavaScript context. Defaults to true. The context that the preload script runs in will only have access to its own dedicated document and window globals, as well as its own set of JavaScript builtins (Array, Object, JSON, etc.), which are all invisible to the loaded content. The Electron API will only be available in the preload script and not the loaded page. This option should be used when loading potentially untrusted remote content to ensure the loaded content cannot tamper with the preload script and any Electron APIs being used. This option uses the same technique used by Chrome Content Scripts. You can access this context in the dev tools by selecting the 'Electron Isolated Context' entry in the combo box at the top of the Console tab.

      • webviewTag 布尔值(可选) - 是否启用 <webview> 标签。默认为 false。注意:为 <webview> 配置的 preload 脚本在执行时将启用节点集成,因此你应确保远程/不受信任的内容无法使用可能是恶意的 preload 脚本创建 <webview> 标记。你可以使用 webContents 上的 will-attach-webview 事件来删除 preload 脚本并验证或更改 <webview> 的初始设置。

        ¥webviewTag boolean (optional) - Whether to enable the <webview> tag. Defaults to false. Note: The preload script configured for the <webview> will have node integration enabled when it is executed so you should ensure remote/untrusted content is not able to create a <webview> tag with a possibly malicious preload script. You can use the will-attach-webview event on webContents to strip away the preload script and to validate or alter the <webview>'s initial settings.

      • additionalArguments 字符串[](可选) - 将在此应用的渲染器进程中附加到 process.argv 的字符串列表。对于将少量数据传递到渲染器进程预加载脚本非常有用。

        ¥additionalArguments string[] (optional) - A list of strings that will be appended to process.argv in the renderer process of this app. Useful for passing small bits of data down to renderer process preload scripts.

      • safeDialogs 布尔值(可选) - 是否启用浏览器风格的连续对话框保护。默认为 false

        ¥safeDialogs boolean (optional) - Whether to enable browser style consecutive dialog protection. Default is false.

      • safeDialogsMessage 字符串(可选) - 触发连续对话保护时显示的消息。如果未定义,将使用默认消息,请注意,当前默认消息是英文且未本地化。

        ¥safeDialogsMessage string (optional) - The message to display when consecutive dialog protection is triggered. If not defined the default message would be used, note that currently the default message is in English and not localized.

      • disableDialogs 布尔值(可选) - 是否完全禁用对话框。覆盖 safeDialogs。默认为 false

        ¥disableDialogs boolean (optional) - Whether to disable dialogs completely. Overrides safeDialogs. Default is false.

      • navigateOnDragDrop 布尔值(可选) - 将文件或链接拖放到页面上是否会导致导航。默认为 false

        ¥navigateOnDragDrop boolean (optional) - Whether dragging and dropping a file or link onto the page causes a navigation. Default is false.

      • autoplayPolicy 字符串(可选) - 应用于窗口中内容的自动播放策略,可以是 no-user-gesture-requireduser-gesture-requireddocument-user-activation-required。默认为 no-user-gesture-required

        ¥autoplayPolicy string (optional) - Autoplay policy to apply to content in the window, can be no-user-gesture-required, user-gesture-required, document-user-activation-required. Defaults to no-user-gesture-required.

      • disableHtmlFullscreenWindowResize 布尔值(可选) - 进入 HTML 全屏时是否阻止窗口调整大小。默认为 false

        ¥disableHtmlFullscreenWindowResize boolean (optional) - Whether to prevent the window from resizing when entering HTML Fullscreen. Default is false.

      • accessibleTitle 字符串(可选) - 仅向屏幕阅读器等辅助工具提供的替代标题字符串。用户不能直接看到该字符串。

        ¥accessibleTitle string (optional) - An alternative title string provided only to accessibility tools such as screen readers. This string is not directly visible to users.

      • spellcheck 布尔值(可选) - 是否启用内置拼写检查器。默认为 true

        ¥spellcheck boolean (optional) - Whether to enable the builtin spellchecker. Default is true.

      • enableWebSQL 布尔值(可选) - 是否启用 WebSQL API。默认为 true

        ¥enableWebSQL boolean (optional) - Whether to enable the WebSQL api. Default is true.

      • v8CacheOptions 字符串(可选) - 强制执行 Blink 使用的 v8 代码缓存策略。接受的值为

        ¥v8CacheOptions string (optional) - Enforces the v8 code caching policy used by blink. Accepted values are

        • none - 禁用代码缓存

          ¥none - Disables code caching

        • code - 基于启发式的代码缓存

          ¥code - Heuristic based code caching

        • bypassHeatCheck - 绕过代码缓存启发式但使用惰性编译

          ¥bypassHeatCheck - Bypass code caching heuristics but with lazy compilation

        • bypassHeatCheckAndEagerCompile - 与上面相同,只是编译是预先的。默认策略是 code

          ¥bypassHeatCheckAndEagerCompile - Same as above except compilation is eager. Default policy is code.

      • enablePreferredSizeMode 布尔值(可选) - 是否启用首选尺寸模式。首选尺寸是包含文档布局所需的最小尺寸(无需滚动)。启用此选项将导致当首选大小更改时在 WebContents 上发出 preferred-size-changed 事件。默认为 false

        ¥enablePreferredSizeMode boolean (optional) - Whether to enable preferred size mode. The preferred size is the minimum size needed to contain the layout of the document—without requiring scrolling. Enabling this will cause the preferred-size-changed event to be emitted on the WebContents when the preferred size changes. Default is false.

      • transparent 布尔值(可选) - 是否开启访客页面背景透明。默认为 true。注意:访客页面的文本和背景颜色源自其根元素的 配色方案。启用透明度后,文本颜色仍会相应变化,但背景将保持透明。

        ¥transparent boolean (optional) - Whether to enable background transparency for the guest page. Default is true. Note: The guest page's text and background colors are derived from the color scheme of its root element. When transparency is enabled, the text color will still change accordingly but the background will remain transparent.

    • paintWhenInitiallyHidden 布尔值(可选) - 当 showfalse 并且刚刚创建时,渲染器是否应该处于活动状态。为了使 document.visibilityState 在第一次加载 show: false 时能够正常工作,你应该将其设置为 false。将其设置为 false 将导致 ready-to-show 事件不触发。默认为 true

      ¥paintWhenInitiallyHidden boolean (optional) - Whether the renderer should be active when show is false and it has just been created. In order for document.visibilityState to work correctly on first load with show: false you should set this to false. Setting this to false will cause the ready-to-show event to not fire. Default is true.

实例事件

¥Instance Events

使用 new BrowserWindow 创建的对象会发出以下事件:

¥Objects created with new BrowserWindow emit the following events:

注意:某些事件仅在特定操作系统上可用并如此标记。

¥Note: Some events are only available on specific operating systems and are labeled as such.

事件:'page-title-updated'

¥Event: 'page-title-updated'

返回:

¥Returns:

  • event 事件

    ¥event Event

  • title 字符串

    ¥title string

  • explicitSet 布尔值

    ¥explicitSet boolean

当文档更改其标题时发出,调用 event.preventDefault() 将阻止原生窗口的标题更改。当标题是从文件 URL 合成时,explicitSet 为 false。

¥Emitted when the document changed its title, calling event.preventDefault() will prevent the native window's title from changing. explicitSet is false when title is synthesized from file URL.

事件:'close'

¥Event: 'close'

返回:

¥Returns:

  • event 事件

    ¥event Event

当窗口将要关闭时发出。它在 DOM 的 beforeunloadunload 事件之前发出。调用 event.preventDefault() 将取消关闭。

¥Emitted when the window is going to be closed. It's emitted before the beforeunload and unload event of the DOM. Calling event.preventDefault() will cancel the close.

通常你会希望使用 beforeunload 处理程序来决定是否应关闭窗口,重新加载窗口时也会调用该处理程序。在 Electron 中,返回 undefined 以外的任何值都会取消关闭。例如:

¥Usually you would want to use the beforeunload handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than undefined would cancel the close. For example:

window.onbeforeunload = (e) => {
console.log('I do not want to be closed')

// Unlike usual browsers that a message box will be prompted to users, returning
// a non-void value will silently cancel the close.
// It is recommended to use the dialog API to let the user confirm closing the
// application.
e.returnValue = false
}

注意:window.onbeforeunload = handlerwindow.addEventListener('beforeunload', handler) 的行为之间存在细微差别。建议始终显式设置 event.returnValue,而不是仅返回一个值,因为前者在 Electron 中工作得更加一致。

¥Note: There is a subtle difference between the behaviors of window.onbeforeunload = handler and window.addEventListener('beforeunload', handler). It is recommended to always set the event.returnValue explicitly, instead of only returning a value, as the former works more consistently within Electron.

事件:'closed'

¥Event: 'closed'

当窗口关闭时发出。收到此事件后,你应该删除对该窗口的引用并避免再使用它。

¥Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more.

事件:'session-end' Windows

¥Event: 'session-end' Windows

当窗口会话由于强制关闭或计算机重新启动或会话注销而即将结束时发出。

¥Emitted when window session is going to end due to force shutdown or machine restart or session log off.

事件:'unresponsive'

¥Event: 'unresponsive'

当网页变得无响应时发出。

¥Emitted when the web page becomes unresponsive.

事件:'responsive'

¥Event: 'responsive'

当无响应的网页再次响应时发出。

¥Emitted when the unresponsive web page becomes responsive again.

事件:'blur'

¥Event: 'blur'

当窗口失去焦点时发出。

¥Emitted when the window loses focus.

事件:'focus'

¥Event: 'focus'

当窗口获得焦点时发出。

¥Emitted when the window gains focus.

事件:'show'

¥Event: 'show'

显示窗口时发出。

¥Emitted when the window is shown.

事件:'hide'

¥Event: 'hide'

当窗口隐藏时发出。

¥Emitted when the window is hidden.

事件:'ready-to-show'

¥Event: 'ready-to-show'

当网页已渲染(但未显示)并且窗口可以在没有视觉闪烁的情况下显示时发出。

¥Emitted when the web page has been rendered (while not being shown) and window can be displayed without a visual flash.

请注意,使用此事件意味着渲染器将被视为 "visible" 并进行绘制,即使 show 为 false。如果你使用 paintWhenInitiallyHidden: false,此事件将永远不会触发

¥Please note that using this event implies that the renderer will be considered "visible" and paint even though show is false. This event will never fire if you use paintWhenInitiallyHidden: false

事件:'maximize'

¥Event: 'maximize'

当窗口最大化时发出。

¥Emitted when window is maximized.

事件:'unmaximize'

¥Event: 'unmaximize'

当窗口从最大化状态退出时发出。

¥Emitted when the window exits from a maximized state.

事件:'minimize'

¥Event: 'minimize'

当窗口最小化时发出。

¥Emitted when the window is minimized.

事件:'restore'

¥Event: 'restore'

当窗口从最小化状态恢复时发出。

¥Emitted when the window is restored from a minimized state.

事件:'will-resize' macOS Windows

¥Event: 'will-resize' macOS Windows

返回:

¥Returns:

  • event 事件

    ¥event Event

  • newBounds 长方形 - 正在调整窗口大小。

    ¥newBounds Rectangle - Size the window is being resized to.

  • details 对象

    ¥details Object

    • edge(string) - 拖动窗口的边缘来调整大小。可以是 bottomleftrighttop-lefttop-rightbottom-leftbottom-right

      ¥edge (string) - The edge of the window being dragged for resizing. Can be bottom, left, right, top-left, top-right, bottom-left or bottom-right.

在调整窗口大小之前发出。调用 event.preventDefault() 将阻止调整窗口大小。

¥Emitted before the window is resized. Calling event.preventDefault() will prevent the window from being resized.

请注意,只有在手动调整窗口大小时才会发出此消息。使用 setBounds/setSize 调整窗口大小不会发出此事件。

¥Note that this is only emitted when the window is being resized manually. Resizing the window with setBounds/setSize will not emit this event.

edge 选项的可能值和行为取决于平台。可能的值为:

¥The possible values and behaviors of the edge option are platform dependent. Possible values are:

  • 在 Windows 上,可能的值为 bottomtopleftrighttop-lefttop-rightbottom-leftbottom-right

    ¥On Windows, possible values are bottom, top, left, right, top-left, top-right, bottom-left, bottom-right.

  • 在 macOS 上,可能的值为 bottomright

    ¥On macOS, possible values are bottom and right.

    • bottom 用于表示垂直调整大小。

      ¥The value bottom is used to denote vertical resizing.

    • right 用于表示水平调整大小。

      ¥The value right is used to denote horizontal resizing.

事件:'resize'

¥Event: 'resize'

调整窗口大小后发出。

¥Emitted after the window has been resized.

事件:'resized' macOS Windows

¥Event: 'resized' macOS Windows

当窗口完成调整大小时发出一次。

¥Emitted once when the window has finished being resized.

这通常在手动调整窗口大小时发出。在 macOS 上,使用 setBounds/setSize 调整窗口大小并将 animate 参数设置为 true 也会在调整大小完成后发出此事件。

¥This is usually emitted when the window has been resized manually. On macOS, resizing the window with setBounds/setSize and setting the animate parameter to true will also emit this event once resizing has finished.

事件:'will-move' macOS Windows

¥Event: 'will-move' macOS Windows

返回:

¥Returns:

  • event 事件

    ¥event Event

  • newBounds 长方形 - 窗口移动到的位置。

    ¥newBounds Rectangle - Location the window is being moved to.

在移动窗口之前发出。在 Windows 上,调用 event.preventDefault() 将阻止窗口移动。

¥Emitted before the window is moved. On Windows, calling event.preventDefault() will prevent the window from being moved.

请注意,只有在手动移动窗口时才会发出此信号。使用 setPosition/setBounds/center 移动窗口不会发出此事件。

¥Note that this is only emitted when the window is being moved manually. Moving the window with setPosition/setBounds/center will not emit this event.

事件:'move'

¥Event: 'move'

当窗口移动到新位置时发出。

¥Emitted when the window is being moved to a new position.

事件:'moved' macOS Windows

¥Event: 'moved' macOS Windows

当窗口移动到新位置时发出一次。

¥Emitted once when the window is moved to a new position.

注意:在 macOS 上,此事件是 move 的别名。

¥Note: On macOS this event is an alias of move.

事件:'enter-full-screen'

¥Event: 'enter-full-screen'

当窗口进入全屏状态时发出。

¥Emitted when the window enters a full-screen state.

事件:'leave-full-screen'

¥Event: 'leave-full-screen'

当窗口离开全屏状态时发出。

¥Emitted when the window leaves a full-screen state.

事件:'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.

事件:'always-on-top-changed'

¥Event: 'always-on-top-changed'

返回:

¥Returns:

  • event 事件

    ¥event Event

  • isAlwaysOnTop 布尔值

    ¥isAlwaysOnTop boolean

当窗口被设置或取消设置为始终显示在其他窗口之上时发出。

¥Emitted when the window is set or unset to show always on top of other windows.

事件:'app-command' Windows Linux

¥Event: 'app-command' Windows Linux

返回:

¥Returns:

  • event 事件

    ¥event Event

  • command 字符串

    ¥command string

当调用 应用命令 时发出。这些通常与键盘媒体键或浏览器命令以及 Windows 上某些鼠标中内置的 "后退" 按钮相关。

¥Emitted when an App Command is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows.

命令变为小写,下划线替换为连字符,并且去掉 APPCOMMAND_ 前缀。例如 APPCOMMAND_BROWSER_BACKWARD 作为 browser-backward 发出。

¥Commands are lowercased, underscores are replaced with hyphens, and the APPCOMMAND_ prefix is stripped off. e.g. APPCOMMAND_BROWSER_BACKWARD is emitted as browser-backward.

const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.on('app-command', (e, cmd) => {
// Navigate the window back when the user hits their mouse back button
if (cmd === 'browser-backward' && win.webContents.canGoBack()) {
win.webContents.goBack()
}
})

Linux 上明确支持以下应用命令:

¥The following app commands are explicitly supported on Linux:

  • browser-backward

  • browser-forward

事件:'swipe' macOS

¥Event: 'swipe' macOS

返回:

¥Returns:

  • event 事件

    ¥event Event

  • direction 字符串

    ¥direction string

三指滑动时发出。可能的方向是 uprightdownleft

¥Emitted on 3-finger swipe. Possible directions are up, right, down, left.

此事件背后的方法是为了处理旧版 macOS 风格的触控板滑动而构建的,其中屏幕上的内容不会随着滑动而移动。大多数 macOS 触控板不再配置为允许这种滑动,因此为了使其正确发出,System Preferences > Trackpad > More Gestures 中的 '在页面之间滑动' 首选项必须设置为 '用两根或三根手指滑动'。

¥The method underlying this event is built to handle older macOS-style trackpad swiping, where the content on the screen doesn't move with the swipe. Most macOS trackpads are not configured to allow this kind of swiping anymore, so in order for it to emit properly the 'Swipe between pages' preference in System Preferences > Trackpad > More Gestures must be set to 'Swipe with two or three fingers'.

事件:'rotate-gesture' macOS

¥Event: 'rotate-gesture' macOS

返回:

¥Returns:

  • event 事件

    ¥event Event

  • rotation 漂浮

    ¥rotation Float

在触控板旋转手势上发出。持续发出直到旋转手势结束。每次触发的 rotation 值是自上次触发以来旋转的角度(以度为单位)。旋转手势时最后发出的事件的值始终为 0。逆时针旋转值为正,顺时针旋转值为负。

¥Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is ended. The rotation value on each emission is the angle in degrees rotated since the last emission. The last emitted event upon a rotation gesture will always be of value 0. Counter-clockwise rotation values are positive, while clockwise ones are negative.

事件:'sheet-begin' macOS

¥Event: 'sheet-begin' macOS

当窗口打开一张工作表时发出。

¥Emitted when the window opens a sheet.

事件:'sheet-end' macOS

¥Event: 'sheet-end' macOS

当窗口关闭工作表时发出。

¥Emitted when the window has closed a sheet.

事件:'new-window-for-tab' macOS

¥Event: 'new-window-for-tab' macOS

单击原生新选项卡按钮时发出。

¥Emitted when the native new tab button is clicked.

事件:'system-context-menu' Windows

¥Event: 'system-context-menu' Windows

返回:

¥Returns:

  • event 事件

    ¥event Event

  • point 观点 - 触发上下文菜单的屏幕坐标

    ¥point Point - The screen coordinates the context menu was triggered at

当在窗口上触发系统上下文菜单时发出,通常仅当用户右键单击窗口的非客户区域时才会触发。这是窗口标题栏或你在无框窗口中声明为 -webkit-app-region: drag 的任何区域。

¥Emitted when the system context menu is triggered on the window, this is normally only triggered when the user right clicks on the non-client area of your window. This is the window titlebar or any area you have declared as -webkit-app-region: drag in a frameless window.

调用 event.preventDefault() 将阻止显示菜单。

¥Calling event.preventDefault() will prevent the menu from being displayed.

静态方法

¥Static Methods

BrowserWindow 类具有以下静态方法:

¥The BrowserWindow class has the following static methods:

BrowserWindow.getAllWindows()

返回 BrowserWindow[] - 所有打开的浏览器窗口的数组。

¥Returns BrowserWindow[] - An array of all opened browser windows.

BrowserWindow.getFocusedWindow()

返回 BrowserWindow | null - 该应用中聚焦的窗口,否则返回 null

¥Returns BrowserWindow | null - The window that is focused in this application, otherwise returns null.

BrowserWindow.fromWebContents(webContents)

返回 BrowserWindow | null - 如果内容不属于某个窗口,则拥有给定 webContentsnull 的窗口。

¥Returns BrowserWindow | null - The window that owns the given webContents or null if the contents are not owned by a window.

BrowserWindow.fromBrowserView(browserView) 已弃用

¥BrowserWindow.fromBrowserView(browserView) Deprecated

注意 BrowserView 类已弃用,并由新的 WebContentsView 类取代。

¥The BrowserView class is deprecated, and replaced by the new WebContentsView class.

返回 BrowserWindow | null - 拥有给定 browserView 的窗口。如果给定视图未附加到任何窗口,则返回 null

¥Returns BrowserWindow | null - The window that owns the given browserView. If the given view is not attached to any window, returns null.

BrowserWindow.fromId(id)

  • id 整数

    ¥id Integer

返回 BrowserWindow | null - 具有给定 id 的窗口。

¥Returns BrowserWindow | null - The window with the given id.

实例属性

¥Instance Properties

使用 new BrowserWindow 创建的对象具有以下属性:

¥Objects created with new BrowserWindow have the following properties:

const { BrowserWindow } = require('electron')
// In this example `win` is our instance
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com')

win.webContents 只读

¥win.webContents Readonly

该窗口拥有的 WebContents 对象。所有与网页相关的事件和操作都将通过它完成。

¥A WebContents object this window owns. All web page related events and operations will be done via it.

请参阅 webContents 文档 了解其方法和事件。

¥See the webContents documentation for its methods and events.

win.id 只读

¥win.id Readonly

代表窗口的唯一 ID 的 Integer 属性。每个 ID 在整个 Electron 应用的所有 BrowserWindow 实例中都是唯一的。

¥A Integer property representing the unique ID of the window. Each ID is unique among all BrowserWindow instances of the entire Electron application.

win.tabbingIdentifier macOS 只读

¥win.tabbingIdentifier macOS Readonly

string(可选)属性,等于传递给 BrowserWindow 构造函数的 tabbingIdentifierundefined(如果未设置)。

¥A string (optional) property that is equal to the tabbingIdentifier passed to the BrowserWindow constructor or undefined if none was set.

win.autoHideMenuBar

一个 boolean 属性,用于确定窗口菜单栏是否应自动隐藏。设置后,只有当用户按单个 Alt 键时才会显示菜单栏。

¥A boolean property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single Alt key.

如果菜单栏已经可见,将此属性设置为 true 不会立即隐藏它。

¥If the menu bar is already visible, setting this property to true won't hide it immediately.

win.simpleFullScreen

一个 boolean 属性,用于确定窗口是否处于简单(Lion 之前)全屏模式。

¥A boolean property that determines whether the window is in simple (pre-Lion) fullscreen mode.

win.fullScreen

确定窗口是否处于全屏模式的 boolean 属性。

¥A boolean property that determines whether the window is in fullscreen mode.

win.focusable Windows macOS

确定窗口是否可聚焦的 boolean 属性。

¥A boolean property that determines whether the window is focusable.

win.visibleOnAllWorkspaces macOS Linux

boolean 属性确定窗口是否在所有工作区上可见。

¥A boolean property that determines whether the window is visible on all workspaces.

注意:在 Windows 上始终返回 false。

¥Note: Always returns false on Windows.

win.shadow

确定窗口是否有阴影的 boolean 属性。

¥A boolean property that determines whether the window has a shadow.

win.menuBarVisible Windows Linux

确定菜单栏是否可见的 boolean 属性。

¥A boolean property that determines whether the menu bar should be visible.

注意:如果菜单栏自动隐藏,用户仍然可以通过按单个 Alt 键调出菜单栏。

¥Note: If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single Alt key.

win.kiosk

确定窗口是否处于 kiosk 模式的 boolean 属性。

¥A boolean property that determines whether the window is in kiosk mode.

win.documentEdited macOS

一个 boolean 属性,指定窗口的文档是否已被编辑。

¥A boolean property that specifies whether the window’s document has been edited.

当设置为 true 时,标题栏中的图标将变为灰色。

¥The icon in title bar will become gray when set to true.

win.representedFilename macOS

string 属性确定窗口所代表的文件的路径名,并且文件的图标将显示在窗口的标题栏中。

¥A string property that determines the pathname of the file the window represents, and the icon of the file will show in window's title bar.

win.title

确定原生窗口标题的 string 属性。

¥A string property that determines the title of the native window.

注意:网页的标题可以与原生窗口的标题不同。

¥Note: The title of the web page can be different from the title of the native window.

win.minimizable macOS Windows

boolean 属性确定用户是否可以手动最小化窗口。

¥A boolean property that determines whether the window can be manually minimized by user.

在 Linux 上,虽然 getter 返回 true,但 setter 是无操作的。

¥On Linux the setter is a no-op, although the getter returns true.

win.maximizable macOS Windows

一个 boolean 属性,用于确定用户是否可以手动最大化窗口。

¥A boolean property that determines whether the window can be manually maximized by user.

在 Linux 上,虽然 getter 返回 true,但 setter 是无操作的。

¥On Linux the setter is a no-op, although the getter returns true.

win.fullScreenable

boolean 属性,用于确定最大化/缩放窗口按钮是否切换全屏模式或最大化窗口。

¥A boolean property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.

win.resizable

boolean 属性确定用户是否可以手动调整窗口大小。

¥A boolean property that determines whether the window can be manually resized by user.

win.closable macOS Windows

boolean 属性,确定用户是否可以手动关闭窗口。

¥A boolean property that determines whether the window can be manually closed by user.

在 Linux 上,虽然 getter 返回 true,但 setter 是无操作的。

¥On Linux the setter is a no-op, although the getter returns true.

win.movable macOS Windows

boolean 属性确定用户是否可以移动窗口。

¥A boolean property that determines Whether the window can be moved by user.

在 Linux 上,虽然 getter 返回 true,但 setter 是无操作的。

¥On Linux the setter is a no-op, although the getter returns true.

win.excludedFromShownWindowsMenu macOS

boolean 属性,用于确定窗口是否从应用的 Windows 菜单中排除。默认为 false

¥A boolean property that determines whether the window is excluded from the application’s Windows menu. false by default.

const win = new BrowserWindow({ height: 600, width: 600 })

const template = [
{
role: 'windowmenu'
}
]

win.excludedFromShownWindowsMenu = true

const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)

win.accessibleTitle

string 属性,定义仅提供给屏幕阅读器等辅助工具的替代标题。用户不能直接看到该字符串。

¥A string property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users.

实例方法

¥Instance Methods

使用 new BrowserWindow 创建的对象具有以下实例方法:

¥Objects created with new BrowserWindow have the following instance methods:

注意:有些方法仅在特定操作系统上可用,并如此标记。

¥Note: Some methods are only available on specific operating systems and are labeled as such.

win.destroy()

强制关闭窗口,网页不会发出 unloadbeforeunload 事件,该窗口也不会发出 close 事件,但保证会发出 closed 事件。

¥Force closing the window, the unload and beforeunload event won't be emitted for the web page, and close event will also not be emitted for this window, but it guarantees the closed event will be emitted.

win.close()

尝试关闭窗口。这与用户手动单击窗口的关闭按钮具有相同的效果。但网页可能会取消关闭。参见 关闭事件

¥Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the close event.

win.focus()

焦点集中在窗户上。

¥Focuses on the window.

win.blur()

从窗口中移除焦点。

¥Removes focus from the window.

win.isFocused()

返回 boolean - 窗口是否获得焦点。

¥Returns boolean - Whether the window is focused.

win.isDestroyed()

返回 boolean - 窗户是否被破坏。

¥Returns boolean - Whether the window is destroyed.

win.show()

显示窗口并给予窗口焦点。

¥Shows and gives focus to the window.

win.showInactive()

显示窗口但不关注它。

¥Shows the window but doesn't focus on it.

win.hide()

隐藏窗户。

¥Hides the window.

win.isVisible()

返回 boolean - 用户在应用的前台是否可以看到该窗口。

¥Returns boolean - Whether the window is visible to the user in the foreground of the app.

win.isModal()

返回 boolean - 当前窗口是否为模态窗口。

¥Returns boolean - Whether current window is a modal window.

win.maximize()

最大化窗口。如果窗口尚未显示,这也将显示(但不聚焦)窗口。

¥Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already.

win.unmaximize()

取消最大化窗口。

¥Unmaximizes the window.

win.isMaximized()

返回 boolean - 窗口是否最大化。

¥Returns boolean - Whether the window is maximized.

win.minimize()

最小化窗口。在某些平台上,最小化的窗口将显示在 Dock 中。

¥Minimizes the window. On some platforms the minimized window will be shown in the Dock.

win.restore()

将窗口从最小化状态恢复到之前的状态。

¥Restores the window from minimized state to its previous state.

win.isMinimized()

返回 boolean - 窗口是否最小化。

¥Returns boolean - Whether the window is minimized.

win.setFullScreen(flag)

  • flag 布尔值

    ¥flag boolean

设置窗口是否应处于全屏模式。

¥Sets whether the window should be in fullscreen mode.

注意:在 macOS 上,全屏转换是异步发生的。如果进一步的操作取决于全屏状态,请使用 'enter-full-screen''leave-full-screen' 事件。

¥Note: On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the 'enter-full-screen' or 'leave-full-screen' events.

win.isFullScreen()

返回 boolean - 窗口是否处于全屏模式。

¥Returns boolean - Whether the window is in fullscreen mode.

注意:在 macOS 上,全屏转换是异步发生的。查询 BrowserWindow 的全屏状态时,应确保已发出 'enter-full-screen''leave-full-screen' 事件。

¥Note: On macOS, fullscreen transitions take place asynchronously. When querying for a BrowserWindow's fullscreen status, you should ensure that either the 'enter-full-screen' or 'leave-full-screen' events have been emitted.

win.setSimpleFullScreen(flag) macOS

  • flag 布尔值

    ¥flag boolean

进入或离开简单全屏模式。

¥Enters or leaves simple fullscreen mode.

简单全屏模式模拟 Lion (10.7) 之前的 macOS 版本中的原生全屏行为。

¥Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7).

win.isSimpleFullScreen() macOS

返回 boolean - 窗口是否处于简单(Lion 之前)全屏模式。

¥Returns boolean - Whether the window is in simple (pre-Lion) fullscreen mode.

win.isNormal()

返回 boolean - 窗口是否处于正常状态(未最大化、未最小化、未全屏模式)。

¥Returns boolean - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode).

win.setAspectRatio(aspectRatio[, extraSize])

  • aspectRatio 漂浮 - 内容视图某些部分保持的宽高比。

    ¥aspectRatio Float - The aspect ratio to maintain for some portion of the content view.

  • extraSize 尺寸(可选)macOS - 在保持纵横比的同时不包括额外的尺寸。

    ¥extraSize Size (optional) macOS - The extra size not to be included while maintaining the aspect ratio.

这将使窗口保持纵横比。额外的尺寸允许开发者拥有以像素指定的空间,不包括在长宽比计算中。该 API 已经考虑了窗口大小与其内容大小之间的差异。

¥This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size.

考虑一个带有高清视频播放器和相关控件的普通窗口。也许左边缘有 15 个像素的控件,右边缘有 25 个像素的控件,播放器下方有 50 个像素的控件。为了在播放器本身内保持 16:9 的宽高比(HD @1920x1080 的标准宽高比),我们将使用 16/9 和 { 宽度参数调用此函数:40, height:50 }.第二个参数并不关心额外的宽度和高度在内容视图中的位置 - 只关心它们存在。对整个内容视图中的所有额外宽度和高度区域进行求和。

¥Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and { width: 40, height: 50 }. The second argument doesn't care where the extra width and height are within the content view--only that they exist. Sum any extra width and height areas you have within the overall content view.

当使用 win.setSize 等 API 以编程方式调整窗口大小时,不会考虑宽高比。

¥The aspect ratio is not respected when window is resized programmatically with APIs like win.setSize.

要重置宽高比,请传递 0 作为 aspectRatio 值:win.setAspectRatio(0)

¥To reset an aspect ratio, pass 0 as the aspectRatio value: win.setAspectRatio(0).

win.setBackgroundColor(backgroundColor)

  • backgroundColor 字符串 - 颜色采用 Hex、RGB、RGBA、HSL、HSLA 或命名的 CSS 颜色格式。对于十六进制类型,Alpha 通道是可选的。

    ¥backgroundColor string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type.

有效 backgroundColor 值的示例:

¥Examples of valid backgroundColor values:

  • 十六进制

    ¥Hex

    • #fff (shorthand RGB)

    • #ffff (shorthand ARGB)

    • #ffffff (RGB)

    • #ffffffff (ARGB)

  • RGB

    • rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)

      • 例如 RGB(255, 255, 255)

        ¥e.g. rgb(255, 255, 255)

  • RGBA

    • rgba\(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)\)

      • 例如 RGBA(255, 255, 255, 1.0)

        ¥e.g. rgba(255, 255, 255, 1.0)

  • HSL

    • hsl\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)

      • 例如 HSL(200, 20%, 50%)

        ¥e.g. hsl(200, 20%, 50%)

  • HSLA

    • hsla\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)

      • 例如 高斯拉(200, 20%, 50%, 0.5)

        ¥e.g. hsla(200, 20%, 50%, 0.5)

  • 颜色名称

    ¥Color name

    • 选项列于 SkParseColor.cpp

      ¥Options are listed in SkParseColor.cpp

    • 与 CSS Color Module Level 3 关键字类似,但区分大小写。

      ¥Similar to CSS Color Module Level 3 keywords, but case-sensitive.

      • 例如 bluevioletred

        ¥e.g. blueviolet or red

设置窗口的背景颜色。参见 设置 backgroundColor

¥Sets the background color of the window. See Setting backgroundColor.

win.previewFile(path[, displayName]) macOS

  • path 字符串 - 要使用 QuickLook 预览的文件的绝对路径。这很重要,因为“快速查看”使用路径上的文件名和文件扩展名来确定要打开的文件的内容类型。

    ¥path string - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open.

  • displayName 字符串(可选) - 要在“快速查看”模式视图上显示的文件的名称。这纯粹是视觉上的,不会影响文件的内容类型。默认为 path

    ¥displayName string (optional) - The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to path.

使用 快速查看 预览给定路径中的文件。

¥Uses Quick Look to preview a file at a given path.

win.closeFilePreview() macOS

关闭当前打开的 快速查看 面板。

¥Closes the currently open Quick Look panel.

win.setBounds(bounds[, animate])

  • bounds 部分<长方形>

    ¥bounds Partial<Rectangle>

  • animate 布尔值(可选)macOS

    ¥animate boolean (optional) macOS

调整窗口大小并将窗口移动到提供的边界。任何未提供的属性将默认为其当前值。

¥Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values.

const { BrowserWindow } = require('electron')
const win = new BrowserWindow()

// set all bounds properties
win.setBounds({ x: 440, y: 225, width: 800, height: 600 })

// set a single bounds property
win.setBounds({ width: 100 })

// { x: 440, y: 225, width: 100, height: 600 }
console.log(win.getBounds())

注意:在 macOS 上,y 坐标值不能小于 Tray 高度。托盘高度随着时间的推移而变化,并且取决于操作系统,但在 20-40px 之间。传递低于托盘高度的值将导致窗口与托盘齐平。

¥Note: On macOS, the y-coordinate value cannot be smaller than the Tray height. The tray height has changed over time and depends on the operating system, but is between 20-40px. Passing a value lower than the tray height will result in a window that is flush to the tray.

win.getBounds()

返回 Rectangle - 窗口的 boundsObject

¥Returns Rectangle - The bounds of the window as Object.

注意:在 macOS 上,返回的 y 坐标值至少为 Tray 高度。例如,调用托盘高度为 38 的 win.setBounds({ x: 25, y: 20, width: 800, height: 600 }) 意味着 win.getBounds() 将返回 { x: 25, y: 38, width: 800, height: 600 }

¥Note: On macOS, the y-coordinate value returned will be at minimum the Tray height. For example, calling win.setBounds({ x: 25, y: 20, width: 800, height: 600 }) with a tray height of 38 means that win.getBounds() will return { x: 25, y: 38, width: 800, height: 600 }.

win.getBackgroundColor()

返回 string - 获取十六进制 (#RRGGBB) 格式的窗口背景颜色。

¥Returns string - Gets the background color of the window in Hex (#RRGGBB) format.

参见 设置 backgroundColor

¥See Setting backgroundColor.

注意:Alpha 值不会与红色、绿色和蓝色值一起返回。

¥Note: The alpha value is not returned alongside the red, green, and blue values.

win.setContentBounds(bounds[, animate])

  • bounds 长方形

    ¥bounds Rectangle

  • animate 布尔值(可选)macOS

    ¥animate boolean (optional) macOS

调整窗口的客户区域(例如网页)的大小并将其移动到提供的边界。

¥Resizes and moves the window's client area (e.g. the web page) to the supplied bounds.

win.getContentBounds()

返回 Rectangle - 窗口的客户区的 boundsObject

¥Returns Rectangle - The bounds of the window's client area as Object.

win.getNormalBounds()

返回 Rectangle - 包含正常状态的窗口边界

¥Returns Rectangle - Contains the window bounds of the normal state

注意:无论窗口的当前状态如何:最大化、最小化或全屏,此函数始终返回正常状态下窗口的位置和大小。在正常状态下,getBounds 和 getNormalBounds 返回相同的 Rectangle

¥Note: whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same Rectangle.

win.setEnabled(enable)

  • enable 布尔值

    ¥enable boolean

禁用或启用该窗口。

¥Disable or enable the window.

win.isEnabled()

返回 boolean - 窗口是否启用。

¥Returns boolean - whether the window is enabled.

win.setSize(width, height[, animate])

  • width 整数

    ¥width Integer

  • height 整数

    ¥height Integer

  • animate 布尔值(可选)macOS

    ¥animate boolean (optional) macOS

将窗口大小调整为 widthheight。如果 widthheight 低于任何设置的最小尺寸限制,窗口将捕捉到其最小尺寸。

¥Resizes the window to width and height. If width or height are below any set minimum size constraints the window will snap to its minimum size.

win.getSize()

返回 Integer[] - 包含窗口的宽度和高度。

¥Returns Integer[] - Contains the window's width and height.

win.setContentSize(width, height[, animate])

  • width 整数

    ¥width Integer

  • height 整数

    ¥height Integer

  • animate 布尔值(可选)macOS

    ¥animate boolean (optional) macOS

将窗口客户区(例如网页)的大小调整为 widthheight

¥Resizes the window's client area (e.g. the web page) to width and height.

win.getContentSize()

返回 Integer[] - 包含窗口客户区的宽度和高度。

¥Returns Integer[] - Contains the window's client area's width and height.

win.setMinimumSize(width, height)

  • width 整数

    ¥width Integer

  • height 整数

    ¥height Integer

将窗口的最小尺寸设置为 widthheight

¥Sets the minimum size of window to width and height.

win.getMinimumSize()

返回 Integer[] - 包含窗口的最小宽度和高度。

¥Returns Integer[] - Contains the window's minimum width and height.

win.setMaximumSize(width, height)

  • width 整数

    ¥width Integer

  • height 整数

    ¥height Integer

将窗口的最大尺寸设置为 widthheight

¥Sets the maximum size of window to width and height.

win.getMaximumSize()

返回 Integer[] - 包含窗口的最大宽度和高度。

¥Returns Integer[] - Contains the window's maximum width and height.

win.setResizable(resizable)

  • resizable 布尔值

    ¥resizable boolean

设置用户是否可以手动调整窗口大小。

¥Sets whether the window can be manually resized by the user.

win.isResizable()

返回 boolean - 用户是否可以手动调整窗口大小。

¥Returns boolean - Whether the window can be manually resized by the user.

win.setMovable(movable) macOS Windows

  • movable 布尔值

    ¥movable boolean

设置用户是否可以移动窗口。在 Linux 上什么都不做。

¥Sets whether the window can be moved by user. On Linux does nothing.

win.isMovable() macOS Windows

返回 boolean - 用户是否可以移动窗口。

¥Returns boolean - Whether the window can be moved by user.

在 Linux 上始终返回 true

¥On Linux always returns true.

win.setMinimizable(minimizable) macOS Windows

  • minimizable 布尔值

    ¥minimizable boolean

设置用户是否可以手动最小化窗口。在 Linux 上什么都不做。

¥Sets whether the window can be manually minimized by user. On Linux does nothing.

win.isMinimizable() macOS Windows

返回 boolean - 用户是否可以手动最小化窗口。

¥Returns boolean - Whether the window can be manually minimized by the user.

在 Linux 上始终返回 true

¥On Linux always returns true.

win.setMaximizable(maximizable) macOS Windows

  • maximizable 布尔值

    ¥maximizable boolean

设置用户是否可以手动最大化窗口。在 Linux 上什么都不做。

¥Sets whether the window can be manually maximized by user. On Linux does nothing.

win.isMaximizable() macOS Windows

返回 boolean - 用户是否可以手动最大化窗口。

¥Returns boolean - Whether the window can be manually maximized by user.

在 Linux 上始终返回 true

¥On Linux always returns true.

win.setFullScreenable(fullscreenable)

  • fullscreenable 布尔值

    ¥fullscreenable boolean

设置最大化/缩放窗口按钮是否切换全屏模式或最大化窗口。

¥Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.

win.isFullScreenable()

返回 boolean - 最大化/缩放窗口按钮是否切换全屏模式或最大化窗口。

¥Returns boolean - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.

win.setClosable(closable) macOS Windows

  • closable 布尔值

    ¥closable boolean

设置用户是否可以手动关闭窗口。在 Linux 上什么都不做。

¥Sets whether the window can be manually closed by user. On Linux does nothing.

win.isClosable() macOS Windows

返回 boolean - 窗口是否可以由用户手动关闭。

¥Returns boolean - Whether the window can be manually closed by user.

在 Linux 上始终返回 true

¥On Linux always returns true.

win.setHiddenInMissionControl(hidden) macOS

  • hidden 布尔值

    ¥hidden boolean

设置当用户切换到任务控制时是否隐藏窗口。

¥Sets whether the window will be hidden when the user toggles into mission control.

win.isHiddenInMissionControl() macOS

返回 boolean - 当用户切换到任务控制时窗口是否隐藏。

¥Returns boolean - Whether the window will be hidden when the user toggles into mission control.

win.setAlwaysOnTop(flag[, level][, relativeLevel])

  • flag 布尔值

    ¥flag boolean

  • level 字符串(可选) macOS Windows - 值包括 normalfloatingtorn-off-menumodal-panelmain-menustatuspop-up-menuscreen-saverdock(已弃用)。当 flag 为 true 时,默认值为 floating。当标志为假时,level 重置为 normal。请注意,从 floatingstatus,窗口位于 macOS 上的 Dock 下方和 Windows 上的任务栏下方。从 pop-up-menu 到更高版本,它显示在 macOS 上的 Dock 上方和 Windows 上的任务栏上方。有关详细信息,请参阅 macOS 文档

    ¥level string (optional) macOS Windows - Values include normal, floating, torn-off-menu, modal-panel, main-menu, status, pop-up-menu, screen-saver, and dock (Deprecated). The default is floating when flag is true. The level is reset to normal when the flag is false. Note that from floating to status included, the window is placed below the Dock on macOS and below the taskbar on Windows. From pop-up-menu to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the macOS docs for more details.

  • relativeLevel 整数(可选)macOS - 相对于给定的 level 设置此窗口的更高层数。默认为 0。请注意,Apple 不鼓励在 screen-saver 之上设置高于 1 的级别。

    ¥relativeLevel Integer (optional) macOS - The number of layers higher to set this window relative to the given level. The default is 0. Note that Apple discourages setting levels higher than 1 above screen-saver.

设置窗口是否应始终显示在其他窗口之上。设置完毕后,该窗口仍然是一个普通窗口,而不是一个无法获得焦点的工具箱窗口。

¥Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on.

win.isAlwaysOnTop()

返回 boolean - 窗口是否始终位于其他窗口之上。

¥Returns boolean - Whether the window is always on top of other windows.

win.moveAbove(mediaSourceId)

  • mediaSourceId 字符串 - 窗口 ID,格式为 DesktopCapturerSource 的 id。例如 "窗口:1869:0"。

    ¥mediaSourceId string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0".

按 z 顺序将窗口移动到源窗口上方。如果 mediaSourceId 不是窗口类型或者窗口不存在,则此方法将引发错误。

¥Moves window above the source window in the sense of z-order. If the mediaSourceId is not of type window or if the window does not exist then this method throws an error.

win.moveTop()

无论焦点如何,将窗口移动到顶部(z 顺序)

¥Moves window to top(z-order) regardless of focus

win.center()

将窗口移动到屏幕中央。

¥Moves window to the center of the screen.

win.setPosition(x, y[, animate])

  • x 整数

    ¥x Integer

  • y 整数

    ¥y Integer

  • animate 布尔值(可选)macOS

    ¥animate boolean (optional) macOS

将窗口移动到 xy

¥Moves window to x and y.

win.getPosition()

返回 Integer[] - 包含窗口的当前位置。

¥Returns Integer[] - Contains the window's current position.

win.setTitle(title)

  • title 字符串

    ¥title string

将原生窗口的标题更改为 title

¥Changes the title of native window to title.

win.getTitle()

返回 string - 原生窗口的标题。

¥Returns string - The title of the native window.

注意:网页的标题可以与原生窗口的标题不同。

¥Note: The title of the web page can be different from the title of the native window.

win.setSheetOffset(offsetY[, offsetX]) macOS

  • offsetY 漂浮

    ¥offsetY Float

  • offsetX 浮动(可选)

    ¥offsetX Float (optional)

更改 macOS 上工作表的附着点。默认情况下,工作表附加在窗口框架的正下方,但你可能希望将它们显示在 HTML 渲染的工具栏下方。例如:

¥Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example:

const { BrowserWindow } = require('electron')
const win = new BrowserWindow()

const toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
win.setSheetOffset(toolbarRect.height)

win.flashFrame(flag)

History
  • flag 布尔值

    ¥flag boolean

开始或停止闪烁窗口以吸引用户的注意力。

¥Starts or stops flashing the window to attract user's attention.

win.setSkipTaskbar(skip) macOS Windows

  • skip 布尔值

    ¥skip boolean

使窗口不显示在任务栏中。

¥Makes the window not show in the taskbar.

win.setKiosk(flag)

  • flag 布尔值

    ¥flag boolean

进入或离开信息亭模式。

¥Enters or leaves kiosk mode.

win.isKiosk()

返回 boolean - 窗口是否处于 kiosk 模式。

¥Returns boolean - Whether the window is in kiosk mode.

win.isTabletMode() Windows

返回 boolean - 窗口是否处于 Windows 10 平板电脑模式。

¥Returns boolean - Whether the window is in Windows 10 tablet mode.

由于 Windows 10 用户可以 将他们的电脑用作平板电脑,在此模式下应用可以选择优化平板电脑的 UI,例如放大标题栏和隐藏标题栏按钮。

¥Since Windows 10 users can use their PC as tablet, under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons.

该 API 返回窗口是否处于平板电脑模式,resize 事件可用于监听平板电脑模式的变化。

¥This API returns whether the window is in tablet mode, and the resize event can be be used to listen to changes to tablet mode.

win.getMediaSourceId()

返回 string - 窗口 ID,格式为 DesktopCapturerSource 的 id。例如 "窗口:1324:0"。

¥Returns string - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0".

更准确地说,格式是 window:id:other_id,其中 id 在 Windows 上是 HWND,在 macOS 上是 CGWindowID (uint64_t),在 Linux 上是 Window (unsigned long)。other_id 用于标识 Web 内容(选项卡),因此位于同一顶层窗口内。

¥More precisely the format is window:id:other_id where id is HWND on Windows, CGWindowID (uint64_t) on macOS and Window (unsigned long) on Linux. other_id is used to identify web contents (tabs) so within the same top level window.

win.getNativeWindowHandle()

返回 Buffer - 窗口的特定于平台的句柄。

¥Returns Buffer - The platform-specific handle of the window.

句柄的原生类型在 Windows 上为 HWND,在 macOS 上为 NSView*,在 Linux 上为 Window (unsigned long)。

¥The native type of the handle is HWND on Windows, NSView* on macOS, and Window (unsigned long) on Linux.

win.hookWindowMessage(message, callback) Windows

  • message 整数

    ¥message Integer

  • callback 函数

    ¥callback Function

    • wParam 缓冲 - 提供给 WndProc 的 wParam

      ¥wParam Buffer - The wParam provided to the WndProc

    • lParam 缓冲 - 提供给 WndProc 的 lParam

      ¥lParam Buffer - The lParam provided to the WndProc

钩子 Windows 消息。当 WndProc 中收到消息时,调用 callback

¥Hooks a windows message. The callback is called when the message is received in the WndProc.

win.isWindowMessageHooked(message) Windows

  • message 整数

    ¥message Integer

返回 boolean - truefalse 取决于消息是否被钩子。

¥Returns boolean - true or false depending on whether the message is hooked.

win.unhookWindowMessage(message) Windows

  • message 整数

    ¥message Integer

取消窗口消息。

¥Unhook the window message.

win.unhookAllWindowMessages() Windows

取消所有窗口消息。

¥Unhooks all of the window messages.

win.setRepresentedFilename(filename) macOS

  • filename 字符串

    ¥filename string

设置窗口代表的文件的路径名,文件的图标将显示在窗口的标题栏中。

¥Sets the pathname of the file the window represents, and the icon of the file will show in window's title bar.

win.getRepresentedFilename() macOS

返回 string - 窗口代表的文件的路径名。

¥Returns string - The pathname of the file the window represents.

win.setDocumentEdited(edited) macOS

  • edited 布尔值

    ¥edited boolean

指定窗口的文档是否已编辑,设置为 true 时标题栏图标将变为灰色。

¥Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to true.

win.isDocumentEdited() macOS

返回 boolean - 窗口的文档是否已被编辑。

¥Returns boolean - Whether the window's document has been edited.

win.focusOnWebView()

win.blurWebView()

win.capturePage([rect, opts])

  • rect 长方形(可选) - 捕获的界限

    ¥rect Rectangle (optional) - The bounds to capture

  • opts 对象(可选)

    ¥opts Object (optional)

    • stayHidden 布尔值(可选) - 保持页面隐藏而不是可见。默认为 false

      ¥stayHidden boolean (optional) - Keep the page hidden instead of visible. Default is false.

    • stayAwake 布尔值(可选) - 保持系统清醒而不是让它休眠。默认为 false

      ¥stayAwake boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is false.

返回 Promise<NativeImage> - 用 NativeImage 解决

¥Returns Promise<NativeImage> - Resolves with a NativeImage

捕获 rect 内页面的快照。省略 rect 将捕获整个可见页面。如果页面不可见,则 rect 可能为空。当浏览器窗口隐藏且捕获器计数非零时,页面被视为可见。如果你希望页面保持隐藏状态,则应确保 stayHidden 设置为 true。

¥Captures a snapshot of the page within rect. Omitting rect will capture the whole visible page. If the page is not visible, rect may be empty. 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.

win.loadURL(url[, options])

  • url 字符串

    ¥url string

  • options 对象(可选)

    ¥options Object (optional)

    • httpReferrer(字符串 | 推荐人)(可选) - HTTP 引用 URL。

      ¥httpReferrer (string | Referrer) (optional) - An HTTP Referrer URL.

    • userAgent 字符串(可选) - 发起请求的用户代理。

      ¥userAgent string (optional) - A user agent originating the request.

    • extraHeaders 字符串(可选) - 由 "\n" 分隔的额外标头

      ¥extraHeaders string (optional) - Extra headers separated by "\n"

    • postData (上传原始数据 | UploadFile)[](可选)

      ¥postData (UploadRawData | UploadFile)[] (optional)

    • baseURLForDataURL 字符串(可选) - 数据 URL 加载的文件的基本 URL(带有尾随路径分隔符)。仅当指定的 url 是数据 URL 并且需要加载其他文件时才需要这样做。

      ¥baseURLForDataURL string (optional) - Base URL (with trailing path separator) for files to be loaded by the data URL. This is needed only if the specified url is a data URL and needs to load other files.

返回 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).

webContents.loadURL(url[, options]) 相同。

¥Same as webContents.loadURL(url[, options]).

url 可以是远程地址(例如 http://)或使用 file:// 协议的本地 HTML 文件的路径。

¥The url can be a remote address (e.g. http://) or a path to a local HTML file using the file:// protocol.

为了确保文件 URL 的格式正确,建议使用 Node 的 url.format 方法:

¥To ensure that file URLs are properly formatted, it is recommended to use Node's url.format method:

const { BrowserWindow } = require('electron')
const win = new BrowserWindow()

const url = require('url').format({
protocol: 'file',
slashes: true,
pathname: require('node:path').join(__dirname, 'index.html')
})

win.loadURL(url)

你可以通过执行以下操作,使用带有 URL 编码数据的 POST 请求加载 URL:

¥You can load a URL using a POST request with URL-encoded data by doing the following:

const { BrowserWindow } = require('electron')
const win = new BrowserWindow()

win.loadURL('http://localhost:8000/post', {
postData: [{
type: 'rawData',
bytes: Buffer.from('hello=world')
}],
extraHeaders: 'Content-Type: application/x-www-form-urlencoded'
})

win.loadFile(filePath[, options])

  • filePath 字符串

    ¥filePath string

  • options 对象(可选)

    ¥options Object (optional)

    • query 记录<字符串,字符串>(可选) - 传递至 url.format()

      ¥query Record<string, string> (optional) - Passed to url.format().

    • search 字符串(可选) - 传递至 url.format()

      ¥search string (optional) - Passed to url.format().

    • hash 字符串(可选) - 传递至 url.format()

      ¥hash string (optional) - Passed to url.format().

返回 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).

webContents.loadFile 相同,filePath 应该是相对于应用根目录的 HTML 文件的路径。有关更多信息,请参阅 webContents 文档。

¥Same as webContents.loadFile, filePath should be a path to an HTML file relative to the root of your application. See the webContents docs for more information.

win.reload()

webContents.reload 相同。

¥Same as webContents.reload.

win.setMenu(menu) Linux Windows

  • menu Menu | null

menu 设置为窗口的菜单栏。

¥Sets the menu as the window's menu bar.

win.removeMenu() Linux Windows

删除窗口的菜单栏。

¥Remove the window's menu bar.

win.setProgressBar(progress[, options])

  • progress 双倍的

    ¥progress Double

  • options 对象(可选)

    ¥options Object (optional)

    • mode 字符串 Windows - 进度条模式。可以是 nonenormalindeterminateerrorpaused

      ¥mode string Windows - Mode for the progress bar. Can be none, normal, indeterminate, error or paused.

设置进度条中的进度值。有效范围为 [0, 1.0]。

¥Sets progress value in progress bar. Valid range is [0, 1.0].

当进度 < 0 时移除进度条;当进度 > 1 时更改为不确定模式。

¥Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1.

在 Linux 平台上,仅支持 Unity 桌面环境,需要将 *.desktop 文件名指定到 package.json 中的 desktopName 字段。默认情况下,它将采用 {app.name}.desktop

¥On Linux platform, only supports Unity desktop environment, you need to specify the *.desktop file name to desktopName field in package.json. By default, it will assume {app.name}.desktop.

在 Windows 上,可以传递模式。接受的值为 nonenormalindeterminateerrorpaused。如果你在未设置模式的情况下调用 setProgressBar(但其值在有效范围内),则将假定为 normal

¥On Windows, a mode can be passed. Accepted values are none, normal, indeterminate, error, and paused. If you call setProgressBar without a mode set (but with a value within the valid range), normal will be assumed.

win.setOverlayIcon(overlay, description) Windows

  • overlay NativeImage | 无效的 - 显示在任务栏图标右下角的图标。如果该参数为 null,则清除叠加

    ¥overlay NativeImage | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter is null, the overlay is cleared

  • description 字符串 - 将提供给辅助功能屏幕阅读器的描述

    ¥description string - a description that will be provided to Accessibility screen readers

在当前任务栏图标上设置 16 x 16 像素的覆盖层,通常用于传达某种应用状态或被动通知用户。

¥Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user.

win.invalidateShadow() macOS

使窗口阴影无效,以便根据当前窗口形状重新计算它。

¥Invalidates the window shadow so that it is recomputed based on the current window shape.

透明的 BrowserWindows 有时会在 macOS 上留下视觉伪影。例如,在执行动画时,可以使用此方法来清除这些伪影。

¥BrowserWindows that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation.

win.setHasShadow(hasShadow)

  • hasShadow 布尔值

    ¥hasShadow boolean

设置窗口是否应该有阴影。

¥Sets whether the window should have a shadow.

win.hasShadow()

返回 boolean - 窗户是否有阴影。

¥Returns boolean - Whether the window has a shadow.

win.setOpacity(opacity) Windows macOS

  • opacity 数字 - 介于 0.0(完全透明)和 1.0(完全不透明)之间

    ¥opacity number - between 0.0 (fully transparent) and 1.0 (fully opaque)

设置窗口的不透明度。在 Linux 上,不执行任何操作。超出范围的数值被限制在 [0, 1] 范围内。

¥Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the [0, 1] range.

win.getOpacity()

返回 number - 介于 0.0(完全透明)和 1.0(完全不透明)之间。在 Linux 上,始终返回 1。

¥Returns number - between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1.

win.setShape(rects) Windows Linux 实验

¥win.setShape(rects) Windows Linux Experimental

  • rects Rectangle[] - 在窗口上设置形状。传递空列表会将窗口恢复为矩形。

    ¥rects Rectangle[] - Sets a shape on the window. Passing an empty list reverts the window to being rectangular.

设置窗口形状确定窗口内系统允许绘图和用户交互的区域。在给定区域之外,不会绘制任何像素,也不会注册任何鼠标事件。该窗口不会接收该区域之外的鼠标事件,但会传递到窗口后面的任何事件。

¥Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window.

win.setThumbarButtons(buttons) Windows

返回 boolean - 按钮是否添加成功

¥Returns boolean - Whether the buttons were added successfully

将具有指定按钮集的缩略图工具栏添加到任务栏按钮布局中窗口的缩略图中。返回一个 boolean 对象,表示缩略图是否添加成功。

¥Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a boolean object indicates whether the thumbnail has been added successfully.

由于空间有限,缩略图工具栏中的按钮数量不应超过 7 个。一旦设置了缩略图工具栏,由于平台的限制,该工具栏将无法删除。但你可以使用空数组调用 API 来清理按钮。

¥The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform's limitation. But you can call the API with an empty array to clean the buttons.

buttonsButton 对象的数组:

¥The buttons is an array of Button objects:

  • Button 对象

    ¥Button Object

    • icon NativeImage - 缩略图工具栏中显示的图标。

      ¥icon NativeImage - The icon showing in thumbnail toolbar.

    • click 函数

      ¥click Function

    • tooltip 字符串(可选) - 按钮工具提示的文本。

      ¥tooltip string (optional) - The text of the button's tooltip.

    • flags 字符串[](可选) - 控制按钮的特定状态和行为。默认为 ['enabled']

      ¥flags string[] (optional) - Control specific states and behaviors of the button. By default, it is ['enabled'].

flags 是一个数组,可以包含以下 string

¥The flags is an array that can include following strings:

  • enabled - 该按钮处于活动状态并且可供用户使用。

    ¥enabled - The button is active and available to the user.

  • disabled - 该按钮被禁用。它存在,但具有表明它不会响应用户操作的视觉状态。

    ¥disabled - The button is disabled. It is present, but has a visual state indicating it will not respond to user action.

  • dismissonclick - 单击该按钮后,缩略图窗口立即关闭。

    ¥dismissonclick - When the button is clicked, the thumbnail window closes immediately.

  • nobackground - 不要绘制按钮边框,仅使用图片。

    ¥nobackground - Do not draw a button border, use only the image.

  • hidden - 该按钮不会向用户显示。

    ¥hidden - The button is not shown to the user.

  • noninteractive - 按钮已启用但不可交互;没有绘制按下按钮的状态。该值适用于在通知中使用按钮的情况。

    ¥noninteractive - The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification.

win.setThumbnailClip(region) Windows

设置将鼠标悬停在任务栏中的窗口上时显示的缩略图图片的窗口区域。你可以通过指定空白区域将缩略图重置为整个窗口:{ x: 0, y: 0, width: 0, height: 0 }

¥Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: { x: 0, y: 0, width: 0, height: 0 }.

win.setThumbnailToolTip(toolTip) Windows

  • toolTip 字符串

    ¥toolTip string

设置将鼠标悬停在任务栏中的窗口缩略图上时显示的工具提示。

¥Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar.

win.setAppDetails(options) Windows

  • options 对象

    ¥options Object

    • appId 字符串(可选) - 窗户是 应用用户模型 ID。必须设置,否则其他选项无效。

      ¥appId string (optional) - Window's App User Model ID. It has to be set, otherwise the other options will have no effect.

    • appIconPath 字符串(可选) - 窗户是 重新启动图标

      ¥appIconPath string (optional) - Window's Relaunch Icon.

    • appIconIndex 整数(可选) - appIconPath 中图标的索引。当 appIconPath 未设置时忽略。默认为 0

      ¥appIconIndex Integer (optional) - Index of the icon in appIconPath. Ignored when appIconPath is not set. Default is 0.

    • relaunchCommand 字符串(可选) - 窗户是 重新启动命令

      ¥relaunchCommand string (optional) - Window's Relaunch Command.

    • relaunchDisplayName 字符串(可选) - 窗户是 重新启动显示名称

      ¥relaunchDisplayName string (optional) - Window's Relaunch Display Name.

设置窗口任务栏按钮的属性。

¥Sets the properties for the window's taskbar button.

注意:relaunchCommandrelaunchDisplayName 必须始终设置在一起。如果未设置这些属性之一,则两者都不会被使用。

¥Note: relaunchCommand and relaunchDisplayName must always be set together. If one of those properties is not set, then neither will be used.

win.showDefinitionForSelection() macOS

webContents.showDefinitionForSelection() 相同。

¥Same as webContents.showDefinitionForSelection().

win.setIcon(icon) Windows Linux

更改窗口图标。

¥Changes window icon.

win.setWindowButtonVisibility(visible) macOS

  • visible 布尔值

    ¥visible boolean

设置窗口交通灯按钮是否可见。

¥Sets whether the window traffic light buttons should be visible.

win.setAutoHideMenuBar(hide) Windows Linux

  • hide 布尔值

    ¥hide boolean

设置窗口菜单栏是否自动隐藏。一旦设置,菜单栏将仅在用户按下单个 Alt 键时显示。

¥Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single Alt key.

如果菜单栏已经可见,调用 setAutoHideMenuBar(true) 不会立即隐藏它。

¥If the menu bar is already visible, calling setAutoHideMenuBar(true) won't hide it immediately.

win.isMenuBarAutoHide() Windows Linux

返回 boolean - 菜单栏是否自动隐藏。

¥Returns boolean - Whether menu bar automatically hides itself.

win.setMenuBarVisibility(visible) Windows Linux

  • visible 布尔值

    ¥visible boolean

设置菜单栏是否可见。如果菜单栏自动隐藏,用户仍然可以通过按单个 Alt 键调出菜单栏。

¥Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single Alt key.

win.isMenuBarVisible() Windows Linux

返回 boolean - 菜单栏是否可见。

¥Returns boolean - Whether the menu bar is visible.

win.setVisibleOnAllWorkspaces(visible[, options]) macOS Linux

  • visible 布尔值

    ¥visible boolean

  • options 对象(可选)

    ¥options Object (optional)

    • visibleOnFullScreen 布尔值(可选)macOS - 设置窗口是否应在全屏窗口上方可见。

      ¥visibleOnFullScreen boolean (optional) macOS - Sets whether the window should be visible above fullscreen windows.

    • skipTransformProcessType 布尔值(可选)macOS - 默认情况下,调用 setVisibleOnAllWorkspaces 将在 UIElementApplication 和 ForegroundApplication 之间转换进程类型,以确保正确的行为。但是,这会在每次调用时隐藏窗口和停靠栏一小段时间。如果你的窗口已经是 UIElementApplication 类型,则可以通过将 true 传递给 skipTransformProcessType 来绕过此转换。

      ¥skipTransformProcessType boolean (optional) macOS - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType.

设置窗口是否应在所有工作区中可见。

¥Sets whether the window should be visible on all workspaces.

注意:该 API 在 Windows 上不执行任何操作。

¥Note: This API does nothing on Windows.

win.isVisibleOnAllWorkspaces() macOS Linux

返回 boolean - 窗口是否在所有工作区中可见。

¥Returns boolean - Whether the window is visible on all workspaces.

注意:此 API 在 Windows 上始终返回 false。

¥Note: This API always returns false on Windows.

win.setIgnoreMouseEvents(ignore[, options])

  • ignore 布尔值

    ¥ignore boolean

  • options 对象(可选)

    ¥options Object (optional)

    • forward 布尔值(可选) macOS Windows - 如果为 true,则将鼠标移动消息转发到 Chromium,启用鼠标相关事件,例如 mouseleave。仅当 ignore 为真时使用。如果 ignore 为 false,则无论该值如何,转发始终被禁用。

      ¥forward boolean (optional) macOS Windows - If true, forwards mouse move messages to Chromium, enabling mouse related events such as mouseleave. Only used when ignore is true. If ignore is false, forwarding is always disabled regardless of this value.

使窗口忽略所有鼠标事件。

¥Makes the window ignore all mouse events.

该窗口中发生的所有鼠标事件都会传递到该窗口下方的窗口,但如果该窗口具有焦点,它仍然会接收键盘事件。

¥All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events.

win.setContentProtection(enable) macOS Windows

  • enable 布尔值

    ¥enable boolean

防止窗口内容被其他应用捕获。

¥Prevents the window contents from being captured by other apps.

在 macOS 上,它将 NSWindow 的共享类型设置为 NSWindowSharingNone。在 Windows 上,它使用 WDA_EXCLUDEFROMCAPTURE 调用 SetWindowDisplayAffinity。对于 Windows 10 版本 2004 及更高版本,窗口将从捕获中完全删除,较旧的 Windows 版本的行为就像应用 WDA_MONITOR 捕获黑色窗口一样。

¥On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with WDA_EXCLUDEFROMCAPTURE. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if WDA_MONITOR is applied capturing a black window.

win.setFocusable(focusable) macOS Windows

  • focusable 布尔值

    ¥focusable boolean

更改窗口是否可以聚焦。

¥Changes whether the window can be focused.

在 macOS 上,它不会从窗口中移除焦点。

¥On macOS it does not remove the focus from the window.

win.isFocusable() macOS Windows

返回 boolean - 窗口是否可以聚焦。

¥Returns boolean - Whether the window can be focused.

win.setParentWindow(parent)

  • parent BrowserWindow | null

设置 parent 为当前窗口的父窗口,传递 null 会将当前窗口变成顶层窗口。

¥Sets parent as current window's parent window, passing null will turn current window into a top-level window.

win.getParentWindow()

返回 BrowserWindow | null - 父窗口或 null(如果没有父窗口)。

¥Returns BrowserWindow | null - The parent window or null if there is no parent.

win.getChildWindows()

返回 BrowserWindow[] - 所有子窗口。

¥Returns BrowserWindow[] - All child windows.

win.setAutoHideCursor(autoHide) macOS

  • autoHide 布尔值

    ¥autoHide boolean

控制打字时是否隐藏光标。

¥Controls whether to hide cursor when typing.

win.selectPreviousTab() macOS

当启用原生选项卡并且窗口中还有其他选项卡时,选择上一个选项卡。

¥Selects the previous tab when native tabs are enabled and there are other tabs in the window.

win.selectNextTab() macOS

当启用原生选项卡并且窗口中有其他选项卡时选择下一个选项卡。

¥Selects the next tab when native tabs are enabled and there are other tabs in the window.

win.showAllTabs() macOS

启用原生选项卡时显示或隐藏选项卡概述。

¥Shows or hides the tab overview when native tabs are enabled.

win.mergeAllWindows() macOS

当启用原生选项卡并且有多个打开的窗口时,将所有窗口合并为具有多个选项卡的一个窗口。

¥Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window.

win.moveTabToNewWindow() macOS

如果启用了原生选项卡并且当前窗口中有多个选项卡,则将当前选项卡移动到新窗口中。

¥Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window.

win.toggleTabBar() macOS

如果启用了原生选项卡并且当前窗口中只有一个选项卡,则切换选项卡栏的可见性。

¥Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window.

win.addTabbedWindow(browserWindow) macOS

  • browserWindow BrowserWindow

在窗口实例的选项卡之后添加一个窗口作为该窗口上的选项卡。

¥Adds a window as a tab on this window, after the tab for the window instance.

win.setVibrancy(type) macOS

  • type 字符串 | 无效的 - 可以是 titlebarselectionmenupopoversidebarheadersheetwindowhudfullscreen-uitooltipcontentunder-windowunder-page。有关详细信息,请参阅 macOS 文档

    ¥type string | null - Can be titlebar, selection, menu, popover, sidebar, header, sheet, window, hud, fullscreen-ui, tooltip, content, under-window, or under-page. See the macOS documentation for more details.

为浏览器窗口添加活力效果。传递 null 或空字符串将消除窗口的活力效果。

¥Adds a vibrancy effect to the browser window. Passing null or an empty string will remove the vibrancy effect on the window.

win.setBackgroundMaterial(material) Windows

  • material 字符串

    ¥material string

    • auto - 让桌面窗口管理器 (DWM) 自动决定系统为该窗口绘制的背景材质。这是默认设置。

      ¥auto - Let the Desktop Window Manager (DWM) automatically decide the system-drawn backdrop material for this window. This is the default.

    • none - 不要绘制任何系统背景。

      ¥none - Don't draw any system backdrop.

    • mica - 绘制与长寿命窗口相对应的背景材质效果。

      ¥mica - Draw the backdrop material effect corresponding to a long-lived window.

    • acrylic - 绘制与瞬态窗口相对应的背景材质效果。

      ¥acrylic - Draw the backdrop material effect corresponding to a transient window.

    • tabbed - 绘制与带有选项卡式标题栏的窗口相对应的背景材质效果。

      ¥tabbed - Draw the backdrop material effect corresponding to a window with a tabbed title bar.

此方法设置浏览器窗口的系统绘制背景材料,包括非客户区域后面。

¥This method sets the browser window's system-drawn background material, including behind the non-client area.

有关详细信息,请参阅 Windows 文档

¥See the Windows documentation for more details.

注意:此方法仅在 Windows 11 22H2 及更高版本上支持。

¥Note: This method is only supported on Windows 11 22H2 and up.

win.setWindowButtonPosition(position) macOS

在无框窗口中设置交通灯按钮的自定义位置。通过 null 会将位置重置为默认值。

¥Set a custom position for the traffic light buttons in frameless window. Passing null will reset the position to default.

win.getWindowButtonPosition() macOS

返回 Point | null - 无框窗红绿灯按钮自定义位置,无自定义位置时返回 null

¥Returns Point | null - The custom position for the traffic light buttons in frameless window, null will be returned when there is no custom position.

win.setTouchBar(touchBar) macOS

  • touchBar TouchBar | null

设置当前窗口的 touchBar 布局。指定 nullundefined 将清除触摸栏。此方法仅在机器具有触摸条时有效。

¥Sets the touchBar layout for the current window. Specifying null or undefined clears the touch bar. This method only has an effect if the machine has a touch bar.

注意:TouchBar API 目前处于实验阶段,可能会在未来的 Electron 版本中更改或删除。

¥Note: The TouchBar API is currently experimental and may change or be removed in future Electron releases.

win.setBrowserView(browserView) 实验性已弃用

¥win.setBrowserView(browserView) Experimental Deprecated

  • browserView BrowserView | 无效的 - 将 browserView 连接到 win。如果附加了其他 BrowserView,它们将从该窗口中删除。

    ¥browserView BrowserView | null - Attach browserView to win. If there are other BrowserViews attached, they will be removed from this window.

注意 BrowserView 类已弃用,并由新的 WebContentsView 类取代。

¥The BrowserView class is deprecated, and replaced by the new WebContentsView class.

win.getBrowserView() 实验性已弃用

¥win.getBrowserView() Experimental Deprecated

返回 BrowserView | null - BrowserView 连接到 win。如果未附加,则返回 null。如果附加多个 BrowserView,则会引发错误。

¥Returns BrowserView | null - The BrowserView attached to win. Returns null if one is not attached. Throws an error if multiple BrowserViews are attached.

注意 BrowserView 类已弃用,并由新的 WebContentsView 类取代。

¥The BrowserView class is deprecated, and replaced by the new WebContentsView class.

win.addBrowserView(browserView) 实验性已弃用

¥win.addBrowserView(browserView) Experimental Deprecated

setBrowserView 的替换 API 支持使用多浏览器视图。

¥Replacement API for setBrowserView supporting work with multi browser views.

注意 BrowserView 类已弃用,并由新的 WebContentsView 类取代。

¥The BrowserView class is deprecated, and replaced by the new WebContentsView class.

win.removeBrowserView(browserView) 实验性已弃用

¥win.removeBrowserView(browserView) Experimental Deprecated

注意 BrowserView 类已弃用,并由新的 WebContentsView 类取代。

¥The BrowserView class is deprecated, and replaced by the new WebContentsView class.

win.setTopBrowserView(browserView) 实验性已弃用

¥win.setTopBrowserView(browserView) Experimental Deprecated

browserView 提升到附加到 win 的其他 BrowserView 之上。如果 browserView 未附加到 win,则会引发错误。

¥Raises browserView above other BrowserViews attached to win. Throws an error if browserView is not attached to win.

注意 BrowserView 类已弃用,并由新的 WebContentsView 类取代。

¥The BrowserView class is deprecated, and replaced by the new WebContentsView class.

win.getBrowserViews() 实验性已弃用

¥win.getBrowserViews() Experimental Deprecated

返回 BrowserView[] - 已附加 addBrowserViewsetBrowserView 的所有 BrowserView 的按 z 索引排序的数组。最顶层的 BrowserView 是数组的最后一个元素。

¥Returns BrowserView[] - a sorted by z-index array of all BrowserViews that have been attached with addBrowserView or setBrowserView. The top-most BrowserView is the last element of the array.

注意 BrowserView 类已弃用,并由新的 WebContentsView 类取代。

¥The BrowserView class is deprecated, and replaced by the new WebContentsView class.

win.setTitleBarOverlay(options) Windows Linux

  • options 对象

    ¥options Object

    • color 字符串(可选) - 启用时窗口控件叠加层的 CSS 颜色。

      ¥color String (optional) - The CSS color of the Window Controls Overlay when enabled.

    • symbolColor 字符串(可选) - 启用后窗口控件叠加上符号的 CSS 颜色。

      ¥symbolColor String (optional) - The CSS color of the symbols on the Window Controls Overlay when enabled.

    • height 整数(可选) - 标题栏和窗口控件叠加的高度(以像素为单位)。

      ¥height Integer (optional) - The height of the title bar and Window Controls Overlay in pixels.

在已启用窗口控件覆盖的窗口上,此方法会更新标题栏覆盖的样式。

¥On a window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay.

在 Linux 上,如果未明确设置,则会自动计算 symbolColor 以具有与 color 的最小可访问对比度。

¥On Linux, the symbolColor is automatically calculated to have minimum accessible contrast to the color if not explicitly set.