Skip to main content

BaseWindow

创建和控制窗口。

进程:主进程

🌐 Process: Main

note

BaseWindow 提供了一种在单个窗口中组合多个网页视图的灵活方式。对于只有单个全尺寸网页视图的窗口,BrowserWindow 类可能是一个更简单的选择。

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

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

// In the main process.
const { BaseWindow, WebContentsView } = require('electron')

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

const leftView = new WebContentsView()
leftView.webContents.loadURL('https://electron.nodejs.cn')
win.contentView.addChildView(leftView)

const rightView = new WebContentsView()
rightView.webContents.loadURL('https://github.com/electron/electron')
win.contentView.addChildView(rightView)

leftView.setBounds({ x: 0, y: 0, width: 400, height: 600 })
rightView.setBounds({ x: 400, y: 0, width: 400, height: 600 })

父窗口和子窗口

🌐 Parent and child windows

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

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

const { BaseWindow } = require('electron')

const parent = new BaseWindow()
const child = new BaseWindow({ parent })

child 窗口将始终显示在 parent 窗口之上。

🌐 The child window will always show on top of the parent 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 { BaseWindow } = require('electron')

const parent = new BaseWindow()
const child = new BaseWindow({ parent, modal: true })

平台须知

🌐 Platform notices

  • 在 macOS 上,模式窗口将显示为附加到父窗口的工作表。
  • 在 macOS 上,当父窗口移动时,子窗口会保持相对于父窗口的位置,而在 Windows 和 Linux 上,子窗口不会移动。
  • 在 Linux 上,模态窗口的类型将更改为 dialog
  • 在 Linux 上,许多桌面环境不支持隐藏模式窗口。

资源管理

🌐 Resource management

当你将 WebContentsView 添加到 BaseWindow 并且 BaseWindow 已关闭时,WebContentsViewwebContents 不会被自动销毁。

🌐 When you add a WebContentsView to a BaseWindow and the BaseWindow is closed, the webContents of the WebContentsView are not destroyed automatically.

当你不再需要 webContents 时,例如当 BaseWindow 被关闭时,关闭 webContents 是你的责任:

🌐 It is your responsibility to close the webContents when you no longer need them, e.g. when the BaseWindow is closed:

const { BaseWindow, WebContentsView } = require('electron')

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

const view = new WebContentsView()
win.contentView.addChildView(view)

win.on('closed', () => {
view.webContents.close()
})

BrowserWindow 不同,如果你不显式关闭 webContents,你将会遇到内存泄漏问题。

🌐 Unlike with a BrowserWindow, if you don't explicitly close the webContents, you'll encounter memory leaks.

类:BaseWindow

🌐 Class: BaseWindow

创建和控制窗口。

进程:主进程

🌐 Process: Main

BaseWindow 是一个 事件触发器

它会根据 options 设置的本地属性创建一个新的 BaseWindow

🌐 It creates a new BaseWindow with native properties as set by the options.

warning

Electron 内置的类不能在用户代码中被继承。 欲了解更多信息,请参见 常见问题

new BaseWindow([options])

实例事件

🌐 Instance Events

使用 new BaseWindow 创建的对象会触发以下事件:

🌐 Objects created with new BaseWindow emit the following events:

note

一些事件仅在特定操作系统上可用,并且会被标注为此。

Event: 'close'

返回:

🌐 Returns:

  • 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
}
note

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

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.

Event: 'query-session-end' Windows

返回:

🌐 Returns:

当会话即将结束(由于关机、机器重启或用户注销)时发出。调用 event.preventDefault() 可以延迟系统关机,但通常最好尊重用户结束会话的选择。不过,如果结束会话可能导致用户丢失数据,你可以选择使用它。

🌐 Emitted when a session is about to end due to a shutdown, machine restart, or user log-off. Calling event.preventDefault() can delay the system shutdown, though it’s generally best to respect the user’s choice to end the session. However, you may choose to use it if ending the session puts the user at risk of losing data.

Event: 'session-end' Windows

返回:

🌐 Returns:

当会话因关机、计算机重启或用户注销即将结束时触发。此事件触发后,无法阻止会话结束。

