BrowserWindow
Create and control browser windows.创建和控制浏览器窗口。
Process: 进程:Main
This module cannot be used until the 在发出ready
event of the app
module is emitted.app
模块的ready
事件之前,无法使用此模块。
// 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窗口自定义
The BrowserWindow
class exposes various ways to modify the look and behavior of your app's windows. BrowserWindow
类公开了修改应用程序窗口的外观和行为的各种方法。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.要使窗口显示没有视觉闪光,有两种解决方案可用于不同的情况。
Using the ready-to-show
event使用ready-to-show
事件
ready-to-show
eventWhile 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. ready-to-show
事件。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()
})
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.did-finish-load
事件之后发出,但对于具有许多远程资源的页面,它可能在did-finish-load
之前发出。
Please note that using this event implies that the renderer will be considered "visible" and paint even though 请注意,使用此事件意味着即使show
is false. show
为false
,渲染器也将被视为“可见”并进行绘制。This event will never fire if you use 如果使用paintWhenInitiallyHidden: false
paintWhenInitiallyHidden: false
,则此事件永远不会激发
Setting the backgroundColor
property设置backgroundColor
属性
backgroundColor
propertyFor a complex app, the 对于复杂的应用程序,ready-to-show
event could be emitted too late, making the app feel slow. ready-to-show
事件可能会发出得太晚,使应用程序感觉很慢。In this case, it is recommended to show the window immediately, and use a 在这种情况下,建议立即显示窗口,并使用靠近应用程序背景的backgroundColor
close to your app's background:backgroundColor
:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ backgroundColor: '#2e2c29' })
win.loadURL('https://github.com')
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.ready-to-show
事件的应用程序,仍然建议设置backgroundColor
以使应用程序感觉更原生。
Some examples of valid 有效backgroundColor
values include: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.有关这些颜色类型的更多信息,请参阅win.setBackgroundColor中的有效选项。
Parent and child windows父窗口和子窗口
By using 通过使用parent
option, you can create child windows:parent
选项,可以创建子窗口:
const { BrowserWindow } = require('electron')
const top = new BrowserWindow()
const child = new BrowserWindow({ parent: top })
child.show()
top.show()
The child
window will always show on top of the top
window.child
窗口将始终显示在top
窗口的顶部。
Modal windows模态窗口
A modal window is a child window that disables parent window, to create a modal window, you have to set both 模式窗口是禁用父窗口的子窗口,要创建模式窗口,必须同时设置parent
and modal
options:parent
和modal
选项:
const { BrowserWindow } = require('electron')
const child = new BrowserWindow({ parent: top, modal: true, show: false })
child.loadURL('https://github.com')
child.once('ready-to-show', () => {
child.show()
})
Page visibility页面可见性
The Page Visibility API works as follows:页面可见性API的工作原理如下:
On all platforms, the visibility state tracks whether the window is hidden/minimized or not.在所有平台上,可见性状态跟踪窗口是否被隐藏/最小化。Additionally, on macOS, the visibility state also tracks the window occlusion state.此外,在macOS上,可见性状态还跟踪窗口遮挡状态。If the window is occluded (i.e. fully covered) by another window, the visibility state will be如果该窗口被另一个窗口遮挡(即完全覆盖),则可见性状态将是hidden
.hidden
。On other platforms, the visibility state will be在其他平台上,只有当窗口最小化或使用hidden
only when the window is minimized or explicitly hidden withwin.hide()
.win.hide()
显式隐藏时,可见性状态才会是hidden
。If a如果使用BrowserWindow
is created withshow: false
, the initial visibility state will bevisible
despite the window actually being hidden.show: false
创建BrowserWindow
,则初始可见性状态将是visible
,尽管窗口实际上是隐藏的。If如果禁用backgroundThrottling
is disabled, the visibility state will remainvisible
even if the window is minimized, occluded, or hidden.backgroundThrottling
,即使窗口被最小化、遮挡或隐藏,可见性状态也将保持visible
。
It is recommended that you pause expensive operations when the visibility state is 建议您在可见性状态为hidden
in order to minimize power consumption.hidden
时暂停昂贵的操作,以最大限度地减少功耗。
Platform notices平台通知
On macOS modal windows will be displayed as sheets attached to the parent window.在macOS上,模式窗口将显示为附加到父窗口的工作表。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.在macOS上,当父窗口移动时,子窗口将保持与父窗口的相对位置,而在windows和Linux上,子窗口不会移动。On Linux the type of modal windows will be changed to在Linux上,模式窗口的类型将更改为dialog
.dialog
。On Linux many desktop environments do not support hiding a modal window.在Linux上,许多桌面环境不支持隐藏模式窗口。
Class: BrowserWindow
Create and control browser windows.创建和控制浏览器窗口。
Process: 进程:Main
BrowserWindow
is an EventEmitter.
It creates a new 它创建了一个新的BrowserWindow
with native properties as set by the options
.BrowserWindow
,其中包含由options
设置的本机属性。
new BrowserWindow([options])
When setting minimum or maximum window size with 当使用minWidth
/maxWidth
/minHeight
/maxHeight
, it only constrains the users. minWidth
/maxWidth
/minHeight
/maxHeight
设置最小或最大窗口大小时,它只约束用户。It won't prevent you from passing a size that does not follow size constraints to 它不会阻止您将不遵循大小约束的大小传递给setBounds
/setSize
or to the constructor of BrowserWindow
.setBounds
/setSize
或BrowserWindow
的构造函数。
The possible values and behaviors of the type
option are platform dependent. type
选项的可能值和行为取决于平台。Possible values are:可能的值为:
On Linux, possible types are在Linux上,可能的类型是desktop
,dock
,toolbar
,splash
,notification
.desktop
、dock
、toolbar
、splash
、notification
On macOS, possible types are在MacOS上,可能的类型是desktop
,textured
,panel
.desktop
、textured
、panel
Thetextured
type adds metal gradient appearance (NSWindowStyleMaskTexturedBackground
).textured
类型添加金属渐变外观(NSWindowStyleMaskTexturedBackground
)。Thedesktop
type places the window at the desktop background window level (kCGDesktopWindowLevel - 1
).desktop
类型将窗口置于桌面背景窗口级别(kCGDesktopWindowLevel - 1
)。Note that desktop window will not receive focus, keyboard or mouse events, but you can use请注意,桌面窗口不会接收焦点、键盘或鼠标事件,但您可以少量使用globalShortcut来接收输入。globalShortcut
to receive input sparingly.Thepanel
type enables the window to float on top of full-screened apps by adding theNSWindowStyleMaskNonactivatingPanel
style mask,normally reserved for NSPanel, at runtime.panel
类型通过在运行时添加通常为NSPanel保留的NSWindowStyleMaskNonactivatingPanel
样式掩码,使窗口能够浮动在全屏应用程序的顶部。Also, the window will appear on all spaces (desktops).此外,该窗口将出现在所有空间(桌面)上。
On Windows, possible type is在Windows上,可能的类型是toolbar
.toolbar
。
Instance Events实例事件
Objects created with 使用new BrowserWindow
emit the following events:new BrowserWindow
创建的对象会发出以下事件:
Note: Some events are only available on specific operating systems and are labeled as such.某些事件仅在特定的操作系统上可用,并被标记为这样。
Event: 'page-title-updated'
Returns:返回:
event
Eventtitle
stringexplicitSet
boolean
Emitted when the document changed its title, calling 当文档更改其标题时发出,调用event.preventDefault()
will prevent the native window's title from changing. event.preventDefault()
将阻止本机窗口的标题更改。当从文件URL合成标题时,explicitSet
is false when title is synthesized from file URL.explicitSet
为false
。
Event: 'close'
Returns:返回:
event
Event
Emitted when the window is going to be closed. 当窗口将要关闭时发出。It's emitted before the 它是在DOM的beforeunload
and unload
event of the DOM. beforeunload
和unload
事件之前发出的。Calling 调用event.preventDefault()
will cancel the close.event.preventDefault()
将取消关闭。
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. beforeunload
处理程序来决定是否应该关闭窗口,在重新加载窗口时也会调用该处理程序。In Electron, returning any value other than 在Electron中,返回除undefined
would cancel the close. undefined
之外的任何值都将取消收盘。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: There is a subtle difference between the behaviors of :window.onbeforeunload = handler
and window.addEventListener('beforeunload', handler)
. window.onbeforeunload = handler
和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.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: 'session-end' Windows
Emitted when window session is going to end due to force shutdown or machine restart or session log off.当窗口会话由于强制关闭或计算机重新启动或会话注销而即将结束时发出。
Event: 'unresponsive'
Emitted when the web page becomes unresponsive.当网页变得没有响应时发出。
Event: 'responsive'
Emitted when the unresponsive web page becomes responsive again.当无响应的网页再次响应时发出。
Event: 'blur'
Emitted when the window loses focus.当窗口失去焦点时发出。
Event: 'focus'
Emitted when the window gains focus.当窗口获得焦点时发射。
Event: 'show'
Emitted when the window is shown.显示窗口时发出。
Event: 'hide'
Emitted when the window is hidden.当窗口被隐藏时发出。
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.当网页已经渲染(而未显示)并且窗口可以在没有视觉闪光的情况下显示时发出。
Please note that using this event implies that the renderer will be considered "visible" and paint even though 请注意,使用此事件意味着即使show
is false. show
为false
,渲染器也将被视为“可见”并进行绘制。This event will never fire if you use 如果使用paintWhenInitiallyHidden: false
paintWhenInitiallyHidden: false
,则此事件永远不会激发
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
EventnewBounds
Rectangle -Size the window is being resized to.调整窗口大小。details
Objectedge
string -The edge of the window being dragged for resizing.正在拖动以调整大小的窗口的边缘。Can be可以是bottom
,left
,right
,top-left
,top-right
,bottom-left
orbottom-right
.bottom
、left
、right
、top-left
、top-right
、bottom-left
或bottom-right
。
Emitted before the window is resized. 在调整窗口大小之前发出。Calling 调用event.preventDefault()
will prevent the window from being resized.event.preventDefault()
将阻止窗口的大小调整。
Note that this is only emitted when the window is being resized manually. 请注意,只有在手动调整窗口大小时才会发出此消息。Resizing the window with 使用setBounds
/setSize
will not emit this event.setBounds
/setSize
调整窗口大小将不会发出此事件。
The possible values and behaviors of the edge
option are platform dependent. edge
选项的可能值和行为取决于平台。Possible values are:可能的值为:
On Windows, possible values are在Windows上,可能的值是bottom
,top
,left
,right
,top-left
,top-right
,bottom-left
,bottom-right
.bottom
、top
、left
、right
、top-left
、top-right
、bottom-left
、bottom-right
。On macOS, possible values are在MacOS上,可能的值是bottom
andright
.bottom
和right
The valuebottom
is used to denote vertical resizing.bottom
值用于表示垂直调整大小。The value值right
is used to denote horizontal resizing.right
用于表示水平调整大小。
Event: 'resize'
Emitted after the window has been resized.在调整窗口大小后发出。
Event: 'resized' macOS Windows
Emitted once when the window has finished being resized.当窗口完成调整大小时发出一次。
This is usually emitted when the window has been resized manually. 这通常是在手动调整窗口大小时发出的。On macOS, resizing the window with 在macOS上,使用setBounds
/setSize
and setting the animate
parameter to true
will also emit this event once resizing has finished.setBounds
/setSize
调整窗口大小并将animate
参数设置为true
也会在调整大小完成后发出此事件。
Event: 'will-move' macOS Windows
Returns:返回:
event
EventnewBounds
Rectangle -Location the window is being moved to.将窗口移动到的位置。
Emitted before the window is moved. 在窗口移动之前发射。On Windows, calling 在Windows上,调用event.preventDefault()
will prevent the window from being moved.event.preventDefault()
将阻止窗口被移动。
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.setPosition
/setBounds
/center
移动窗口将不会发出此事件。
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: On macOS this event is an alias of :在macOS上,此事件是move
.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: 'enter-html-full-screen'
Emitted when the window enters a full-screen state triggered by HTML API.当窗口进入由HTML API触发的全屏状态时发出。
Event: 'leave-html-full-screen'
Emitted when the window leaves a full-screen state triggered by HTML API.当窗口离开由HTML API触发的全屏状态时发出。
Event: 'always-on-top-changed'
Returns:返回:
event
EventisAlwaysOnTop
boolean
Emitted when the window is set or unset to show always on top of other windows.当窗口被设置或取消设置为始终显示在其他窗口的顶部时发出。
Event: 'app-command' Windows Linux
Returns:返回:
event
Eventcommand
string
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.这些通常与键盘媒体键或浏览器命令以及Windows上一些鼠标内置的“后退”按钮有关。
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
.APPCOMMAND_
前缀被去掉。例如,APPCOMMAND_BROWSER_BACKWARD
作为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()
}
})
The following app commands are explicitly supported on Linux:Linux明确支持以下应用程序命令:
browser-backward
browser-forward
Event: 'scroll-touch-begin' macOS
Emitted when scroll wheel event phase has begun.滚轮事件阶段开始时发出。
Event: 'scroll-touch-end' macOS
Emitted when scroll wheel event phase has ended.滚轮事件阶段结束时发出。
Event: 'scroll-touch-edge' macOS
Emitted when scroll wheel event phase filed upon reaching the edge of element.当滚轮事件阶段在到达元素边缘时归档时发出。
Event: 'swipe' macOS
Returns:返回:
event
Eventdirection
string
Emitted on 3-finger swipe. 三指轻扫时发射。Possible directions are 可能的方向有up
, right
, down
, left
.up
、right
、down
、left
。
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. 此事件背后的方法是为了处理旧的macOS风格的触控板滑动,即屏幕上的内容不会随着滑动而移动。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 大多数macOS触控板不再配置为允许这种滑动,因此为了使其正确发出,“系统首选项”>“触控板”>“更多手势”中的“在页面之间滑动”首选项必须设置为“用两个或三个手指滑动”。System Preferences > Trackpad > More Gestures
must be set to 'Swipe with two or three fingers'.
Event: 'rotate-gesture' macOS
Returns:返回:
event
Eventrotation
Float
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. rotation
值是自上次发射以来旋转的角度(以度为单位)。The last emitted event upon a rotation gesture will always be of value 旋转手势上最后发出的事件的值将始终为0
. 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
Emitted when the native new tab button is clicked.单击本机新选项卡按钮时发出。
Event: 'system-context-menu' Windows
Returns:返回:
event
Eventpoint
Point -The screen coordinates the context menu was triggered at触发上下文菜单的屏幕坐标
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.-webkit-app-region: drag
的任何区域。
Calling 调用event.preventDefault()
will prevent the menu from being displayed.event.preventDefault()
将阻止显示菜单。
Static Methods静态方法
The BrowserWindow
class has the following static methods:BrowserWindow
类具有以下静态方法:
BrowserWindow.getAllWindows()
Returns 返回BrowserWindow[]
- An array of all opened browser windows.所有打开的浏览器窗口的数组。
BrowserWindow.getFocusedWindow()
Returns 返回BrowserWindow | null
- The window that is focused in this application, otherwise returns 此应用程序中关注的窗口,否则返回null
.null
。
BrowserWindow.fromWebContents(webContents)
webContents
WebContents
Returns 返回BrowserWindow | null
- The window that owns the given 拥有给定webContents
or null
if the contents are not owned by a window.webContents
的窗口,如果内容不归窗口所有,则为null
。
BrowserWindow.fromBrowserView(browserView)
browserView
BrowserView
Returns 返回BrowserWindow | null
- The window that owns the given 拥有给定browserView
. browserView
的窗口。If the given view is not attached to any window, returns 如果给定的视图未附加到任何窗口,则返回null
.null
。
BrowserWindow.fromId(id)
id
Integer
Returns 返回BrowserWindow | null
- The window with the given 具有给定id
.id
的窗口。
Instance Properties实例属性
Objects created with 使用new BrowserWindow
have the following properties:new BrowserWindow
创建的对象具有以下属性:
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
Readonly
A 此窗口拥有的WebContents
object this window owns. WebContents
对象。All web page related events and operations will be done via it.所有与网页相关的事件和操作都将通过它完成。
See the 有关其方法和事件,请参阅webContents
documentation for its methods and events.webContents
文档。
win.id
Readonly
A Integer
property representing the unique ID of the window. Integer
属性,表示窗口的唯一ID。Each ID is unique among all 在整个Electron应用程序的所有BrowserWindow
instances of the entire Electron application.BrowserWindow
实例中,每个ID都是唯一的。
win.autoHideMenuBar
A 一个boolean
property that determines whether the window menu bar should hide itself automatically. boolean
属性,用于确定窗口菜单栏是否应自动隐藏。Once set, the menu bar will only show when users press the single 设置后,菜单栏将仅在用户按下单个Alt
key.Alt
键时显示。
If the menu bar is already visible, setting this property to 如果菜单栏已经可见,则将此属性设置为true
won't hide it immediately.true
不会立即隐藏它。
win.simpleFullScreen
A 一个boolean
property that determines whether the window is in simple (pre-Lion) fullscreen mode.boolean
属性,用于确定窗口是否处于简单(Lion之前的)全屏模式。
win.fullScreen
A 一个boolean
property that determines whether the window is in fullscreen mode.boolean
属性,用于确定窗口是否处于全屏模式。
win.focusable
Windows macOS
A 一个boolean
property that determines whether the window is focusable.boolean
属性,用于确定窗口是否可聚焦。
win.visibleOnAllWorkspaces
macOS Linux
A 一个boolean
property that determines whether the window is visible on all workspaces.boolean
属性,用于确定窗口是否在所有工作空间上都可见。
Note: Always returns false on Windows.在Windows上总是返回false
。
win.shadow
A 一个boolean
property that determines whether the window has a shadow.boolean
属性,用于确定窗口是否有阴影。
win.menuBarVisible
Windows Linux
A 一个boolean
property that determines whether the menu bar should be visible.boolean
属性,用于确定菜单栏是否可见。
Note: If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single 如果菜单栏是自动隐藏的,用户仍然可以通过按下单个Alt
key.Alt
键来打开菜单栏。
win.kiosk
A 一个boolean
property that determines whether the window is in kiosk mode.boolean
属性,用于确定窗口是否处于kiosk模式。
win.documentEdited
macOS
A 一个boolean
property that specifies whether the window’s document has been edited.boolean
属性,用于指定窗口的文档是否已被编辑。
The icon in title bar will become gray when set to 当设置为true
.true
时,标题栏中的图标将变为灰色。
win.representedFilename
macOS
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.string
属性,用于确定窗口所代表的文件的路径名,并且该文件的图标将显示在窗口的标题栏中。
win.title
A 一个string
property that determines the title of the native window.string
属性,用于确定本机窗口的标题。
Note: The title of the web page can be different from the title of the native window.网页的标题可以与本机窗口的标题不同。
win.minimizable
macOS Windows
A 一个boolean
property that determines whether the window can be manually minimized by user.boolean
属性,用于确定用户是否可以手动最小化窗口。
On Linux the setter is a no-op, although the getter returns 在Linux上,setter是无操作的,尽管getter返回true
.true
。
win.maximizable
macOS Windows
A 一个boolean
property that determines whether the window can be manually maximized by user.boolean
属性,用于确定用户是否可以手动最大化窗口。
On Linux the setter is a no-op, although the getter returns 在Linux上,setter是无操作的,尽管getter返回true
.true
。
win.fullScreenable
A 一个boolean
property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.boolean
属性,用于确定最大化/缩放窗口按钮是切换全屏模式还是最大化窗口。
win.resizable
A 一个boolean
property that determines whether the window can be manually resized by user.boolean
属性,用于确定用户是否可以手动调整窗口的大小。
win.closable
macOS Windows
A 一个boolean
property that determines whether the window can be manually closed by user.boolean
属性,用于确定用户是否可以手动关闭窗口。
On Linux the setter is a no-op, although the getter returns 在Linux上,setter是无操作的,尽管getter返回true
.true
。
win.movable
macOS Windows
A 一个boolean
property that determines Whether the window can be moved by user.boolean
属性,用于确定用户是否可以移动窗口。
On Linux the setter is a no-op, although the getter returns 在Linux上,setter是无操作的,尽管getter返回true
.true
。
win.excludedFromShownWindowsMenu
macOS
A 一个boolean
property that determines whether the window is excluded from the application’s Windows menu. boolean
属性,用于确定是否将窗口从应用程序的Windows菜单中排除。默认情况下为false
by default.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
A 一个string
property that defines an alternative title provided only to accessibility tools such as screen readers. string
属性,用于定义仅提供给屏幕阅读器等辅助功能工具的替代标题。This string is not directly visible to users.用户无法直接看到此字符串。
Instance Methods实例方法
Objects created with 使用new BrowserWindow
have the following instance methods:new BrowserWindow
创建的对象具有以下实例方法:
Note: Some methods are only available on specific operating systems and are labeled as such.某些方法仅在特定的操作系统上可用,并被标记为这样。
win.destroy()
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.unload
和beforeunload
事件,该窗口也不会发出close
事件,但它保证会发出closed
事件。
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.请参阅close event。
win.focus()
Focuses on the window.聚焦于窗口。
win.blur()
Removes focus from the window.从窗口中移除焦点。
win.isFocused()
Returns 返回boolean
- Whether the window is focused.窗口是否聚焦。
win.isDestroyed()
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()
Returns 返回boolean
- Whether the window is visible to the user.该窗口对用户是否可见。
win.isModal()
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()
Returns 返回boolean
- Whether the window is maximized.窗口是否最大化。
win.minimize()
Minimizes the window. 最小化窗口。On some platforms the minimized window will be shown in the Dock.在某些平台上,最小化的窗口将显示在Dock中。
win.restore()
Restores the window from minimized state to its previous state.将窗口从最小化状态恢复到以前的状态。
win.isMinimized()
Returns 返回boolean
- Whether the window is minimized.窗口是否最小化。
win.setFullScreen(flag)
flag
boolean
Sets whether the window should be in fullscreen mode.设置窗口是否应处于全屏模式。
win.isFullScreen()
Returns 返回boolean
- Whether the window is in fullscreen mode.窗口是否处于全屏模式。
win.setSimpleFullScreen(flag)
macOS
flag
boolean
Enters or leaves simple fullscreen mode.进入或退出简单全屏模式。
Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7).简单全屏模式模拟Lion(10.7)之前的macOS版本中的本机全屏行为。
win.isSimpleFullScreen()
macOS
Returns 返回boolean
- Whether the window is in simple (pre-Lion) fullscreen mode.窗口是否处于简单(Lion之前的)全屏模式。
win.isNormal()
Returns 返回boolean
- Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode).窗口是否处于正常状态(未最大化、未最小化、未处于全屏模式)。
win.setAspectRatio(aspectRatio[, extraSize])
aspectRatio
Float -The aspect ratio to maintain for some portion of the content view.内容视图的某些部分要保持的纵横比。extraSize
Size (optional) macOS -The extra size not to be included while maintaining the aspect ratio.在保持纵横比的同时不包括额外的尺寸。
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.这个API已经考虑了窗口大小与其内容大小之间的差异。
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. 也许左边缘有15个像素的控件,右边缘有25个像素的控制器,玩家下方有50个像素的控制。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 }. 为了在播放器内部保持16:9的纵横比(HD@1920x1080的标准纵横比),我们将使用16/9
和{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.对整个内容视图中的任何额外宽度和高度区域求和。
The aspect ratio is not respected when window is resized programmatically with APIs like 当使用诸如win.setSize
.win.setSize
之类的API以编程方式调整窗口大小时,不考虑纵横比。
win.setBackgroundColor(backgroundColor)
backgroundColor
string -Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format.颜色采用十六进制、RGB、RGBA、HSL、HSLA或命名的CSS颜色格式。The alpha channel is optional for the hex type.对于十六进制类型,alpha通道是可选的。
Examples of valid 有效backgroundColor
values: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)
- rgb(([\d]+),\s([\d]+),\s([\d]+))
- RGBA
- rgba(([\d]+),\s([\d]+),\s([\d]+),\s*([\d.]+))
- e.g. rgba(255, 255, 255, 1.0)
- rgba(([\d]+),\s([\d]+),\s([\d]+),\s*([\d.]+))
- HSL
- hsl((-?[\d.]+),\s([\d.]+)%,\s([\d.]+)%)
- e.g. hsl(200, 20%, 50%)
- hsl((-?[\d.]+),\s([\d.]+)%,\s([\d.]+)%)
- HSLA
- hsla((-?[\d.]+),\s([\d.]+)%,\s([\d.]+)%,\s*([\d.]+))
- e.g. hsla(200, 20%, 50%, 0.5)
- hsla((-?[\d.]+),\s([\d.]+)%,\s([\d.]+)%,\s*([\d.]+))
Color name颜色名称Options are listed in SkParseColor.cpp在SkParseColor.cpp中列出的选项Similar to CSS Color Module Level 3 keywords, but case-sensitive.类似于CSS颜色模块级别3关键字,但区分大小写。- e.g.
blueviolet
orred
- e.g.
Sets the background color of the window. 设置窗口的背景颜色。See Setting backgroundColor
.
win.previewFile(path[, displayName])
macOS
path
string -The absolute path to the file to preview with QuickLook.要使用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
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
.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
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())
win.getBounds()
Returns 返回Rectangle - The 窗口的bounds
of the window as Object
.bounds
,作为Object
。
win.getBackgroundColor()
Returns 返回string
- Gets the background color of the window in Hex (以十六进制(#RRGGBB
) format.#RRGGBB
)格式获取窗口的背景色。
See Setting 请参见设置backgroundColor
.backgroundColor
。
Note: The alpha value is not returned alongside the red, green, and blue values.alpha值不会与红色、绿色和蓝色值一起返回。
win.setContentBounds(bounds[, animate])
bounds
Rectangleanimate
boolean (optional) macOS
Resizes and moves the window's client area (e.g. the web page) to the supplied bounds.调整窗口的客户端区域(例如网页)的大小并将其移动到提供的边界。
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, getBounds and getNormalBounds returns the same Rectangle.在正常状态下,getBounds和getNormalBounds返回相同的Rectangle。
win.setEnabled(enable)
enable
boolean
Disable or enable the window.禁用或启用窗口。
win.isEnabled()
Returns 返回boolean
- whether the window is enabled.窗口是否已启用。
win.setSize(width, height[, animate])
width
Integerheight
Integeranimate
boolean (optional) macOS
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()
Returns 返回Integer[]
- Contains the window's width and height.
win.setContentSize(width, height[, animate])
width
Integerheight
Integeranimate
boolean (optional) macOS
Resizes the window's client area (e.g. the web page) to width
and height
.
win.getContentSize()
Returns 返回Integer[]
- Contains the window's client area's width and height.
win.setMinimumSize(width, height)
width
Integerheight
Integer
Sets the minimum size of window to width
and height
.
win.getMinimumSize()
Returns 返回Integer[]
- Contains the window's minimum width and height.
win.setMaximumSize(width, height)
width
Integerheight
Integer
Sets the maximum size of window to width
and height
.
win.getMaximumSize()
Returns 返回Integer[]
- Contains the window's maximum width and height.包含窗口的最大宽度和高度。
win.setResizable(resizable)
resizable
boolean
Sets whether the window can be manually resized by the user.设置用户是否可以手动调整窗口的大小。
win.isResizable()
Returns 返回boolean
- Whether the window can be manually resized by the user.用户是否可以手动调整窗口的大小。
win.setMovable(movable)
macOS Windows
movable
boolean
Sets whether the window can be moved by user. 设置用户是否可以移动窗口。On Linux does nothing.在Linux上什么都不做。
win.isMovable()
macOS Windows
Returns 返回boolean
- Whether the window can be moved by user.用户是否可以移动窗口。
On Linux always returns 在Linux上,总是返回true
.true
。
win.setMinimizable(minimizable)
macOS Windows
minimizable
boolean
Sets whether the window can be manually minimized by user. On Linux does nothing.设置用户是否可以手动最小化窗口。在Linux上什么都不做。
win.isMinimizable()
macOS Windows
Returns 返回boolean
- Whether the window can be manually minimized by the user.用户是否可以手动最小化窗口。
On Linux always returns 在Linux上,总是返回true
.true
。
win.setMaximizable(maximizable)
macOS Windows
maximizable
boolean
Sets whether the window can be manually maximized by user. 设置用户是否可以手动最大化窗口。On Linux does nothing.在Linux上什么都不做。
win.isMaximizable()
macOS Windows
Returns 返回boolean
- Whether the window can be manually maximized by user.用户是否可以手动最大化窗口。
On Linux always returns 在Linux上,总是返回true
.true
。
win.setFullScreenable(fullscreenable)
fullscreenable
boolean
Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.设置最大化/缩放窗口按钮是切换全屏模式还是最大化窗口。
win.isFullScreenable()
Returns 返回boolean
- Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.最大化/缩放窗口按钮是切换全屏模式还是最大化窗口。
win.setClosable(closable)
macOS Windows
closable
boolean
Sets whether the window can be manually closed by user. 设置用户是否可以手动关闭窗口。On Linux does nothing.在Linux上什么都不做。
win.isClosable()
macOS Windows
Returns 返回boolean
- Whether the window can be manually closed by user.用户是否可以手动关闭窗口。
On Linux always returns 在Linux上,总是返回true
.true
。
win.setAlwaysOnTop(flag[, level][, relativeLevel])
flag
booleanlevel
string (optional) macOS Windows -Values include值包括normal
,floating
,torn-off-menu
,modal-panel
,main-menu
,status
,pop-up-menu
,screen-saver
, and(Deprecated).dock
normal
、floating
、torn-off-menu
、modal-panel
、main-menu
、status
、pop-up-menu
、screen-saver
和dock
(建议弃用)。The default is当floating
whenflag
is true.flag
为true
时,默认值为floating
。The当level
is reset tonormal
when the flag is false.flag
为false
时,level
将重置为normal
。Note that from请注意,从floating
tostatus
included, the window is placed below the Dock on macOS and below the taskbar on Windows.floating
到包含status
,该窗口位于macOS上的Dock下方和Windows上的任务栏下方。From从pop-up-menu
to a higher it is shown above the Dock on macOS and above the taskbar on Windows.pop-up-menu
到更高的菜单,它显示在macOS的Dock上方和Windows的任务栏上方。See the macOS docs for more details.有关更多详细信息,请参阅macOS文档。relativeLevel
Integer (optional) macOS -The number of layers higher to set this window relative to the given将此窗口设置为相对于给定level
.level
更高的层数。The default is默认值为0
.0
。Note that Apple discourages setting levels higher than 1 above请注意,苹果公司不鼓励设置高于screen-saver
.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()
Returns 返回boolean
- Whether the window is always on top of other windows.该窗口是否始终位于其他窗口的顶部。
win.moveAbove(mediaSourceId)
mediaSourceId
string -Window id in the format of DesktopCapturerSource's id. For example "window:1869:0".窗口id的格式为DesktopCapturerSource的id。例如“Window:1869:0”。
Moves window above the source window in the sense of z-order. 按z顺序将窗口移动到源窗口上方。If the 如果mediaSourceId
is not of type window or if the window does not exist then this method throws an error.mediaSourceId
不是window类型,或者该窗口不存在,则此方法将抛出错误。
win.moveTop()
Moves window to top(z-order) regardless of focus将窗口移动到顶部(z顺序),而不考虑焦点
win.center()
Moves window to the center of the screen.将窗口移动到屏幕中心。
win.setPosition(x, y[, animate])
x
Integery
Integeranimate
boolean (optional) macOS
Moves window to 将窗口移动到x
and y
.x
和y
。
win.getPosition()
Returns 返回Integer[]
- Contains the window's current position.包含窗口的当前位置。
win.setTitle(title)
title
string
Changes the title of native window to 将本机窗口的标题更改为title
.title
。
win.getTitle()
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
FloatoffsetX
Float (optional)
Changes the attachment point for sheets on macOS. 更改macOS上工作表的连接点。By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. 默认情况下,工作表附着在窗口框架的正下方,但您可能希望将它们显示在HTML呈现的工具栏下方。For example:例如:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
const toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
win.setSheetOffset(toolbarRect.height)
win.flashFrame(flag)
flag
boolean
Starts or stops flashing the window to attract user's attention.启动或停止闪烁窗口以吸引用户的注意力。
win.setSkipTaskbar(skip)
macOS Windows
skip
boolean
Makes the window not show in the taskbar.使窗口不显示在任务栏中。
win.setKiosk(flag)
flag
boolean
Enters or leaves kiosk mode.进入或离开信息亭模式。
win.isKiosk()
Returns 返回boolean
- Whether the window is in kiosk mode.窗口是否处于信息亭模式。
win.isTabletMode()
Windows
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.由于Windows 10用户可以将电脑用作平板电脑,因此在这种模式下,应用程序可以选择优化平板电脑的用户界面,例如放大标题栏和隐藏标题栏按钮。
This API returns whether the window is in tablet mode, and the 此API返回窗口是否处于平板电脑模式,调整resize
event can be be used to listen to changes to tablet mode.resize
事件可用于侦听对平板电脑模式的更改。
win.getMediaSourceId()
Returns 返回string
- Window id in the format of DesktopCapturerSource's id. 窗口id,格式为DesktopCapturerSource的id。For example "window:1324:0".例如“window:1324:0”。
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. window:id:other_id
,其中id
在Windows上是HWND
,在macOS上是CGWindowID
(uint64_t
),在Linux上是window
(unsigned long
)。other_id
is used to identify web contents (tabs) so within the same top level window.other_id
用于标识相同顶层窗口中的web内容(选项卡)。
win.getNativeWindowHandle()
Returns 返回Buffer
- The platform-specific handle of the window.窗口的特定于平台的句柄。
The native type of the handle is 句柄的本机类型在Windows上为HWND
on Windows, NSView*
on macOS, and Window
(unsigned long
) on Linux.HWND
,在macOS上为NSView*
,在Linux上为Window
(unsigned long
)。
win.hookWindowMessage(message, callback)
Windows
message
Integercallback
FunctionwParam
any -The提供给WndProc的wParam
provided to the WndProcwParam
lParam
any -The提供给WndProc的lParam
provided to the WndProclParam
Hooks a windows message. 挂接一条windows消息。The 当在WndProc中接收到消息时,会调用callback
is called when the message is received in the WndProc.callback
。
win.isWindowMessageHooked(message)
Windows
message
Integer
Returns 返回boolean
- true
or false
depending on whether the message is hooked.true
或false
,具体取决于消息是否被钩住。
win.unhookWindowMessage(message)
Windows
message
Integer
Unhook the window message.解开车窗信息。
win.unhookAllWindowMessages()
Windows
Unhooks all of the window messages.取消预订所有窗口消息。
win.setRepresentedFilename(filename)
macOS
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
Returns 返回string
- The pathname of the file the window represents.窗口所代表的文件的路径名。
win.setDocumentEdited(edited)
macOS
edited
boolean
Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to 指定窗口的文档是否已编辑,并且当设置为true
.true
时,标题栏中的图标将变为灰色。
win.isDocumentEdited()
macOS
Returns 返回boolean
- Whether the window's document has been edited.窗口的文档是否已编辑。
win.focusOnWebView()
win.blurWebView()
win.capturePage([rect])
rect
Rectangle (optional) -The bounds to capture要捕获的边界
Returns 返回Promise<NativeImage>
- Resolves with a NativeImage使用NativeImage进行解决
Captures a snapshot of the page within 在rect
. rect
中捕获页面的快照。Omitting 省略rect
will capture the whole visible page. rect
将捕获整个可见页面。If the page is not visible, 如果页面不可见,则rect
may be empty.rect
可能为空。
win.loadURL(url[, options])
url
string
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).promise将在页面加载完成时解析(请参阅did-finish-load),并在页面加载失败时拒绝(请参阅did-fail-load)。
Same as webContents.loadURL(url[, options]).与webContents.loadURL(url[, options])相同。
The url
can be a remote address (e.g. http://
) or a path to a local HTML file using the file://
protocol.url
可以是远程地址(例如http://
),也可以是使用file://
协议的本地HTML文件的路径。
To ensure that file URLs are properly formatted, it is recommended to use Node's url.format method:为了确保文件URL的格式正确,建议使用Node的url.format方法:
const url = require('url').format({
protocol: 'file',
slashes: true,
pathname: require('path').join(__dirname, 'index.html')
})
win.loadURL(url)
You can load a URL using a 您可以通过执行以下操作,使用带有URL编码数据的POST
request with URL-encoded data by doing the following:POST
请求加载URL:
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
string
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).promise将在页面加载完成时解析(请参阅did-finish-load),并在页面加载失败时拒绝(请参阅did-fail-load)。
Same as 与webContents.loadFile
, filePath
should be a path to an HTML file relative to the root of your application. webContents.loadFile
相同,filePath
应该是相对于应用程序根的HTML文件的路径。See the 有关详细信息,请参阅webContents
docs for more information.webContents
文档。
win.reload()
Same as 与webContents.reload
.webContents.reload
相同。
win.setMenu(menu)
Linux Windows
menu
Menu | null
Sets the 将menu
as the window's menu bar.menu
设置为窗口的菜单栏。
win.removeMenu()
Linux Windows
Remove the window's menu bar.删除窗口的菜单栏。
win.setProgressBar(progress[, options])
progress
Double
Sets progress value in progress bar. 在进度条中设置进度值。Valid range is [0, 1.0].有效范围为[0, 1.0]
。
Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1.当进度<0时删除进度条;当进度>1时,更改为不确定模式。
On Linux platform, only supports Unity desktop environment, you need to specify the 在Linux平台上,仅支持Unity桌面环境,您需要在*.desktop
file name to desktopName
field in package.json
. package.json
中指定*.desktop
文件名到desktopName
字段。By default, it will assume 默认情况下,它将采用{app.name}.desktop
.{app.name}.desktop
。
On Windows, a mode can be passed. 在Windows上,可以传递模式。Accepted values are 被接受的值是none
, normal
, indeterminate
, error
, and paused
. none
、normal
、indeterminate
、error
和paused
。If you call 如果您在没有模式设置的情况下调用setProgressBar
without a mode set (but with a value within the valid range), normal
will be assumed.setProgressBar
(但值在有效范围内),则会假定为normal
。
win.setOverlayIcon(overlay, description)
Windows
overlay
NativeImage | null -the icon to display on the bottom right corner of the taskbar icon.要显示在任务栏图标右下角的图标。If this parameter is如果此参数为null
, the overlay is clearednull
,则清除覆盖description
string -a description that will be provided to Accessibility screen readers将提供给辅助功能屏幕阅读器的说明
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.在当前任务栏图标上设置一个16 x 16像素的覆盖,通常用于传达某种应用程序状态或被动通知用户。
win.setHasShadow(hasShadow)
hasShadow
boolean
Sets whether the window should have a shadow.设置窗口是否应该有阴影。
win.hasShadow()
Returns 返回boolean
- Whether the window has a shadow.窗口是否有阴影。
win.setOpacity(opacity)
Windows macOS
opacity
number -between 0.0 (fully transparent) and 1.0 (fully opaque)介于0.0(完全透明)和1.0(完全不透明)之间
Sets the opacity of the window. 设置窗口的不透明度。On Linux, does nothing. 在Linux上,什么都不做。Out of bound number values are clamped to the [0, 1] range.超出界限的数值被限制在[0, 1]
范围内。
win.getOpacity()
Returns 返回number
- between 0.0 (fully transparent) and 1.0 (fully opaque). 介于0.0(完全透明)和1.0(完全不透明)之间。On Linux, always returns 1.在Linux上,总是返回1。
win.setShape(rects)
Windows Linux Experimental
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
buttons
ThumbarButton[]
Returns 返回boolean
- Whether the buttons were added successfully按钮添加是否成功
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.boolean
对象,指示缩略图是否已成功添加。
The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. 由于空间有限,缩略图工具栏中的按钮数量不应超过7个。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.但是您可以用一个空数组调用API来清理按钮。
The buttons
is an array of Button
objects:buttons
是Button
对象的数组:
Button
Objecticon
NativeImage -The icon showing in thumbnail toolbar.缩略图工具栏中显示的图标。click
Functiontooltip
string (optional) -The text of the button's tooltip.按钮工具提示的文本。flags
string[] (optional) -Control specific states and behaviors of the button.控制按钮的特定状态和行为。By default, it is默认情况下,它是['enabled']
.['enabled']
。
The flags
is an array that can include following string
s:flags
是一个数组,可以包括以下string
:
enabled
-The button is active and available to the user.该按钮处于活动状态,用户可以使用。disabled
-The button is disabled.该按钮已禁用。It is present, but has a visual state indicating it will not respond to user action.它存在,但具有一个视觉状态,指示它不会对用户操作做出响应。dismissonclick
-When the button is clicked, the thumbnail window closes immediately.单击该按钮后,缩略图窗口将立即关闭。nobackground
-Do not draw a button border, use only the image.不要绘制按钮边框,只使用图像。hidden
-The button is not shown to the user.该按钮不会显示给用户。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
region
Rectangle -Region of the window窗口的区域
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 }
.{ x: 0, y: 0, width: 0, height: 0 }
。
win.setThumbnailToolTip(toolTip)
Windows
toolTip
string
Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar.设置将鼠标悬停在任务栏中的窗口缩略图上时显示的工具提示。
win.setAppDetails(options)
Windows
Sets the properties for the window's taskbar button.设置窗口任务栏按钮的属性。
Note: relaunchCommand
and relaunchDisplayName
must always be set together. relaunchCommand
和relaunchDisplayName
必须始终设置在一起。If one of those properties is not set, then neither will be used.如果未设置其中一个属性,则不会使用这两个属性。
win.showDefinitionForSelection()
macOS
Same as 与webContents.showDefinitionForSelection()
.webContents.showDefinitionForSelection()
相同。
win.setIcon(icon)
Windows Linux
icon
NativeImage | string
Changes window icon.更改窗口图标。
win.setWindowButtonVisibility(visible)
macOS
visible
boolean
Sets whether the window traffic light buttons should be visible.设置车窗红绿灯按钮是否可见。
win.setAutoHideMenuBar(hide)
Windows Linux
hide
boolean
Sets whether the window menu bar should hide itself automatically. 设置窗口菜单栏是否应自动隐藏。Once set the menu bar will only show when users press the single 设置后,菜单栏将仅在用户按下单个Alt键时显示。Alt
key.
If the menu bar is already visible, calling 如果菜单栏已经可见,则调用setAutoHideMenuBar(true)
won't hide it immediately.setAutoHideMenuBar(true)
不会立即隐藏它。
win.isMenuBarAutoHide()
Windows Linux
Returns 返回boolean
- Whether menu bar automatically hides itself.菜单栏是否自动隐藏。
win.setMenuBarVisibility(visible)
Windows Linux
visible
boolean
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键来打开菜单栏。Alt
key.
win.isMenuBarVisible()
Windows Linux
Returns 返回boolean
- Whether the menu bar is visible.菜单栏是否可见。
win.setVisibleOnAllWorkspaces(visible[, options])
macOS Linux
visible
boolean
Sets whether the window should be visible on all workspaces.设置窗口是否应在所有工作空间上可见。
Note: This API does nothing on Windows.此API在Windows上不起任何作用。
win.isVisibleOnAllWorkspaces()
macOS Linux
Returns 返回boolean
- Whether the window is visible on all workspaces.该窗口在所有工作空间上是否可见。
Note: This API always returns false on Windows.此API在Windows上总是返回false
。
win.setIgnoreMouseEvents(ignore[, options])
ignore
boolean
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
boolean
Prevents the window contents from being captured by other apps.防止窗口内容被其他应用程序捕获。
On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. 在macOS上,它将NSWindow的sharingType
设置为NSWindowSharingNone
。On Windows it calls SetWindowDisplayAffinity with 在Windows上,它使用WDA_EXCLUDEFROMCAPTURE
. WDA_EXCLUDEFROMCAPTURE
调用SetWindowDisplayAffinity。For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if 对于Windows 10 2004版及以上版本,窗口将完全从捕获中删除,较旧的Windows版本的行为就像WDA_MONITOR
is applied capturing a black window.WDA_MONITOR
应用于捕获黑窗口一样。
win.setFocusable(focusable)
macOS Windows
focusable
boolean
Changes whether the window can be focused.更改窗口是否可以聚焦。
On macOS it does not remove the focus from the window.在macOS上,它不会从窗口中移除焦点。
win.isFocusable()
macOS Windows
Returns whether the window can be focused.返回窗口是否可以聚焦。
win.setParentWindow(parent)
parent
BrowserWindow | null
Sets 将parent
as current window's parent window, passing null
will turn current window into a top-level window.parent
设置为当前窗口的父窗口,传递null
将使当前窗口变成顶级窗口。
win.getParentWindow()
Returns 返回BrowserWindow | null
- The parent window or 父窗口,如果没有父窗口,则为null
if there is no parent.null
。
win.getChildWindows()
Returns 返回BrowserWindow[]
- All child windows.所有子窗口。
win.setAutoHideCursor(autoHide)
macOS
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.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
string | null -Can be可以是appearance-based
,light
,dark
,titlebar
,selection
,menu
,popover
,sidebar
,medium-light
,ultra-dark
,header
,sheet
,window
,hud
,fullscreen-ui
,tooltip
,content
,under-window
, orunder-page
.appearance-based
、light
、dark
、titlebar
、selection
、menu
、popover
、sidebar
、medium-light
、ultra-dark
、header
、sheet
、window
、hud
、fullscreen-ui
、tooltip
、content
、under-window
或under-page
。See the macOS documentation for more details.请参阅macOS文档以了解详情。
Adds a vibrancy effect to the browser window. 为浏览器窗口添加活力效果。Passing 传递null
or an empty string will remove the vibrancy effect on the window.null
或空字符串将删除窗口上的活力效果。
Note that 请注意,appearance-based
, light
, dark
, medium-light
, and ultra-dark
have been deprecated and will be removed in an upcoming version of macOS.appearance-based
、light
、dark
、medium-light
和ultra-dark
已被弃用,并将在即将推出的macOS版本中删除。
win.setTrafficLightPosition(position)
macOS
position
Point
Set a custom position for the traffic light buttons in frameless window.为无框车窗中的红绿灯按钮设置自定义位置。
win.getTrafficLightPosition()
macOS
Returns 返回Point
- The custom position for the traffic light buttons in frameless window.无框窗口中红绿灯按钮的自定义位置。
win.setTouchBar(touchBar)
macOS
touchBar
TouchBar | null
Sets the touchBar layout for the current window. 设置当前窗口的触摸条布局。Specifying 指定null
or undefined
clears the touch bar. null
或undefined
将清除触摸条。This method only has an effect if the machine has a touch bar and is running on macOS 10.12.1+.只有当机器有触摸条并且在macOS 10.12.1+上运行时,此方法才会生效。
Note: The TouchBar API is currently experimental and may change or be removed in future Electron releases.TouchBar API目前处于实验阶段,可能会在未来的Electron版本中更改或删除。
win.setBrowserView(browserView)
Experimental
browserView
BrowserView | null -Attach将browserView
towin
.browserView
附加到win
。If there are other如果附加了其他BrowserView
s attached, they will be removed from this window.BrowserView
,它们将从此窗口中删除。
win.getBrowserView()
Experimental
Returns 返回BrowserView | null
- The 将BrowserView
attached to win
. Returns null
if one is not attached. BrowserView
附加到win
。如果未附加,则返回null
。Throws an error if multiple 如果附加了多个BrowserView
s are attached.BrowserView
,则引发错误。
win.addBrowserView(browserView)
Experimental
browserView
BrowserView
Replacement API for setBrowserView supporting work with multi browser views.setBrowserView的替换API支持使用多浏览器视图。
win.removeBrowserView(browserView)
Experimental
browserView
BrowserView
win.setTopBrowserView(browserView)
Experimental
browserView
BrowserView
Raises 将browserView
above other BrowserView
s attached to win
. browserView
提升到其他附加到win
的BrowserView
之上。Throws an error if 如果未把browserView
is not attached to win
.browserView
附加到win
,则抛出错误。
win.getBrowserViews()
Experimental
Returns 返回BrowserView[]
- an array of all BrowserViews that have been attached with 已使用addBrowserView
or setBrowserView
.addBrowserView
或setBrowserView
附加的所有BrowserView
的数组。
Note: The BrowserView API is currently experimental and may change or be removed in future Electron releases.BrowserView API目前处于实验阶段,可能会在未来的Electron版本中更改或删除。
win.setTitleBarOverlay(options)
Windows
On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay.在已启用“窗口控件覆盖”的窗口上,此方法会更新标题栏覆盖的样式。