BrowserWindow
创建并控制浏览器窗口。
Process: Main
在 app 模块 emitted ready 事件之前,您不能使用此模块。
// 在主进程中.
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')
自定义窗口
BrowserWindow 类暴露了各种方法来修改应用窗口的外观和行为。 For more details, see the Window Customization tutorial.
优雅地显示窗口
每次加载页面都是直接展示,用户突然就看到了,这不是一个好的本地应用使用体验 要使窗口显示时没有视觉闪烁,对于不同情况有两种解决方案。
使用 ready-to-show 事件
在加载页面时,渲染进程第一次完成绘制时,如果窗口还没有被显示,渲染进程会发出 ready-to-show 事件 。 在此事件后显示窗口将没有视觉闪烁:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => {
win.show()
})
这个事件通常在 did-finish-load 事件之后发出,但是页面有许多远程资源时,它可能会在 did-finish-load之前发出事件。
请注意,使用此事件意味着渲染器会被认为是"可见的"并绘制,即使 show 是false。 如果您使用 paintWhenInitiallyHidden: false,此事件将永远不会被触发。
设置 backgroundColor 属性
对于一个复杂的应用,ready-to-show 可能发出的太晚,会让应用感觉缓慢。 在这种情况下,建议立刻显示窗口,并使用接近应用程序背景的 backgroundColor
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ backgroundColor: '#2e2c29' })
win.loadURL('https://github.com')
请注意,即使对于使用 ready-to-show 事件的应用,仍建议 设置 backgroundColor,以使应用感觉更接近原生。
一些包括 backgroundColor 的有效值的例子:
const win = new BrowserWindow()
win.setBackgroundColor('hsl(230, 100%, 50%)')
win.setBackgroundColor('rgb(255, 145, 145)')
win.setBackgroundColor('#ff00a3')
win.setBackgroundColor('blueviolet')
For more information about these color types see valid options in win.setBackgroundColor.
父子窗口
通过使用 parent 选项,你可以创建子窗口:
const { BrowserWindow } = require('electron')
const top = new BrowserWindow()
const child = new BrowserWindow({ parent: top })
child.show()
top.show()
child 窗口将总是显示在 top 窗口的顶部.
模态窗口
模态窗口是禁用父窗口的子窗口。 要创建模态窗口,必须同时设置parent和modal属性:
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()
})
页面可见性
页面可见性 API 的工作方式如下:
- 在所有平台上, 可见性状态与窗口是否隐藏/最小化相关。
- 此外, 在 macOS 上, 可见性状态还会跟踪窗口的遮挡状态。 如果窗口被另一个窗口完全遮挡了,可见性状态为
hidden. 在其他平台上,可见性状态只有在使用win.hide()使窗口最小化或者隐藏时才为hidden - 如果创建
BrowserWindow时带有show: false的参数, 最初的可见性状态将为visible尽管窗口实际上是隐藏的。 - 如果
backgroundThrottling被禁用,可见性状态将保持为visible即使窗口被最小化、遮挡或隐藏。
推荐您在可见性状态为 hidden 时暂停消耗资源的操作以便减少电力消耗。
平台相关的提示
- 在 macOS 上,modal 窗口将显示为附加到父窗口的工作表。
- 在 macOS 上,子窗口将保持与父窗口的相对位置。而在 Windows 和 Linux 中,当父窗口移动时子窗口不会移动。
- 在Linux上,模态窗口的类型将更改为
dialog. - 在Linux上,许多桌面环境不支持隐藏模态窗口。
Class: BrowserWindow extends BaseWindow
创建并控制浏览器窗口。
Process: Main
BrowserWindow 是一个 EventEmitter。
通过 options 可以创建一个具有原生属性的 BrowserWindow 。
[!WARNING] Electron's built-in classes cannot be subclassed in user code. For more information, see the FAQ.
new BrowserWindow([options])
实例事件
使用 new BrowserWindow 创建的对象具有以下属性:
[!NOTE] Some events are only available on specific operating systems and are labeled as such.
事件: 'page-title-updated'
返回:
eventEventtitlestringexplicitSetboolean
文档更改标题时触发,调用event.preventDefault()将阻止更改标题 当标题合成自文件 URL 中时, explicitSet 的值为false。
事件: 'close'
返回:
eventEvent
在窗口要关闭的时候触发。 它在DOM 的beforeunload 和 unload 事件之前触发. 调用event.preventDefault()将阻止这个操作。
通常你想通过 beforeunload处理器来决定是否关闭窗口,但是它也会在窗口重载的时候触发. 在 Electron 里,返回除 undefined之外的任何值都将取消关闭. 例如:
window.onbeforeunload = (e) => {
console.log('I do not want to be closed')
// 与通常的浏览器不同,会提示给用户一个消息框,
//返回非空值将默认取消关闭
//建议使用对话框 API 让用户确认关闭应用程序.
e.returnValue = false
}
[!NOTE] There is a subtle difference between the behaviors of
window.onbeforeunload = handlerandwindow.addEventListener('beforeunload', handler). It is recommended to always set theevent.returnValueexplicitly, instead of only returning a value, as the former works more consistently within Electron.
事件: 'closed'
在窗口关闭时触发 当你接收到这个事件的时候, 你应当移除相应窗口的引用对象,避免再次使用它.
Event: 'query-session-end' Windows
返回:
eventWindowSessionEndEvent
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.
事件: 'session-end' Windows
返回:
eventWindowSessionEndEvent
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.
事件: 'unresponsive'
网页变得未响应时触发
事件: 'responsive'
未响应的页面变成响应时触发
事件: 'blur'
当窗口失去焦点时触发
事件: 'focus'
当窗口获得焦点时触发
事件: 'show'
当窗口显示时触发
事件: 'hide'
当窗口隐藏时触发
事件: 'ready-to-show'
当页面已经渲染完成(但是还没有显示) 并且窗口可以被现实时触发
请注意,使用此事件意味着渲染器会被认为是"可见的"并绘制,即使 show 是false。 如果您使用 paintWhenInitiallyHidden: false,此事件将永远不会被触发。
事件: 'maximize'
窗口最大化时触发
事件: 'unmaximize'
当窗口从最大化状态退出时触发
事件: 'minimize'
窗口最小化时触发
事件: 'restore'
当窗口从最小化状态恢复时触发
事件: 'will-resize' macOS Windows
返回:
eventEventnewBoundsRectangle - Size the window is being resized to.detailsObjectedge(string) - 窗口边缘被拖动以调整大小。 值可以是bottom,left,right,top-left,top-right,bottom-left或bottom-right.
调整窗口大小前触发。 调用 event.preventDefault() 将阻止窗口大小调整。
请注意,该事件仅在手动调整窗口大小时触发。 通过 setBounds/setSize 调整窗口大小不会触发此事件。
edge 选项的可用值和行为选项与平台相关 可能的值有
- 在 Windows 平台可用值有
bottom,top,left,right,top-left,top-right,bottom-left,bottom-right. - 在 macOS, 可用值有
bottom和right.bottom值用于表示垂直调整大小。right值用于表示水平调整大小。
事件: 'resize'
调整窗口大小后触发。
事件:'resized' macOS Windows
当窗口完成调整大小后触发一次。
这通常在手动调整窗口大小后触发。 在 macOS 系统上,使用setBounds/setSize调整窗口大小并将animate参数设置为true也会在调整大小完成后触发此事件。
事件: 'will-move' macOS Windows
返回:
eventEventnewBoundsRectangle - Location the window is being moved to.
窗口移动前触发。 在Windows上,调用 event.preventDefault() 将阻止窗口移动。
注意:仅当手动移动窗口时才会触发此消息。 使用 setPosition/setBounds/center 移动窗口不会触发此事件。
事件: 'move'
窗口移动到新位置时触发
事件: 'moved' macOS Windows
当窗口移动到新位置时触发一次
[!NOTE] On macOS, this event is an alias of
move.
事件: 'enter-full-screen'
窗口进入全屏状态时触发
事件: 'leave-full-screen'
窗口离开全屏状态时触发
事件: 'enter-html-full-screen'
窗口进入由HTML API 触发的全屏状态时触发
事件: 'leave-html-full-screen'
窗口离开由HTML API触发的全屏状态时触发
事件: 'always-on-top-changed'
返回:
eventEventisAlwaysOnTopboolean
设置或取消设置窗口总是在其他窗口的顶部显示时触发。
事件: 'app-command' Windows__Linux
返回:
eventEventcommandstring
Emitted when an App Command is invoked. 典型的是键盘上的媒体键或浏览器命令, 以及在Windows上的一些鼠标中内置的“后退”按钮。
命令是小写的,下划线替换为连字符,以及APPCOMMAND_ 前缀将被删除。 例如 APPCOMMAND_BROWSER_BACKWARD将被browser-backward触发.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.on('app-command', (e, cmd) => {
// 当用户鼠标单击返回按钮时将自动返回上一个窗口
if (cmd === 'browser-backward' && win.webContents.canGoBack()) {
win.webContents.goBack()
}
})
以下应用命令在 Linux 上有明确地支持:
browser-backwardbrowser-forward
事件: 'swipe' macOS
返回:
eventEventdirectionstring
三指滑动时触发。 Possible directions are up, right, down, left.
此事件的基本方法是用来处理旧的macOS风格的触摸板滑动,屏幕内容不会随着滑动而移动。 大多数macOS触摸板都不再允许配置这样的滑动,因此为了正确地触发该事件,需将System Preferences > Trackpad > More Gestures中'Swipe between pages'首选项设置为'Swipe with two or three fingers'。
事件: 'rotate-gesture' macOS
返回:
eventEventrotationFloat
在触控板旋转手势上触发。 持续触发直到旋转手势结束。 每次触发的 rotation 值是自上次触发以来旋转的角度。 旋转手势最后一次触发的事件值永远是0。 逆时针旋转值为正值,顺时针旋转值为负值。
事件: 'sheet-begin' macOS
窗口打开sheet(工作表) 时触发
事件: 'sheet-end' macOS
窗口关闭sheet(工作表) 时触发
事件: 'new-window-for-tab' macOS
当点击了系统的新标签按钮时触发
Event: 'system-context-menu' Windows Linux
返回:
eventEventpointPoint - The screen coordinates where the context menu was triggered.
当系统上下文菜单在窗口上触发时发出, 通常只在用户右键点击你窗口的非客户端区域时触发。 非客户端区域指的是窗口标题栏或无边框窗口中被你声明为 -webkit-app-region: drag 的任意区域。
调用 event.preventDefault() 将阻止菜单显示。
To convert point to DIP, use screen.screenToDipPoint(point).
静态方法
BrowserWindow 类有以下方法:
BrowserWindow.getAllWindows()
返回 BrowserWindow[] - 所有打开的窗口的数组
BrowserWindow.getFocusedWindow()
返回 BrowserWindow | null - 此应用程序中当前获得焦点的窗口,如果无就返回 null.
BrowserWindow.fromWebContents(webContents)
webContentsWebContents
返回 BrowserWindow | null - 返回拥有给定 webContents的窗口,否则如果内容不属于一个窗口,返回null。
BrowserWindow.fromBrowserView(browserView) Deprecated
browserViewBrowserView
[!NOTE] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
返回 BrowserWindow | null - 拥有给定 browserView 的窗口。 如果给定的视图没有附加到任何窗口,返回 null。
BrowserWindow.fromId(id)
idInteger
返回 BrowserWindow | null - 带有给定 id 的窗口。
实例属性
使用 new BrowserWindow 创建的对象具有以下属性:
const { BrowserWindow } = require('electron')
// 本例中 `win` 是我们的实例
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com')
win.webContents 只读
此窗口拥有的 WebContents 对象。 所有与网页相关的事件和操作都将通过它完成。
See the webContents documentation for its methods and events.
win.id 只读
一个 Integer 属性代表了窗口的唯一ID。 每个ID在整个Electron应用程序的所有 BrowserWindow 实例中都是唯一的。
win.tabbingIdentifier macOS 只读
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 键时显示。
如果菜单栏已经可见,将该属性设置为 true 将不会使其立刻隐藏。
win.simpleFullScreen
一个 boolean 属性,用于决定窗口是否处于简单(pre-Lion) 全屏模式。
win.fullScreen
一个 boolean 属性,用于决定窗口是否处于全屏模式。
win.focusable Windows macOS
确定窗口是否可作为焦点被选中的 boolean 属性。
win.visibleOnAllWorkspaces macOS Linux
一个 boolean 属性,用于决定窗口是否在所有工作区中可见。
[!NOTE] Always returns false on Windows.
win.shadow
一个 boolean 属性,用于决定窗口是否显示阴影。
win.menuBarVisible Windows Linux
一个 boolean 属性,用于决定菜单栏是否可见。
[!NOTE] If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single
Altkey.
win.kiosk
一个 boolean 属性,用于决定窗口是否处于kiosk模式。
win.documentEdited macOS
一个 boolean 属性指明窗口文档是否已被编辑。
当设置为 true 时,标题栏的图标将变灰。
win.representedFilename macOS
一个 string 属性,用于确定窗口代表的文件的路径名,文件的图标将显示在窗口的标题栏中。
win.title
一个 string 属性,用于确定原生窗口的标题。
[!NOTE] The title of the web page can be different from the title of the native window.
win.minimizable macOS Windows
一个 boolean 属性,用于决定窗口是否可被用户手动最小化。
在 Linux 上,setter 不会进行任何操作,尽管 getter 返回的是 true。
win.maximizable macOS Windows
一个 boolean 属性,用于决定窗口是否可被用户手动最大化。
在 Linux 上,setter 不会进行任何操作,尽管 getter 返回的是 true。
win.fullScreenable
一个 boolean 属性,决定最大化/缩放窗口按钮是切换全屏模式还是最大化窗口。
win.resizable
一个 boolean 属性,用于决定窗口是否可被用户手动调整大小。
win.closable macOS Windows
一个 boolean 属性,用于决定窗口是否可被用户手动关闭。
在 Linux 上,setter 不会进行任何操作,尽管 getter 返回的是 true。
win.movable macOS Windows
一个 boolean 属性,用于决定窗口是否可被用户移动。
在 Linux 上,setter 不会进行任何操作,尽管 getter 返回的是 true。
win.excludedFromShownWindowsMenu macOS
一个 boolean 属性,用于决定窗口是否从应用程序的 Windows 菜单排除。 默认值为 false
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 属性,定义一个仅为如屏幕阅读器等辅助工具提供的替代标题 。 此字符串不直接对用户可见。
win.snapped Windows Readonly
A boolean property that indicates whether the window is arranged via Snap.
实例方法
使用 new BrowserWindow 创建的对象具有以下实例方法:
[!NOTE] Some methods are only available on specific operating systems and are labeled as such.
win.destroy()
强制关闭窗口, 除了closed之外,close,unload 和 beforeunload 都不会被触发
win.close()
尝试关闭窗口。 该方法与用户手动单击窗口的关闭按钮效果相同。 但网页可能会取消这个关闭操作。 See the close event.
win.focus()
聚焦于窗口
win.blur()
取消窗口的聚焦
win.isFocused()
返回 boolean - 判断窗口是否聚焦
win.isDestroyed()
返回 boolean -判断窗口是否被销毁
win.show()
显示并聚焦于窗口
win.showInactive()
显示但不聚焦于窗口
win.hide()
隐藏窗口
win.isVisible()
返回boolean - 窗口是否在应用前台对用户可见。
win.isModal()
返回 boolean - 判断是否为模态窗口
win.maximize()
最大化窗口。 如果窗口尚未显示,该方法也会将其显示 (但不会聚焦)。
win.unmaximize()
取消窗口最大化
win.isMaximized()
返回 boolean - 判断窗口是否最大化
win.minimize()
最小化窗口。 在某些平台上, 最小化的窗口将显示在Dock中。
win.restore()
将窗口从最小化状态恢复到以前的状态。
win.isMinimized()
返回 boolean -判断窗口是否最小化
win.setFullScreen(flag)
flagboolean
设置窗口是否应处于全屏模式。
[!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 - 窗口当前是否已全屏
[!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
flagboolean
进入或离开简单的全屏模式。
简单全屏模式模拟了 Lion (10.7) 之前的macOS版本中的原生全屏行为。
win.isSimpleFullScreen() macOS
返回 boolean - 窗口是否为简单全屏模式(pre-Lion)。
win.isNormal()
返回 boolean - 窗口是否处于正常状态(未最大化,未最小化,不在全屏模式下)。
win.setAspectRatio(aspectRatio[, extraSize])
aspectRatioFloat- 为内容视图保持的宽高比.extraSizeSize (optional) macOS - The extra size not to be included while maintaining the aspect ratio.
这将使窗口保持长宽比。 额外的大小允许开发人员有空间 (以像素为单位), 不包括在纵横比计算中。 此 API 已经考虑了窗口大小和内容大小之间的差异。
想象一个使用高清视频播放器和相关控件的普通窗口。 假假如左边缘有15px, 右边缘有25px, 在播放器下面有50px. 为了在播放器内部保持 16:9 的宽高比(HD @1920x1080 的标准宽高比) ,我们将此函数的参数设置为 16/9 和 { width: 40, height: 50 }。 第二个参数不管网页中的额外的宽度和高度在什么位置, 只要它们存在就行. 在全部内部窗口中,加上任何额外的宽度和高度 。
当窗口使用类似于 win.setSize 这样的 API 调整窗口时,宽高比不会被采用。
To reset an aspect ratio, pass 0 as the aspectRatio value: win.setAspectRatio(0).
win.setBackgroundColor(backgroundColor)
backgroundColorstring - 颜色,格式为 Hex,RGB,RGBA,HSL,HSLA 或 CSS 命名颜色。 对于 Hex 类型,透明通道为可选的。
有效的 backgroundColor 值的例子:
- Hex
- #fff (shorthand RGB)
- #ffff (shorthand ARGB)
- #ffffff (RGB)
- #ffffffff (ARGB)
- RGB
rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)- e.g. rgb(255, 255, 255)
- RGBA
rgba\(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)\)- e.g. rgba(255, 255, 255, 1.0)
- HSL
hsl\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)- e.g. hsl(200, 20%, 50%)
- HSLA
hsla\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)- e.g. hsla(200, 20%, 50%, 0.5)
- Color name
- 名称列表在 SkParseColor.cpp
- 类似 CSS Color Module Level 3 关键字,但大小写敏感。
- 例如
blueviolet或red。
- 例如
设置窗口的背景颜色。 See Setting backgroundColor.
win.previewFile(path[, displayName]) macOS
pathstring -要用 QuickLook 预览的文件的绝对路径。 这一点很重要,因为Quick Look 使用了路径上的文件名和文件扩展名 来决定要打开的文件的内容类型。displayNamestring (可选) - 在Quick Look 模态视图中显示的文件的名称。 这完全是视觉的,不会影响文件的内容类型。 默认值为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])
boundsPartial<Rectangle>animateboolean (可选) macOS
重置窗口,并且移动窗口到指定的位置. 任何未提供的属性将默认为其当前值。
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
// 设置所有 bounds 边界属性
win.setBounds({ x: 440, y: 225, width: 800, height: 600 })
// 设置单一 bounds 边界属性
win.setBounds({ width: 100 })
// { x: 440, y: 225, width: 100, height: 600 }
console.log(win.getBounds())
[!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()
Returns Rectangle - The bounds of the window as Object.
[!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 thatwin.getBounds()will return{ x: 25, y: 38, width: 800, height: 600 }.
win.getBackgroundColor()
返回 string - 格式获取窗口的背景色,格式为 Hex (#RRGGBB)。
[!NOTE] The alpha value is not returned alongside the red, green, and blue values.
win.setContentBounds(bounds[, animate])
boundsRectangleanimateboolean (可选) macOS
调整窗口的工作区 (如网页) 的大小并将其移动到所提供的边界。
win.getContentBounds()
Returns Rectangle - The bounds of the window's client area as Object.
win.getNormalBounds()
Returns Rectangle - Contains the window bounds of the normal state
[!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,
getBoundsandgetNormalBoundsreturn the same Rectangle.
win.setEnabled(enable)
enableboolean
禁用或者启用窗口。
win.isEnabled()
返回 boolean - 窗口是否启用。
win.setSize(width, height[, animate])
widthIntegerheightIntegeranimateboolean (可选) macOS
调整窗口的width和 height. 如果 width 或 height 低于任何设定的最小尺寸约束,窗口将对齐到约束的最小尺寸。
win.getSize()
返回 Integer []-包含窗口的宽度和高度。
win.setContentSize(width, height[, animate])
widthIntegerheightIntegeranimateboolean (可选) macOS
将窗口的工作区 (如网页) 的大小调整为 width 和 height。
win.getContentSize()
返回 Integer []-包含窗口的宽度和高度。
win.setMinimumSize(width, height)
widthIntegerheightInteger
设置窗口最小化的 width 和height.
win.getMinimumSize()
返回 Integer []-包含窗口最小化的宽度和高度。
win.setMaximumSize(width, height)
widthIntegerheightInteger
设置窗口最大化的 width 和 height.
win.getMaximumSize()
返回 Integer []-包含窗口最大化的宽度和高度。
win.setResizable(resizable)
resizableboolean
设置用户是否可以手动调整窗口大小。
win.isResizable()
返回 boolean - 用户是否可以手动调整窗口大小。
win.setMovable(movable) macOS Windows
movableboolean
设置用户是否可以移动窗口。 在Linux上不起作用。
win.isMovable() macOS Windows
返回 boolean - 窗口是否可以被用户拖动
在 Linux 上总是返回 true。
win.setMinimizable(minimizable) macOS Windows
minimizableboolean
设置用户是否可以手动将窗口最小化。 在Linux上不起作用。
win.isMinimizable() macOS Windows
返回 boolean - 用户是否可以手动最小化窗口。
在 Linux 上总是返回 true。
win.setMaximizable(maximizable) macOS Windows
maximizableboolean
设置用户是否可以手动最大化窗口。 在Linux上不起作用。
win.isMaximizable() macOS Windows
返回 boolean - 窗口是否可以最大化.
在 Linux 上总是返回 true。
win.setFullScreenable(fullscreenable)
fullscreenableboolean
设置最大化/缩放窗口按钮是切换全屏模式还是最大化窗口。
win.isFullScreenable()
返回 boolean - 最大化/缩放窗口按钮是切换全屏模式还是最大化窗口。
win.setClosable(closable) macOS Windows
closableboolean
设置用户是否可以手动关闭窗口。 在Linux上不起作用。
win.isClosable() macOS Windows
返回 boolean - 窗口是否被用户关闭了.
在 Linux 上总是返回 true。
win.setHiddenInMissionControl(hidden) macOS
hiddenboolean
Sets whether the window will be hidden when the user toggles into mission control.
win.isHiddenInMissionControl() macOS
Returns boolean - Whether the window will be hidden when the user toggles into mission control.
win.setAlwaysOnTop(flag[, level][, relativeLevel])
flagbooleanlevelstring (可选) macOS Windows - 值包括normal,floating,torn-off-menu,modal-panel,main-menu,status,pop-up-menu,screen-saver和(已弃用)。 当dockflag属性为true时,默认值为floating。 当flag为false时,level会重置为normal。 请注意,包括从floating到status,窗口会被置于 macOS 上的 Dock 下方和 Windows 上的任务栏下方。 从pop-up-menu到更高级别,窗口显示在 macOS 上的Dock上方和 Windows 上的任务栏上方。 更多信息,请查阅 macOS 文档。relativeLevelInteger (可选) macOS - 设置此窗口相对于给定级别的层数。. 默认值为0. 请注意, Apple 不鼓励在屏幕保护程序之上设置高于1的级别。
设置窗口是否应始终显示在其他窗口的前面。 设置后,窗口仍然是一个正常窗口,而不是一个无法获取焦点的工具框窗口。
win.isAlwaysOnTop()
返回 boolean - 当前窗口是否始终在其它窗口之前.
win.moveAbove(mediaSourceId)
mediaSourceIdstring - DesktopCapturerSource格式的窗口 id 。 例如 "window:1869:0"。
将窗口按z轴顺序移动到源窗口前面。 如果 mediaSourceId 不是window类型,或者如果窗口不存在,则此方法会抛出一个错误。
win.moveTop()
无论焦点如何, 将窗口移至顶端(z轴上的顺序).
win.center()
将窗口移动到屏幕中央。
win.setPosition(x, y[, animate])
xIntegeryIntegeranimateboolean (可选) macOS
Moves window to x and y.
win.getPosition()
返回 Integer[] - 返回一个包含当前窗口位置的数组.
win.setTitle(title)
titlestring
将原生窗口的标题更改为 title。
win.getTitle()
返回 string - 本地窗口标题。
[!NOTE] The title of the web page can be different from the title of the native window.
win.setSheetOffset(offsetY[, offsetX]) macOS
offsetYFloatoffsetXFloat (可选)
改变macOS上sheet组件的附着点。 默认情况下,sheet贴在窗口边框正下方,但你可能需要在 HTML 渲染工具栏下方显示它们。 例如:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
const toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
win.setSheetOffset(toolbarRect.height)
win.flashFrame(flag)
History
| Version(s) | Changes |
|---|---|
None |
|
flagboolean
启动或停止闪烁窗口, 以吸引用户的注意。
win.setSkipTaskbar(skip) macOS Windows
skipboolean
使窗口不显示在任务栏中。
win.setKiosk(flag)
flagboolean
进入或离开 kiosk 模式。
win.isKiosk()
返回 boolean - 判断窗口是否处于kiosk模式.
win.isTabletMode() Windows
返回 boolean - 无论当前窗口是否处在 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 返回 窗口是否在平板电脑模式下,并且 调整大小 事件可以用于监听对平板模式的更改。
win.getMediaSourceId()
返回 string - DesktopCapturerSource的id格式的窗口 id 。 例如 "window:1324:0"。
更确切地说,格式是 window:id:other_id。在Windows上 id 是 HWND 类型;在macOS上是 CGWindowID (uint64_t);在Linux上是 Window (unsigned long)。 other_id 用于识别同一顶层窗口内的Web 内容 (选项卡)。
win.getNativeWindowHandle()
返回 Buffer - 窗口的平台特定句柄
Windows上句柄类型为 HWND,macOS 上为 NSView*,Linux 上为Window (unsigned long)
win.hookWindowMessage(message, callback) Windows
messageIntegercallbackFunctionwParamBuffer - ThewParamprovided to the WndProclParamBuffer - ThelParamprovided to the WndProc
钩住窗口消息。 当消息到达 WndProc 时调用callback 。
win.isWindowMessageHooked(message) Windows
messageInteger
返回 boolean - true 或false ,具体取决于是否钩挂了消息.
win.unhookWindowMessage(message) Windows
messageInteger
取消窗口信息的钩子。
win.unhookAllWindowMessages() Windows
取消所有窗口信息的钩子。
win.setRepresentedFilename(filename) macOS
filenamestring
设置窗口所代表的文件的路径名,并且将这个文件的图标放在窗口标题栏上。
win.getRepresentedFilename() macOS
返回 string - 获取窗口当前文件路径.
win.setDocumentEdited(edited) macOS
editedboolean
明确指出窗口文档是否可以编辑, 如果设置为true则将标题栏的图标变成灰色.
win.isDocumentEdited() macOS
返回 boolean - 判断当前窗口文档是否可编辑.
win.focusOnWebView()
win.blurWebView()
win.capturePage([rect, opts])
rectRectangle (optional) - The bounds to captureoptsObject (optional)stayHiddenboolean (可选) - 使页面保持隐藏而不是可见。 默认值为false.stayAwakeboolean (可选) - 使系统保持唤醒状态,而不是让它处于睡眠状态。 默认值为false.
返回 Promise<NativeImage> - 完成后返回一个NativeImage
在 rect内捕获页面的快照。 省略 rect 将捕获整个可见页面。 如果页面不可见, rect 可能是空的。 The page is considered visible when its browser window is hidden and the capturer count is non-zero. 如果你想要页面保持隐藏状态,则应确保 stayHidden 设置为 true。
win.loadURL(url[, options])
urlstring
返回 Promise<void> - 当页面完成加载后 promise 将会resolve (见 did-finish-load),如果页面加载失败,则 reject (见 did-fail-load)。
Same as webContents.loadURL(url[, options]).
url 可以是远程地址 (例如 http://),也可以是 file:// 协议的本地HTML文件的路径.
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('node:url').format({
protocol: 'file',
slashes: true,
pathname: require('node:path').join(__dirname, 'index.html')
})
win.loadURL(url)
您可以通过执行以下操作, 使用带有网址编码数据的 POST请求加载网址:
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])
filePathstring
返回 Promise<void> - 当页面完成加载后 promise 将会resolve (见 did-finish-load),如果页面加载失败,则 reject (见 did-fail-load)。
与 webContents.loadFile相同, filePath 应该是一个与你的应用程序的根路径相关的HTML文件路径。 有关更多信息,请参阅webContents 文档。
win.reload()
与 webContents.reload 相同.
win.setMenu(menu) Linux Windows
menuMenu | null
将 menu 设置为窗口的菜单栏。
win.removeMenu() Linux Windows
删除窗口的菜单栏。
win.setProgressBar(progress[, options])
progressDouble
设置进度条的进度值。 Valid range is [0, 1.0].
当进度小于0时不显示进度; 当进度大于0时显示结果不确定.
在 Linux 平台上,只支持 Unity 桌面模式, 你需要在 package.json 中为 desktopName 指定 *.desktop 的文件名. 默认情况下,将取 {app.name}.desktop。
在 Windows 上, 可以传递模式。 Accepted values are none, normal, indeterminate, error, and paused. 如果没有设置模式 (但值在有效范围内) 的情况下调用 setProgressBar, 默认值为normal。
win.setOverlayIcon(overlay, description) Windows
overlayNativeImage | null - the icon to display on the bottom right corner of the taskbar icon. 如果此参数是null,覆盖层层会被清除。descriptionstring -提供给屏幕阅读器的描述文字
在当前任务栏图标上设置一个 16 x 16 像素的图标, 通常用于传达某种应用程序状态或被动地通知用户。
win.invalidateShadow() macOS
Invalidates the window shadow so that it is recomputed based on the current window shape.
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)
hasShadowboolean
设置窗口是否有阴影。
win.hasShadow()
返回 boolean - 判断窗口是否有阴影.
win.setOpacity(opacity) Windows macOS
opacitynumber - 介于0.0 ( 完全透明 ) 和1.0 ( 完全不透明 ) 之间
设置窗口的不透明度。 在Linux上不起作用。 Out of bound number values are clamped to the [0, 1] range.
win.getOpacity()
返回 number - 介于0.0 (完全透明) 和1.0 (完全不透明) 之间。 在Linux上,始终返回1。
win.setShape(rects) Windows Linux 实验性
rectsRectangle[] - Sets a shape on the window. 通过传入空列表将窗口恢复为矩形。
对窗口形状的设置决定了窗口内系统允许绘制与用户交互的区域. 在给定的区域外, 没有像素会被绘制, 且没有鼠标事件会被登记. 在该区域外的鼠标事件将不会被该窗口接收, 而是落至该窗口后方的任意窗口.
win.setThumbarButtons(buttons) Windows
buttonsThumbarButton[]
返回 boolean - 按钮是否成功添加
将指定的一组按钮添加到菜单栏的缩图工具栏上。 返回一个 boolean 对象表示是否成功地添加了缩略图.
由于空间有限, 缩图工具栏中的按钮数量不要超过7个。 一旦设置了缩略图工具栏,则无法删除。 但你可以通过调用 API 传递一个空数组来清除按钮.
buttons 是一个 Button 对象的数组:
ButtonObjecticonNativeImage - The icon showing in thumbnail toolbar.clickFunctiontooltipstring (可选) - 按钮的提示文本.flagsstring[] (可选) - 控制按钮的特定状态和行为。 默认情况下,值为['enabled']。
flags 属性是一个数组,包含以下string类型的值:
enabled- 该按钮处于活动状态并可供用户使用.disabled- 按钮已禁用。 会以一种视觉状态表示它不会响应用户操作的形式显示。dismissonclick- 当按钮被点击时,缩略图窗口立即关闭。nobackground- 仅仅使用图像而不绘制边框。hidden- 该按钮对用户不可见。noninteractive- 按钮已启用,但不交互;不绘制按钮按下的状态。 此值用于在通知中使用按钮的实例。
win.setThumbnailClip(region) Windows
regionRectangle - Region of the window
将窗口的区域设置为在任务栏中悬停在窗口上方时显示的缩略图图像。 通过指定空区域:{ x: 0, y: 0, width: 0, height: 0 },可以重置整个窗口的缩略图。
win.setThumbnailToolTip(toolTip) Windows
toolTipstring
设置在任务栏中悬停在窗口缩略图上时显示的工具提示。
win.setAppDetails(options) Windows
选项对象appIdstring (可选) - 窗口的 App User Model ID. 该项必须设置, 否则其他选项将没有效果.appIconPathstring (可选) -窗口的 Relaunch Icon.appIconIndexInteger (可选) -appIconPath中的图标索引。 未设置appIconPath时忽略。 默认值为0.relaunchCommandstring (可选) - 窗口的 重新启动命令.relaunchDisplayNamestring (可选) - 窗口的重新启动显示名称.
设置窗口任务栏按钮的属性。
relaunchCommand and relaunchDisplayName must always be set together. 如果其中一个属性没有设置,那么这两个属性都不会使用。
win.setAccentColor(accentColor) Windows
accentColorboolean | string - The accent color for the window. By default, follows user preference in System Settings.
Sets the system accent color and highlighting of active window border.
The accentColor parameter accepts the following values:
- Color string - Sets a custom accent color using standard CSS color formats (Hex, RGB, RGBA, HSL, HSLA, or named colors). Alpha values in RGBA/HSLA formats are ignored and the color is treated as fully opaque.
true- Uses the system's default accent color from user preferences in System Settings.false- Explicitly disables accent color highlighting for the window.
示例
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)')
// Use system accent color.
win.setAccentColor(true)
// Disable accent color.
win.setAccentColor(false)
win.getAccentColor() Windows
Returns string | boolean - the system accent color and highlighting of active window border in Hex RGB format.
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.showDefinitionForSelection() macOS
和 webContents.showDefinitionForSelection() 相同.
win.setIcon(icon) Windows Linux
iconNativeImage | string
设置窗口图标
win.setWindowButtonVisibility(visible) macOS
visibleboolean
设置是否窗口交通灯需要显示。
win.setAutoHideMenuBar(hide) Windows Linux
hideboolean
设置窗口菜单栏是否自动隐藏。 一旦设置,菜单栏将只在用户单击 Alt 键时显示。
如果菜单栏已经可见, 调用 setAutoHideMenuBar(true)时不会立刻隐藏。
win.isMenuBarAutoHide() Windows Linux
返回 boolean - 判断窗口的菜单栏是否自动隐藏.
win.setMenuBarVisibility(visible) Windows Linux
visibleboolean
设置菜单栏是否可见。 如果菜单栏自动隐藏,用户仍然可以通过单击 Alt 键来唤出菜单栏。
win.isMenuBarVisible() Windows Linux
返回 boolean - 判断窗口的菜单栏是否可见.
win.isSnapped() Windows
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
visibleboolean
设置窗口是否在所有工作空间上可见
[!NOTE] This API does nothing on Windows.
win.isVisibleOnAllWorkspaces() macOS Linux
返回 boolean - 判断窗口是否在所有工作空间上可见.
[!NOTE] This API always returns false on Windows.
win.setIgnoreMouseEvents(ignore[, options])
ignoreboolean
忽略窗口内的所有鼠标事件
在此窗口中发生的所有鼠标事件将被传递到此窗口下面的窗口, 但如果此窗口具有焦点, 它仍然会接收键盘事件
win.setContentProtection(enable) macOS Windows
enableboolean
防止窗口内容被其他应用捕获
On Windows, it calls SetWindowDisplayAffinity with WDA_EXCLUDEFROMCAPTURE. 对于 Windows 10 2004以上版,本窗口将完全从抓取中移除,在低版本 Windows 上其行为就像是 WDA_MONITOR 捕捉了黑色窗口。
On macOS, it sets the NSWindow's sharingType to NSWindowSharingNone. Unfortunately, due to an intentional change in macOS, newer Mac applications that use ScreenCaptureKit will capture your window despite win.setContentProtection(true). See here.
win.isContentProtected() macOS Windows
Returns boolean - whether or not content protection is currently enabled.
win.setFocusable(focusable) macOS Windows
focusableboolean
设置窗口是否可聚焦
在 macOS 上,该方法不会从窗口中移除焦点。
win.isFocusable() macOS Windows
Returns boolean - Whether the window can be focused.
win.setParentWindow(parent)
parentBrowserWindow | null
设置 parent 为当前窗口的父窗口. 为null时表示将当前窗口转为顶级窗口
win.getParentWindow()
返回 BrowserWindow | null - 如果没有父窗口则为 null。
win.getChildWindows()
返回 BrowserWindow[] - 首页的子窗口.
win.setAutoHideCursor(autoHide) macOS
autoHideboolean
设置输入时是否隐藏光标
win.selectPreviousTab() macOS
当启用本地选项卡,并且窗口中有另一个标签时,选择上一个选项卡。
win.selectNextTab() macOS
当启用本地选项卡,并且窗口中有另一个标签时,选择下一个选项卡。
win.showAllTabs() macOS
Shows or hides the tab overview when native tabs are enabled.
win.mergeAllWindows() macOS
当启用本地选项卡并且存在多个打开窗口时,将所有窗口合并到一个带有多个选项卡的窗口中。
win.moveTabToNewWindow() macOS
如果启用了本机选项卡并且当前窗口中有多个选项卡,则将当前选项卡移动到新窗口中。
win.toggleTabBar() macOS
如果启用了本机选项卡并且当前窗口中只有一个选项卡,则切换选项卡栏是否可见。
win.addTabbedWindow(browserWindow) macOS
browserWindowBrowserWindow
在该窗口中添加一个窗口作为选项卡,位于窗口实例的选项卡之后。
win.setVibrancy(type[, options]) macOS
typestring | null - Can betitlebar,selection,menu,popover,sidebar,header,sheet,window,hud,fullscreen-ui,tooltip,content,under-window, orunder-page. 更多详细信息,请查阅 macOS documentation
在浏览器窗口中添加一个动态特效。 传递 null 或空字符串将会移除窗口上的动态效果。 The animationDuration parameter only animates fading in or fading out the vibrancy effect. Animating between different types of vibrancy is not supported.
win.setBackgroundMaterial(material) Windows
materialstringauto- Let the Desktop Window Manager (DWM) automatically decide the system-drawn backdrop material for this window. 默认为该值。none- Don't draw any system backdrop.mica- Draw the backdrop material effect corresponding to a long-lived window.acrylic- Draw the backdrop material effect corresponding to a transient window.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.
See the Windows documentation for more details.
[!NOTE] This method is only supported on Windows 11 22H2 and up.
win.setWindowButtonPosition(position) macOS
positionPoint | null
在无框窗口中设置自定义控制按钮的位置。 Passing null will reset the position to default.
win.getWindowButtonPosition() macOS
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
touchBarTouchBar | null
设置窗口的触摸条布局 设置为 null 或undefined将清除触摸条. 此方法只在 设备有触摸条时才生效。
[!NOTE] The TouchBar API is currently experimental and may change or be removed in future Electron releases.
win.setBrowserView(browserView) Experimental Deprecated
browserViewBrowserView | null - AttachbrowserViewtowin. 如果已经附加了其他BrowserView,那么它们将会被从此窗口中移除。
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.getBrowserView() Experimental Deprecated
返回 BrowserView | null - 附加到 win 的 BrowserView 。 如果未附加,则返回 null。 如果附加了多个 BrowserView,则抛出错误。
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.addBrowserView(browserView) Experimental Deprecated
browserViewBrowserView
替代 setBrowserView 的API,支持多个browserView一起使用。
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.removeBrowserView(browserView) Experimental Deprecated
browserViewBrowserView
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.setTopBrowserView(browserView) Experimental Deprecated
browserViewBrowserView
提高 browserView 于其它附加到 win 的 BrowserView 之上 。 如果 browserView 未附加到 win,则抛出错误。
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.getBrowserViews() Experimental Deprecated
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.
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.setTitleBarOverlay(options) Windows Linux
选项对象colorString (optional) - The CSS color of the Window Controls Overlay when enabled.symbolColorString (optional) - The CSS color of the symbols on the Window Controls Overlay when enabled.heightInteger (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.
On Linux, the symbolColor is automatically calculated to have minimum accessible contrast to the color if not explicitly set.