🌐 Emitted when a session is about to end due to a shutdown, machine restart, or user log-off. Once this event fires, there is no way to prevent the session from ending.

Event: 'blur'

返回:

🌐 Returns:

  • event 活动

当窗口失去焦点时发出。

🌐 Emitted when the window loses focus.

Event: 'focus'

返回:

🌐 Returns:

  • event 活动

当窗口获得焦点时发出。

🌐 Emitted when the window gains focus.

Event: 'show'

显示窗口时发出。

🌐 Emitted when the window is shown.

Event: 'hide'

当窗口隐藏时发出。

🌐 Emitted when the window is hidden.

Event: 'maximize'

当窗口最大化时发出。

🌐 Emitted when window is maximized.

Event: 'unmaximize'

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

🌐 Emitted when the window exits from a maximized state.

Event: 'minimize'

当窗口最小化时发出。

🌐 Emitted when the window is minimized.

Event: 'restore'

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

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

Event: 'will-resize' macOS Windows

返回:

🌐 Returns:

  • event 活动
  • newBounds 矩形 - 窗口正在调整到的大小。
  • details 对象
    • edge(字符串)- 正在拖动以调整大小的窗口边缘。可以是 bottomleftrighttop-lefttop-rightbottom-leftbottom-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
  • 在 macOS 上,可能的值为 bottomright
    • bottom 用于表示垂直调整大小。
    • right 用于表示水平调整大小。

Event: 'resize'

调整窗口大小后发出。

🌐 Emitted after the window has been resized.

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.

Event: 'will-move' macOS Windows

返回:

🌐 Returns:

  • event 活动
  • newBounds 矩形 - 窗口被移动到的位置。

在窗口被移动之前触发。在 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.

Event: 'move'

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

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

Event: 'moved' macOS Windows

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

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

note

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

Event: 'enter-full-screen'

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

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

Event: 'leave-full-screen'

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

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

Event: 'always-on-top-changed'

返回:

🌐 Returns:

  • event 活动
  • isAlwaysOnTop 布尔值

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

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

Event: 'app-command' Windows Linux

返回:

🌐 Returns:

  • event 活动
  • command 字符串

当调用应用命令时触发。这些通常与键盘多媒体键或浏览器命令有关,以及某些 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 { BaseWindow } = require('electron')

const win = new BaseWindow()
win.on('app-command', (e, cmd) => {
// Navigate the window back when the user hits their mouse back button
if (cmd === 'browser-backward') {
// Find the appropriate WebContents to navigate.
}
})

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

🌐 The following app commands are explicitly supported on Linux:

  • browser-backward
  • browser-forward

Event: 'swipe' macOS

返回:

🌐 Returns:

  • event 活动
  • direction 字符串

在三指滑动时触发。可能的方向有 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'.

Event: 'rotate-gesture' macOS

返回:

🌐 Returns:

  • event 活动
  • rotation 浮点

在触控板旋转手势时触发。会持续触发,直到旋转手势结束。每次触发时的 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.

Event: 'sheet-begin' macOS

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

🌐 Emitted when the window opens a sheet.

Event: 'sheet-end' macOS

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

🌐 Emitted when the window has closed a sheet.

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

当用户点击原生 macOS 新建标签按钮时会触发该事件。只有当前的 BrowserWindow 具有 tabbingIdentifier 时,才会显示新建标签按钮。

🌐 Emitted when the user clicks the native macOS new tab button. The new tab button is only visible if the current BrowserWindow has a tabbingIdentifier.

你必须在此处理程序中创建一个窗口,以便 macOS 的标签页功能按预期工作。

🌐 You must create a window in this handler in order for macOS tabbing to work as expected.

Event: 'system-context-menu' Windows Linux

返回:

🌐 Returns:

  • event 活动
  • point - 触发上下文菜单时的屏幕坐标。

当系统上下文菜单在窗口上触发时会发出此事件,通常只有当用户在窗口的非客户区右键点击时才会触发。非客户区是窗口标题栏或你在无边框窗口中声明为 -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.

要将 point 转换为 DIP,请使用 screen.screenToDipPoint(point)

🌐 To convert point to DIP, use screen.screenToDipPoint(point).

静态方法

🌐 Static Methods

BaseWindow 类具有以下静态方法:

🌐 The BaseWindow class has the following static methods:

BaseWindow.getAllWindows()

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

🌐 Returns BaseWindow[] - An array of all opened browser windows.

BaseWindow.getFocusedWindow()

返回 BaseWindow | null - 该应用中当前获得焦点的窗口,否则返回 null

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

BaseWindow.fromId(id)

  • id 整数

返回 BaseWindow | null - 具有指定 id 的窗口。

🌐 Returns BaseWindow | null - The window with the given id.

实例属性

🌐 Instance Properties

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

🌐 Objects created with new BaseWindow have the following properties:

const { BaseWindow } = require('electron')
// In this example `win` is our instance
const win = new BaseWindow({ width: 800, height: 600 })

win.id 只读

🌐 win.id Readonly

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

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

win.contentView

窗口内容视图的 View 属性。

🌐 A View property for the content view of the window.

win.tabbingIdentifier macOS 只读

🌐 win.tabbingIdentifier macOS Readonly

string(可选)属性,其值等于传递给 BrowserWindow 构造函数的 tabbingIdentifier,如果未设置,则为 undefined

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

win.autoHideMenuBar Linux Windows

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 属性,用于确定窗口是否处于简单(狮子版本之前的)全屏模式。

🌐 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.

note

在 Windows 上始终返回 false。

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.

note

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

win.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

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

win.minimizable macOS Windows

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

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

在 Linux 上,设置器不会执行任何操作,但获取器会返回 true

🌐 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 上,设置器不会执行任何操作,但获取器会返回 true

🌐 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 上,设置器不会执行任何操作,但获取器会返回 true

🌐 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 上,设置器不会执行任何操作,但获取器会返回 true

🌐 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 { Menu, BaseWindow } = require('electron')

const win = new BaseWindow({ 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.

win.snapped Windows 只读

🌐 win.snapped Windows Readonly

boolean 属性,用于指示窗口是否通过 Snap 安排

🌐 A boolean property that indicates whether the window is arranged via Snap.

实例方法

🌐 Instance Methods

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

🌐 Objects created with new BaseWindow have the following instance methods:

note

一些方法仅在特定操作系统上可用,并且会被标注为此。

win.setContentView(view)

设置窗口的内容视图。

🌐 Sets the content view of the window.

win.getContentView()

返回 View - 窗口的内容视图。

🌐 Returns View - The content view of the window.

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 布尔值

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

🌐 Sets whether the window should be in fullscreen mode.

note

在 macOS 上,全屏切换是异步进行的。如果后续操作依赖于全屏状态,请使用 'enter-full-screen''leave-full-screen' 事件。

win.isFullScreen()

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

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

win.setSimpleFullScreen(flag) macOS

  • flag 布尔值

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

🌐 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 - 窗口是否处于简单(狮子版本之前的)全屏模式。

🌐 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 浮点数 - 内容视图某部分需保持的宽高比。
  • extraSize 尺寸(可选)macOS - 在保持纵横比的同时,不包括的额外尺寸。

这将使窗口保持纵横比。额外的大小允许开发者拥有指定像素数的空间,这部分空间不包含在纵横比的计算中。该 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 和 { width: 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.

要重置宽高比,将 aspectRatio 的值设为 0:win.setAspectRatio(0)

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

win.setBackgroundColor(backgroundColor)

  • backgroundColor 字符串 - 颜色可以是十六进制、RGB、RGBA、HSL、HSLA 或命名的 CSS 颜色格式。十六进制类型的 alpha 通道是可选的。

backgroundColor 值的有效示例:

🌐 Examples of valid backgroundColor values:

  • 十六进制
    • #fff (shorthand RGB)
    • #ffff (shorthand ARGB)
    • #ffffff (RGB)
    • #ffffffff (ARGB)
  • RGB
    • rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)
      • 例如 RGB(255, 255, 255)
  • RGBA
    • rgba\(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)\)
      • 例如 RGBA(255, 255, 255, 1.0)
  • HSL
    • hsl\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)
      • 例如 HSL(200, 20%, 50%)
  • HSLA
    • hsla\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)
      • 例如 高斯拉(200, 20%, 50%, 0.5)
  • 颜色名称
    • 选项列在 SkParseColor.cpp
    • 与 CSS Color Module Level 3 关键字类似,但区分大小写。
      • 例如 bluevioletred

设置窗口的背景色。请参阅 设置 backgroundColor

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

win.previewFile(path[, displayName]) macOS

  • path 字符串 - 要用 QuickLook 预览的文件的绝对路径。这很重要,因为 Quick Look 会使用路径中的文件名和文件扩展名来确定要打开的文件的内容类型。
  • displayName 字符串(可选)- 在快速预览模态视图中显示的文件名。这仅用于视觉显示,不影响文件的内容类型。默认值为 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 Partial<Rectangle>
  • animate 布尔值(可选)macOS

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

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

const { BaseWindow } = require('electron')

const win = new BaseWindow()

// 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())
note

在 macOS 上,y 坐标值不能小于 托盘 的高度。托盘的高度随着时间而变化,并且取决于操作系统,但通常在 20-40 像素之间。传入小于托盘高度的值将导致窗口与托盘紧贴。

win.getBounds()

返回 Rectangle - 窗口的 bounds,以 Object 的形式。

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

note

在 macOS 上,返回的 y 坐标值最小为 托盘 的高度。例如,调用 win.setBounds({ x: 25, y: 20, width: 800, height: 600 }) 并且托盘高度为 38 时,win.getBounds() 将返回 { x: 25, y: 38, width: 800, height: 600 }

note

在 Wayland 上,该方法将返回 { x: 0, y: 0, ... },因为禁止以检查或编程方式更改全局窗口坐标。

win.getBackgroundColor()

返回 string - 获取窗口的背景颜色,格式为 Hex(#RRGGBB)。

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

请参阅 设置 backgroundColor

🌐 See Setting backgroundColor.

note

alpha 值不会与红色、绿色和蓝色值一起返回。

win.setContentBounds(bounds[, animate])

  • bounds 矩形
  • animate 布尔值(可选)macOS

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

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

win.getContentBounds()

返回 Rectangle - 作为 Object 的窗口客户区的 bounds

🌐 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

note

无论窗口当前状态如何:最大化、最小化或全屏,此函数总是返回窗口在普通状态下的位置和大小。在普通状态下,getBounds 和 getNormalBounds 返回相同的 Rectangle

win.setEnabled(enable)

  • enable 布尔值

禁用或启用该窗口。

🌐 Disable or enable the window.

win.isEnabled()

返回 boolean - 窗口是否已启用。

🌐 Returns boolean - whether the window is enabled.

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

  • width 整数
  • height 整数
  • animate 布尔值(可选)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 整数
  • height 整数
  • animate 布尔值(可选)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 整数
  • height 整数

将窗口的最小尺寸设置为 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 整数
  • height 整数

将窗口的最大尺寸设置为 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 布尔值

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

🌐 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 布尔值

设置窗口是否可以由用户移动。在 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 布尔值

设置窗口是否可以被用户手动最小化。在 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 布尔值

设置窗口是否可以被用户手动最大化。在 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 布尔值

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

🌐 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 布尔值

设置窗口是否可以被用户手动关闭。在 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 布尔值

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

🌐 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 布尔值
  • level 字符串(可选) macOS Windows - 可选值包括 normalfloatingtorn-off-menumodal-panelmain-menustatuspop-up-menuscreen-saver,以及 dock(已弃用)。当 flag 为 true 时,默认值为 floating。当该标志为 false 时,level 将重置为 normal。请注意,从 floatingstatus(含)时,窗口会在 macOS 上位于 Dock 下方,在 Windows 上位于任务栏下方。从 pop-up-menu 到更高数值时,窗口会在 macOS 上显示在 Dock 上方,在 Windows 上显示在任务栏上方。有关更多详情,请参见 macOS 文档
  • relativeLevel 整数(可选)macOS - 相对于给定的 level 要设置此窗口的更高层数。默认值为 0。请注意,苹果不建议将层级设置为超过 screen-saver 以上的 1 层。

设置窗口是否应始终显示在其他窗口之上。设置此项后,窗口仍然是普通窗口,而不是无法获取焦点的工具箱窗口。

🌐 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 字符串 - 以 DesktopCapturerSource 的 id 格式表示的窗口 id。例如 "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 整数
  • y 整数
  • animate 布尔值(可选)macOS

将窗口移动到 xy

🌐 Moves window to x and y.

win.getPosition()

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

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

note

在 Wayland 上,该方法将返回 [0, 0],因为禁止以自省或编程方式更改全局窗口坐标。

win.setTitle(title)

  • title 字符串

将本地窗口的标题更改为 title

🌐 Changes the title of native window to title.

win.getTitle()

返回 string - 本地窗口的标题。

🌐 Returns string - The title of the native window.

note

网页的标题可以与本地窗口的标题不同。

win.setSheetOffset(offsetY[, offsetX]) macOS

  • offsetY 浮点
  • offsetX 浮点数(可选)

更改 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 { BaseWindow } = require('electron')

const win = new BaseWindow()

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

win.flashFrame(flag)

History
  • flag 布尔值

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

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

win.setSkipTaskbar(skip) macOS Windows

  • skip 布尔值

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

🌐 Makes the window not show in the taskbar.

win.setKiosk(flag)

  • flag 布尔值

进入或离开信息亭模式。

🌐 Enters or leaves kiosk mode.

win.isKiosk()

返回 boolean - 窗口是否处于自助服务模式。

🌐 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 用户可以将他们的电脑用作平板,在这种模式下,应用可以选择为平板优化其界面,例如放大标题栏并隐藏标题栏按钮。

🌐 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 used to listen to changes to tablet mode.

win.getMediaSourceId()

返回 string - 窗口 ID,格式为 DesktopCapturerSource 的 ID。例如 “window: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 上是 CGWindowIDuint64_t),在 Linux 上是 Windowunsigned long)。other_id 用于标识网页内容(标签页),因此在同一顶层窗口内使用。

🌐 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 上是 Windowunsigned 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 整数
  • callback 函数
    • wParam 缓冲区 - 提供给 WndProc 的 wParam
    • lParam 缓冲区 - 提供给 WndProc 的 lParam

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

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

win.isWindowMessageHooked(message) Windows

  • message 整数

根据消息是否被钩住,返回 boolean - truefalse

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

win.unhookWindowMessage(message) Windows

  • message 整数

取消窗口消息。

🌐 Unhook the window message.

win.unhookAllWindowMessages() Windows

取消所有窗口消息。

🌐 Unhooks all of the window messages.

win.setRepresentedFilename(filename) macOS

  • filename 字符串

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

🌐 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 布尔值

指定窗口的文档是否已被编辑,当设置为 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.setMenu(menu) Linux Windows

  • menu 菜单 | 空

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 双倍
  • options 对象(可选)
    • mode 字符串 Windows - 进度条模式。可以是 nonenormalindeterminateerrorpaused

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

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

当进度 < 0; Change to indeterminate mode when progress > 1 时移除进度条。

在 Linux 平台上,仅支持 Unity 桌面环境,你需要在 package.json 中将 *.desktop 文件名指定到 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 - 要显示在任务栏图标右下角的图标。如果此参数为 null,覆盖层将被清除
  • description 字符串 - 将提供给辅助功能屏幕阅读器的描述

在当前任务栏图标上设置一个 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.

BaseWindow 的透明部分有时会在 macOS 上留下视觉残影。
这种方法可以在执行动画等操作时,用来清除这些残影。

win.setHasShadow(hasShadow)

  • hasShadow 布尔值

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

🌐 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(完全不透明)之间

设置窗口的不透明度。在 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[] - 在窗口上设置一个形状。传入空列表会使窗口恢复为矩形。

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

🌐 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.

buttons 是一个由 Button 对象组成的数组:

🌐 The buttons is an array of Button objects:

  • Button 对象
    • icon 原生图片 - 缩略图工具栏中显示的图标。
    • click 函数
    • tooltip 字符串(可选)- 按钮工具提示的文本。
    • flags string[](可选)- 控制按钮的特定状态和行为。默认情况下,它是 ['enabled']

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

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

  • enabled - 该按钮处于活动状态并且可供用户使用。
  • disabled - 按钮已被禁用。它存在,但显示的状态表明不会响应用户操作。
  • dismissonclick - 当按钮被点击时,缩略图窗口会立即关闭。
  • nobackground - 不要绘制按钮边框,仅使用图片。
  • hidden - 该按钮不会向用户显示。
  • noninteractive - 该按钮已启用但不可交互;未绘制按下状态。此值适用于按钮用作通知的情况。

win.setThumbnailClip(region) Windows

  • region 矩形 - 窗口区域

设置窗口的区域,以在任务栏中将鼠标悬停在窗口上时显示为缩略图。你可以通过指定空区域来将缩略图重置为整个窗口: { 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 字符串

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

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

win.setAppDetails(options) Windows

  • options 对象
    • appId 字符串(可选)- 窗口的 应用用户模型 ID。必须设置,否则其他选项将无效。
    • appIconPath 字符串(可选)- 窗口的 重新启动图标
    • appIconIndex 整数(可选)- appIconPath 中图标的索引。当未设置 appIconPath 时将被忽略。默认值为 0
    • relaunchCommand 字符串(可选)- 窗口的 重新启动命令
    • relaunchDisplayName 字符串(可选)- 窗口的 重新启动显示名称

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

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

note

relaunchCommandrelaunchDisplayName 必须始终一起设置。 如果其中一个属性未设置,则两个都不会被使用。

win.setAccentColor(accentColor) Windows

  • accentColor 布尔值 | 字符串 | null - 窗口的强调颜色。默认情况下,遵循系统设置中的用户偏好。要重置为系统默认值,请传入 null

设置系统强调色和活动窗口边框的高亮。

🌐 Sets the system accent color and highlighting of active window border.

accentColor 参数接受以下值:

🌐 The accentColor parameter accepts the following values:

  • 颜色字符串 - 类似于 true,但使用标准 CSS 颜色格式(Hex、RGB、RGBA、HSL、HSLA 或命名颜色)设置自定义强调色。在 RGBA/HSLA 格式中,Alpha 值会被忽略,颜色被视为完全不透明。
  • true - 启用窗口的强调色高亮,无论系统 Settings. 中是否为窗口启用了强调色,都使用系统强调色
  • false - 无论系统设置中是否已启用窗口重点色,都禁用窗口的重点色高亮显示。
  • null - 将窗口强调色行为重置为跟随系统设置中的行为。

示例:

🌐 Examples:

const win = new BrowserWindow({ frame: false })

// Set red accent color.
win.setAccentColor('#ff0000')

// RGB format (alpha ignored if present).
win.setAccentColor('rgba(255,0,0,0.5)')

// Enable accent color, using the color specified in System Settings.
win.setAccentColor(true)

// Disable accent color.
win.setAccentColor(false)

// Reset window accent color behavior to follow behavior set in System Settings.
win.setAccentColor(null)

win.getAccentColor() Windows

返回 string | boolean —— 系统强调色和活动窗口边框高亮的十六进制 RGB 格式。

🌐 Returns string | boolean - the system accent color and highlighting of active window border in Hex RGB format.

如果窗口已设置了与系统强调色不同的颜色,将返回窗口强调色。否则,将返回一个布尔值,其中 true 表示窗口使用全局系统强调色,false 表示此窗口已禁用强调色高亮。

🌐 If a color has been set for the window that differs from the system accent color, the window accent color will be returned. Otherwise, a boolean will be returned, with true indicating that the window uses the global system accent color, and false indicating that accent color highlighting is disabled for this window.

win.setIcon(icon) Windows Linux

更改窗口图标。

🌐 Changes window icon.

win.setWindowButtonVisibility(visible) macOS

  • visible 布尔值

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

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

win.setAutoHideMenuBar(hide) Windows Linux

  • hide 布尔值

设置窗口菜单栏是否应自动隐藏。设置后,菜单栏只会在用户按下单个 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 布尔值

设置菜单栏是否可见。如果菜单栏设置为自动隐藏,用户仍然可以通过按单个 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.isSnapped() Windows

返回 boolean - 窗口是否通过 Snap 排列

🌐 Returns boolean - whether the window is arranged via Snap.

当鼠标悬停在窗口最大化按钮上时,通过显示的按钮可以固定窗口,或者通过将窗口拖动到屏幕边缘来固定窗口。

🌐 The window is snapped via buttons shown when the mouse is hovered over window maximize button, or by dragging it to the edges of the screen.

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

  • visible 布尔值
  • options 对象(可选)
    • visibleOnFullScreen 布尔值(可选)macOS - 设置窗口是否应显示在全屏窗口之上。
    • skipTransformProcessType 布尔(可选)macOS - 调用 setVisibleOnAllWorkspaces 默认会在 UIElementApplication 和 ForegroundApplication 之间转换进程类型,以确保正确的行为。然而,每次调用时,这会导致窗口和 Dock 短暂隐藏。如果你的窗口已经是 UIElementApplication 类型,可以通过传递 true 来跳过此类型转换。

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

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

note

这个 API 在 Windows 上不起作用。

win.isVisibleOnAllWorkspaces() macOS Linux

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

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

note

这个 API 在 Windows 上总是返回 false。

win.setIgnoreMouseEvents(ignore[, options])

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

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

🌐 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 布尔值

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

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

在 macOS 上,它将 NSWindow 的 sharingType 设置为 NSWindowSharingNone。 在 Windows 上,它调用 SetWindowDisplayAffinity 并使用 WDA_EXCLUDEFROMCAPTURE。 对于 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.isContentProtected() macOS Windows

返回 boolean - 当前内容保护是否已启用。

🌐 Returns boolean - whether or not content protection is currently enabled.

win.setFocusable(focusable) macOS Windows

  • focusable 布尔值

更改窗口是否可以聚焦。

🌐 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 基础窗口 | null

parent 设置为当前窗口的父窗口,传入 null 将使当前窗口成为顶层窗口。

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

win.getParentWindow()

返回 BaseWindow | null - 父窗口;如果没有父窗口,则返回 null

🌐 Returns BaseWindow | null - The parent window or null if there is no parent.

win.getChildWindows()

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

🌐 Returns BaseWindow[] - All child windows.

win.setAutoHideCursor(autoHide) macOS

  • autoHide 布尔值

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

🌐 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(baseWindow) macOS

  • baseWindow 基础窗口

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

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

win.setVibrancy(type) macOS

  • type 字符串 | null - 可以是 titlebarselectionmenupopoversidebarheadersheetwindowhudfullscreen-uitooltipcontentunder-windowunder-page。更多详情请参见 macOS 文档

为窗口添加活力效果。传入 null 或空字符串将移除窗口的活力效果。

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

win.setBackgroundMaterial(material) Windows

  • material 字符串
    • auto - 让桌面窗口管理器 (DWM) 自动决定此窗口的系统绘制背景材质。这是默认设置。
    • none - 不要绘制任何系统背景。
    • mica - 绘制与长寿命窗口相对应的背景材质效果。
    • acrylic - 绘制与瞬态窗口相对应的背景材质效果。
    • tabbed - 绘制与带有选项卡式标题栏的窗口相对应的背景材质效果。

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

🌐 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.

note

该方法仅在 Windows 11 22H2 及以上版本支持。

win.setWindowButtonPosition(position) macOS

  • position | 空

在无边框窗口中为交通灯按钮设置自定义位置。传入 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 触控栏 | null

设置当前窗口的触控栏布局。指定 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.

note

TouchBar API 目前处于实验阶段,未来的 Electron 版本中可能会发生变化或被移除。

win.setTitleBarOverlay(options) Windows Linux

  • options 对象
    • color 字符串(可选)- 启用时窗口控件覆盖的 CSS 颜色。
    • symbolColor 字符串(可选)- 启用时,窗口控件覆盖上的符号的 CSS 颜色。
    • height 整数(可选)- 标题栏和窗口控制覆盖层的高度,单位为像素。

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

🌐 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.