BrowserWindow
创建和控制浏览器窗口。
进程:主进程
// 在主进程中.
const { BrowserWindow } = require('electron')
// 或者从渲染进程中使用 `remote`.
// const { BrowserWindow } = require('electron').remote
let win = new BrowserWindow({ width: 800, height: 600 })
win.on('closed', () => {
win = null
})
// 加载远程URL
win.loadURL('https://github.com')
// 或加载本地HTML文件
win.loadURL(`file://${__dirname}/app/index.html`)
Create and control browser windows.
Process: Main
// In the main process.
const { BrowserWindow } = require('electron')
// Or use `remote` from the renderer process.
// const { BrowserWindow } = require('electron').remote
let win = new BrowserWindow({ width: 800, height: 600 })
win.on('closed', () => {
win = null
})
// Load a remote URL
win.loadURL('https://github.com')
// Or load a local HTML file
win.loadURL(`file://${__dirname}/app/index.html`)
无边框窗口
如果想创建一个无边框或者任意形状的视图,可以使用Frameless Window 的API
Frameless window
To create a window without chrome, or a transparent window in arbitrary shape, you can use the Frameless Window API.
优雅地显示窗口
当页面在窗口中直接加载时,用户会看到未完成的页面,这不是一个好的原生应用的体验。为了让画面准备好了再显示,这有两种不同的解决方案。
Showing 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 visual flash, there are two solutions for different situations.
使用ready-to-show
事件
在加载页面时,渲染进程第一次完成绘制时,会发出 ready-to-show
事件 。 在此事件后显示窗口将没有视觉闪烁:
const { BrowserWindow } = require('electron')
let win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => {
win.show()
})
这个事件通常在 did-finish-load
事件之后发出,但是页面有许多远程资源时,它可能会在 did-finish-load
之前发出事件。
Using ready-to-show
event
While loading the page, the ready-to-show
event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash:
const { BrowserWindow } = require('electron')
let 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.
设置 backgroundColor
对于一个复杂的应用,ready-to-show
可能发出的太晚,会让应用感觉缓慢。 在这种情况下,建议立刻显示窗口,并使用接近应用程序背景的 backgroundColor
const { BrowserWindow } = require('electron')
let win = new BrowserWindow({ backgroundColor: '#2e2c29' })
win.loadURL('https://github.com')
请注意,即使是使用 ready-to-show
事件的应用程序,仍建议使用设置 backgroundColor
使应用程序感觉更原生。
Setting backgroundColor
For a complex app, the ready-to-show
event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a backgroundColor
close to your app's background:
const { BrowserWindow } = require('electron')
let 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 app feel more native.
父子窗口
通过使用 parent
选项,你可以创建子窗口:
const { BrowserWindow } = require('electron')
let top = new BrowserWindow()
let child = new BrowserWindow({ parent: top })
child.show()
top.show()
child
窗口将总是显示在 top
窗口的顶部.
Parent and child windows
By using parent
option, you can create child windows:
const { BrowserWindow } = require('electron')
let top = new BrowserWindow()
let child = new BrowserWindow({ parent: top })
child.show()
top.show()
The child
window will always show on top of the top
window.
模态窗口
模态窗口是禁用父窗口的子窗口,创建模态窗口必须设置 parent
和 modal
选项:
const { BrowserWindow } = require('electron')
let child = new BrowserWindow({ parent: top, modal: true, show: false })
child.loadURL('https://github.com')
child.once('ready-to-show', () => {
child.show()
})
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:
const { BrowserWindow } = require('electron')
let 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
时暂停消耗资源的操作以便减少电力消耗。
Page visibility
The Page Visibility API works as follows:
- 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. If the window is occluded (i.e. fully covered) by another window, the visibility state will be
hidden
. On other platforms, the visibility state will behidden
only when the window is minimized or explicitly hidden withwin.hide()
. - If a
BrowserWindow
is created withshow: false
, the initial visibility state will bevisible
despite the window actually being hidden. - If
backgroundThrottling
is disabled, the visibility state will remainvisible
even if the window is minimized, occluded, or hidden.
It is recommended that you pause expensive operations when the visibility state is hidden
in order to minimize power consumption.
平台相关的提示
- 在 macOS 上,modal 窗口将显示为附加到父窗口的工作表。
- 在 macOS 上,子窗口将保持与父窗口的相对位置。而在 Windows 和 Linux 中,当父窗口移动时子窗口不会移动。
- 在Linux上,模态窗口的类型将更改为
dialog
. - 在Linux上,许多桌面环境不支持隐藏模态窗口。
Platform notices
- On macOS modal windows will be displayed as sheets attached to the parent window.
- 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.
- On Linux the type of modal windows will be changed to
dialog
. - On Linux many desktop environments do not support hiding a modal window.
Class: BrowserWindow
创建和控制浏览器窗口。
进程:主进程
BrowserWindow
是一个EventEmitter.
通过 options
可以创建一个具有原生属性的 BrowserWindow
。
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
.
new BrowserWindow([options])
选项
Object (可选)width
Integer (可选) - 窗口的宽度,单位为像素。默认为800
.height
Integer(可选) - 窗口的高度,单位为像素。默认为600
.x
Integer (可选) (如果 y 存在时必填) - 窗口相对于屏幕左侧的偏移位置. 默认居中.y
Integer (可选) (如果 x 存在时必填) - 窗口相对于屏幕顶部的偏移位置. 默认居中.useContentSize
Boolean (可选) -width
和height
将设置为 web 页面的尺寸(译注: 不包含边框), 这意味着窗口的实际尺寸将包括窗口边框的大小,稍微会大一点。 默认值为false
.center
Boolean (可选) - 窗口在屏幕居中.minWidth
Integer (可选) - 窗口的最小宽度, 默认值为0
.minHeight
Integer (可选) - 窗口的最小高度. 默认值为0
.maxWidth
Integer (可选) - 窗口的最大宽度, 默认无限制.maxHeight
Integer (可选) - 窗口的最大高度, 默认无限制.resizable
Boolean (可选) - 窗口是否可以改变尺寸. 默认值为true
.movable
Boolean (可选) - 窗口是否可以移动. 在 Linux 中无效. 默认值为true
.minimizable
Boolean (可选) - 窗口是否可以最小化. 在 Linux 中无效. 默认值为true
.maximizable
Boolean (可选) - 窗口是否可以最大化动. 在 Linux 中无效. 默认值为true
.closable
Boolean (可选) - 窗口是否可以关闭. 在 Linux 中无效. 默认值为true
.focusable
Boolean (可选) - 窗口是否可以聚焦. 默认值为true
。 在 Windows 中设置focusable: false
也意味着设置了skipTaskbar: true
. 在 Linux 中设置focusable: false
时窗口停止与 wm 交互, 并且窗口将始终置顶。alwaysOnTop
Boolean (可选) -窗口是否永远在别的窗口的上面. 默认值为false
.fullscreen
Boolean (可选) - 窗口是否全屏. 当明确设置为false
时,在 macOS 上全屏的按钮将被隐藏或禁用. 默认值为false
.fullscreenable
Boolean (可选) - 窗口是否可以进入全屏状态. 在 macOS上, 最大化/缩放按钮是否可用 默认值为true
。simpleFullscreen
Boolean (可选) - 在 macOS 上使用 pre-Lion 全屏. 默认为false
.skipTaskbar
Boolean (可选) - 是否在任务栏中显示窗口. 默认值为false
.kiosk
Boolean (可选) - kiosk 模式. 默认值为false
.title
String(可选) - 默认窗口标题 默认为"Electron"
。 如果由loadURL()
加载的HTML文件中含有标签<title>
,此属性将被忽略。icon
(NativeImage | String) (可选) - 窗口的图标. 在 Windows 上推荐使用ICO
图标来获得最佳的视觉效果, 默认使用可执行文件的图标.show
Boolean (可选) - 窗口创建的时候是否显示. 默认值为true
.frame
Boolean (可选) - 设置为false
时可以创建一个Frameless Window. 默认值为true
.parent
BrowserWindow (可选) - 指定父窗口. 默认值为null
.modal
Boolean (可选) -是否为模态窗. 仅供子窗口使用. 默认值为false
.acceptFirstMouse
Boolean (可选) - 是否允许单击页面来激活窗口. 默认值为false
.disableAutoHideCursor
Boolean (可选) - 是否在输入时隐藏鼠标. 默认值为false
.autoHideMenuBar
Boolean (可选) - 自动隐藏菜单栏, 除非按了Alt
键. 默认值为false
.enableLargerThanScreen
Boolean (可选) - 是否允许改变窗口的大小时, 大于屏幕的尺寸. 默认值为false
.backgroundColor
String(可选) - 窗口的背景颜色为十六进制值,例如#66CD00
,#FFF
,#80FFFFFF
(设置transparent
为true
方可支持alpha属性,格式为#AARRGGBB)。 默认值为#FFF
(白色)。hasShadow
Boolean (可选) - 窗口是否有阴影. 仅在 macOS 上支持. 默认值为true
.opacity
Number (可选)-设置窗口初始的不透明度, 介于 0.0 (完全透明) 和 1.0 (完全不透明) 之间。仅支持 Windows 和 macOS 。darkTheme
Boolean (可选) - 强制窗口使用 dark 主题, 只在一些拥有 GTK+3 桌面环境上有效. 默认值为false
.transparent
Boolean (可选) - 使窗口 透明. 默认值为false
.type
String (可选) - 窗口的类型, 默认为普通窗口. 下面可以查看更多.titleBarStyle
String (可选) - 窗口标题栏的样式. 默认值为default
. 可能的值有:default
- 标准灰色不透明的Mac标题栏hidden
- 隐藏标题栏, 内容充满整个窗口, 但它依然在左上角, 仍然受标准窗口控制.hiddenInset
- 隐藏标题栏, 显示小的控制按钮在窗口边缘customButtonsOnHover
Boolean (可选) - 在macOS的无框窗口上绘制自定义的关闭与最小化按钮. 除非鼠标悬停到窗口的左上角, 否则这些按钮不会显示出来. 这些自定义的按钮能防止, 与发生于标准的窗口工具栏按钮处的鼠标事件相关的问题. 注意: 此选项目前是实验性的。
fullscreenWindowTitle
Boolean (可选) - 在 macOS 全屏模式时,为所有带titleBarStyle
选项的标题栏显示标题。默认值为false
。thickFrame
Boolean(可选)-对 Windows 上的无框窗口使用WS_THICKFRAME
样式,会增加标准窗口框架。 设置为false
时将移除窗口的阴影和动画. 默认值为true
。vibrancy
String (可选) - 窗口是否使用 vibrancy 动态效果, 仅 macOS 中有效. 可以为appearance-based
,light
,dark
,titlebar
,selection
,menu
,popover
,sidebar
,medium-light
或ultra-dark
. 请注意,结合一个 vibrancy 值使用frame: false
,需要确保titleBarStyle
为一个非默认值。zoomToPageWidth
Boolean (可选) - 单击工具栏上的绿色信号灯按钮或单击 窗口>缩放 菜单项时的行为, 仅macOS中有效. 如果为true
, 窗口将放大到网页的本身宽度,false
将使其缩放到屏幕的宽度。 这也会影响直接调用maximize()
时的行为。 默认值为false
.tabbingIdentifier
String (可选) - 选项组卡的名称,在macOS 10.12+上可使窗口在原生选项卡中打开. 具有相同标识符的窗口将被组合在一起。 这还会在窗口的标签栏中添加一个原生的新选项卡按钮, 并允许app
和窗口接收new-window-for-tab
事件。webPreferences
Object (可选) - 网页功能的设置devTools
Boolean (可选) - 是否开启 DevTools. 如果设置为false
, 则无法使用BrowserWindow.webContents.openDevTools ()
打开 DevTools。 默认值为true
。nodeIntegration
Boolean (可选) - 是否集成Node,默认为false
。nodeIntegrationInWorker
Boolean (可选) - 是否在Web工作器中启用了Node集成. 默认值为false
. 更多内容参见 多线程.nodeIntegrationInSubFrames
Boolean (optional) - Experimental option for enabling Node.js support in sub-frames such as iframes and child windows. All your preloads will load for every iframe, you can useprocess.isMainFrame
to determine if you are in the main frame or not.preload
String (可选) -在页面运行其他脚本之前预先加载指定的脚本 无论页面是否集成Node, 此脚本都可以访问所有Node API 脚本路径为文件的绝对路径。 当 node integration 关闭时, 预加载的脚本将从全局范围重新引入node的全局引用标志 参考示例.sandbox
Boolean (可选)-如果设置该参数, 沙箱的渲染器将与窗口关联, 使它与Chromium OS-level 的沙箱兼容, 并禁用 Node. js 引擎。 它与nodeIntegration
的选项不同,且预加载脚本的 API 也有限制. 更多详情. 注意:改选项目前是为实验性质,可能会在 Electron 未来的版本中移除。enableRemoteModule
Boolean(可选)- 是否启用Remote
模块。 默认值为true
。session
Session (可选) - 设置页面的 session 而不是直接忽略 Session 对象, 也可用partition
选项来代替,它接受一个 partition 字符串. 同时设置了session
和partition
时,session
的优先级更高. 默认使用默认的 session.partition
String (optional) - 通过 session 的 partition 字符串来设置界面session. 如果partition
以persist:
开头, 该页面将使用持续的 session,并在所有页面生效,且使用同一个partition
. 如果没有persist:
前缀, 页面将使用 in-memory session. 通过分配相同的partition
, 多个页可以共享同一会话。 默认使用默认的 session.affinity
String (可选) - 当指定,具有相同affinity
的 web页面将在相同的渲染进程运行。 需要注意的是,由于渲染过程中会有代码重用,如webPreferences
的preload
,sandbox
和nodeIntegration
等选项会在不同页面之间共用,即使你已经在不同页面中为同一选项设置过不同的值,它们仍会被共用。 因此,建议为affinity
相同的页面,使用相同的webPreferences
这一选项当前是实验性的zoomFactor
Number (可选) - 页面的默认缩放系数,3.0
表示300%
. 默认值为1.0
.javascript
Boolean (可选) - 是否启用 JavaScript 支持. 默认值为true
.webSecurity
Boolean (可选) - 当设置为false
, 它将禁用同源策略 (通常用来测试网站), 如果此选项不是由开发者设置的,还会把allowRunningInsecureContent
设置为true
. 默认值为true
。allowRunningInsecureContent
Boolean (可选) -允许一个 https 页面运行 http url 里的资源,包括 JavaScript, CSS 或 plugins. 默认值为false
.images
Boolean (可选) - 启动图像支持. 默认值为true
.textAreasAreResizable
Boolean (可选) - 让 TextArea 元素可以调整大小. 默认值为true
.webgl
Boolean (可选) - 启用 WebGL 支持. 默认值为true
.plugins
Boolean (可选) - 是否支持插件. 默认值为false
.experimentalFeatures
Boolean (optional) - 启用 Chromium 的实验功能. 默认值为false
.scrollBounce
Boolean (可选) - 在 macOS 启用弹力动画 (橡皮筋) 效果. 默认值为false
.enableBlinkFeatures
String(可选) - 以逗号
分隔的需要启用的特性列表,譬如CSSVariables,KeyboardEventKey
在 RuntimeEnabledFeatures.json5文件中查看被支持的所有特性.disableBlinkFeatures
String (可选) - 以,
分隔的禁用特性列表, 如CSSVariables,KeyboardEventKey
. 在RuntimeEnabledFeatures.json5 文件中查看被支持的所有特性.defaultFontFamily
Object (可选) - 设置 font-family 的默认字体.standard
String (可选) - 默认值为Times New Roman
.serif
String (可选) - 默认值为Times New Roman
.sansSerif
String (可选) - 默认值为Arial
.monospace
String (可选) - 默认值为Courier New
.cursive
String (可选) - 默认值为Script
.fantasy
String (可选) - 默认值为Impact
.
defaultFontSize
Integer (可选) - 默认值为16
.defaultMonospaceFontSize
Integer (可选) - 默认值为13
.minimumFontSize
Integer (可选) - 默认值为0
.defaultEncoding
String (可选) - 默认值为ISO-8859-1
.backgroundThrottling
Boolean (可选)-是否在页面成为背景时限制动画和计时器。 这也会影响到 Page Visibility API. 默认值为true
。offscreen
Boolean (optional) - 是否绘制和渲染可视区域外的窗口. 默认值为false
. 更多详情, 请参见 offscreen rendering tutorial 。contextIsolation
Boolean (可选) - 是否在独立 JavaScript 环境中运行 Electron API和指定的preload
脚本. 默认值为false
.preload
脚本的运行环境仍然可以访问document
和window
全局变量,但它将使用自己内置的函数 (如Array
,Object
,JSON
等),并且将被加载的页面与对全局环境所做的任何更改隔离开来. Electron API 仅在preload
脚本中有效,而不是加载的页面。 在加载可能不受信任的远程内容时, 应使用此选项, 以确保加载的内容不能篡改preload
脚本和使用的 Electron APIs。 此选项使用 Chrome Content Scripts 使用的相同技术。 通过在控制台选项卡顶部的组合框中选择 "Electron Isolated Context" 条目, 可以在开发工具中访问此上下文。nativeWindowOpen
Boolean (可选) - 是否使用原生的window.open()
. 默认值为false
. Child windows will always have node integration disabled unlessnodeIntegrationInSubFrames
is true. 注意: 此选项目前是实验性的。webviewTag
Boolean (可选) - 是否启用<webview>
tag标签. 默认值为false
. 注意: 为< webview>
配置的preload
脚本在执行时将启用节点集成, 因此应确保远程或不受信任的内容无法创建恶意的preload
脚本 。 可以使用 webContents 上的will-attach-webview
事件对preload
脚本进行剥离, 并验证或更改<webview>
的初始设置。additionalArguments
String[] (可选) - 一系列将会被附加至此app的渲染进程的process.argv
的字符串. 对于将少量数据向下传至渲染进程的预加载脚本而言是十分实用的.safeDialogs
Boolean (可选) - 是否启用浏览器样式的持续对话框保护。 缺省为false
。safeDialogsMessage
String (可选) - 当持续对话框保护被触发时显示的消息。 如果没有定义,那么将使用缺省的消息。注意:当前缺省消息是英文,并没有本地化。navigateOnDragDrop
Boolean (可选) - 将文件或链接拖放到页面上时是否触发页面跳转. 默认为false
.autoplayPolicy
String (optional) - Autoplay policy to apply to content in the window, can beno-user-gesture-required
,user-gesture-required
,document-user-activation-required
. Defaults tono-user-gesture-required
.disableHtmlFullscreenWindowResize
Boolean (optional) - Whether to prevent the window from resizing when entering HTML Fullscreen. Default isfalse
.
当使用 minWidth
/maxWidth
/minHeight
/maxHeight
设置最小或最大窗口大小时, 它只限制用户。 它不会阻止您将不符合大小限制的值传递给 setBounds
/setSize
或 BrowserWindow
的构造函数。
type
选项的可能值和行为与平台相关。可能的值为:
- 在 Linux 上, 可能的类型有
desktop
、dock
、toolbar
、splash
、notification
。 在 macOS, 可能的类型是
desktop
,textured
.textured
类型增加金属色泽的外观 (NSTexturedBackgroundWindowMask
).desktop
类型将窗口置于桌面背景级别 (kCGDesktopWindowLevel - 1
). 注意,桌面窗口不会接收焦点、键盘或鼠标事件,但您可以使用< 0> globalShortcut < /0 >接收快捷键的消息
- 在 Windows 上, 可能的类型为
toolbar
.
new BrowserWindow([options])
options
Object (optional)width
Integer (optional) - Window's width in pixels. Default is800
.height
Integer (optional) - Window's height in pixels. Default is600
.x
Integer (optional) (required if y is used) - Window's left offset from screen. Default is to center the window.y
Integer (optional) (required if x is used) - Window's top offset from screen. Default is to center the window.useContentSize
Boolean (optional) - Thewidth
andheight
would be used as web page's size, which means the actual window's size will include window frame's size and be slightly larger. Default isfalse
.center
Boolean (optional) - Show window in the center of the screen.minWidth
Integer (optional) - Window's minimum width. Default is0
.minHeight
Integer (optional) - Window's minimum height. Default is0
.maxWidth
Integer (optional) - Window's maximum width. Default is no limit.maxHeight
Integer (optional) - Window's maximum height. Default is no limit.resizable
Boolean (optional) - Whether window is resizable. Default istrue
.movable
Boolean (optional) - Whether window is movable. This is not implemented on Linux. Default istrue
.minimizable
Boolean (optional) - Whether window is minimizable. This is not implemented on Linux. Default istrue
.maximizable
Boolean (optional) - Whether window is maximizable. This is not implemented on Linux. Default istrue
.closable
Boolean (optional) - Whether window is closable. This is not implemented on Linux. Default istrue
.focusable
Boolean (optional) - Whether the window can be focused. Default istrue
. On Windows settingfocusable: false
also implies settingskipTaskbar: true
. On Linux settingfocusable: false
makes the window stop interacting with wm, so the window will always stay on top in all workspaces.alwaysOnTop
Boolean (optional) - Whether the window should always stay on top of other windows. Default isfalse
.fullscreen
Boolean (optional) - Whether the window should show in fullscreen. When explicitly set tofalse
the fullscreen button will be hidden or disabled on macOS. Default isfalse
.fullscreenable
Boolean (optional) - Whether the window can be put into fullscreen mode. On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. Default istrue
.simpleFullscreen
Boolean (optional) - Use pre-Lion fullscreen on macOS. Default isfalse
.skipTaskbar
Boolean (optional) - Whether to show the window in taskbar. Default isfalse
.kiosk
Boolean (optional) - The kiosk mode. Default isfalse
.title
String (optional) - Default window title. Default is"Electron"
. If the HTML tag<title>
is defined in the HTML file loaded byloadURL()
, this property will be ignored.icon
(NativeImage | String) (optional) - The window icon. On Windows it is recommended to useICO
icons to get best visual effects, you can also leave it undefined so the executable's icon will be used.show
Boolean (optional) - Whether window should be shown when created. Default istrue
.frame
Boolean (optional) - Specifyfalse
to create a Frameless Window. Default istrue
.parent
BrowserWindow (optional) - Specify parent window. Default isnull
.modal
Boolean (optional) - Whether this is a modal window. This only works when the window is a child window. Default isfalse
.acceptFirstMouse
Boolean (optional) - Whether the web view accepts a single mouse-down event that simultaneously activates the window. Default isfalse
.disableAutoHideCursor
Boolean (optional) - Whether to hide cursor when typing. Default isfalse
.autoHideMenuBar
Boolean (optional) - Auto hide the menu bar unless theAlt
key is pressed. Default isfalse
.enableLargerThanScreen
Boolean (optional) - Enable the window to be resized larger than screen. Default isfalse
.backgroundColor
String (optional) - Window's background color as a hexadecimal value, like#66CD00
or#FFF
or#80FFFFFF
(alpha in #AARRGGBB format is supported iftransparent
is set totrue
). Default is#FFF
(white).hasShadow
Boolean (optional) - Whether window should have a shadow. This is only implemented on macOS. Default istrue
.opacity
Number (optional) - Set the initial opacity of the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This is only implemented on Windows and macOS.darkTheme
Boolean (optional) - Forces using dark theme for the window, only works on some GTK+3 desktop environments. Default isfalse
.transparent
Boolean (optional) - Makes the window transparent. Default isfalse
.type
String (optional) - The type of window, default is normal window. See more about this below.titleBarStyle
String (optional) - The style of window title bar. Default isdefault
. Possible values are:default
- Results in the standard gray opaque Mac title bar.hidden
- Results in a hidden title bar and a full size content window, yet the title bar still has the standard window controls ("traffic lights") in the top left.hiddenInset
- Results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge.customButtonsOnHover
Boolean (optional) - Draw custom close, and minimize buttons on macOS frameless windows. These buttons will not display unless hovered over in the top left of the window. These custom buttons prevent issues with mouse events that occur with the standard window toolbar buttons. Note: This option is currently experimental.
fullscreenWindowTitle
Boolean (optional) - Shows the title in the title bar in full screen mode on macOS for alltitleBarStyle
options. Default isfalse
.thickFrame
Boolean (optional) - UseWS_THICKFRAME
style for frameless windows on Windows, which adds standard window frame. Setting it tofalse
will remove window shadow and window animations. Default istrue
.vibrancy
String (optional) - Add a type of vibrancy effect to the window, only on macOS. Can beappearance-based
,light
,dark
,titlebar
,selection
,menu
,popover
,sidebar
,medium-light
orultra-dark
. Please note that usingframe: false
in combination with a vibrancy value requires that you use a non-defaulttitleBarStyle
as well.zoomToPageWidth
Boolean (optional) - Controls the behavior on macOS when option-clicking the green stoplight button on the toolbar or by clicking the Window > Zoom menu item. Iftrue
, the window will grow to the preferred width of the web page when zoomed,false
will cause it to zoom to the width of the screen. This will also affect the behavior when callingmaximize()
directly. Default isfalse
.tabbingIdentifier
String (optional) - Tab group name, allows opening the window as a native tab on macOS 10.12+. Windows with the same tabbing identifier will be grouped together. This also adds a native new tab button to your window's tab bar and allows yourapp
and window to receive thenew-window-for-tab
event.webPreferences
Object (optional) - Settings of web page's features.devTools
Boolean (optional) - Whether to enable DevTools. If it is set tofalse
, can not useBrowserWindow.webContents.openDevTools()
to open DevTools. Default istrue
.nodeIntegration
Boolean (optional) - Whether node integration is enabled. Default isfalse
.nodeIntegrationInWorker
Boolean (optional) - Whether node integration is enabled in web workers. Default isfalse
. More about this can be found in Multithreading.nodeIntegrationInSubFrames
Boolean (optional) - Experimental option for enabling Node.js support in sub-frames such as iframes and child windows. All your preloads will load for every iframe, you can useprocess.isMainFrame
to determine if you are in the main frame or not.preload
String (optional) - Specifies a script that will be loaded before other scripts run in the page. This script will always have access to node APIs no matter whether node integration is turned on or off. The value should be the absolute file path to the script. When node integration is turned off, the preload script can reintroduce Node global symbols back to the global scope. See example here.sandbox
Boolean (optional) - If set, this will sandbox the renderer associated with the window, making it compatible with the Chromium OS-level sandbox and disabling the Node.js engine. This is not the same as thenodeIntegration
option and the APIs available to the preload script are more limited. Read more about the option here. Note: This option is currently experimental and may change or be removed in future Electron releases.enableRemoteModule
Boolean (optional) - Whether to enable theremote
module. Default istrue
.session
Session (optional) - Sets the session used by the page. Instead of passing the Session object directly, you can also choose to use thepartition
option instead, which accepts a partition string. When bothsession
andpartition
are provided,session
will be preferred. Default is the default session.partition
String (optional) - Sets the session used by the page according to the session's partition string. Ifpartition
starts withpersist:
, the page will use a persistent session available to all pages in the app with the samepartition
. If there is nopersist:
prefix, the page will use an in-memory session. By assigning the samepartition
, multiple pages can share the same session. Default is the default session.affinity
String (optional) - When specified, web pages with the sameaffinity
will run in the same renderer process. Note that due to reusing the renderer process, certainwebPreferences
options will also be shared between the web pages even when you specified different values for them, including but not limited topreload
,sandbox
andnodeIntegration
. So it is suggested to use exact samewebPreferences
for web pages with the sameaffinity
. This property is experimentalzoomFactor
Number (optional) - The default zoom factor of the page,3.0
represents300%
. Default is1.0
.javascript
Boolean (optional) - Enables JavaScript support. Default istrue
.webSecurity
Boolean (optional) - Whenfalse
, it will disable the same-origin policy (usually using testing websites by people), and setallowRunningInsecureContent
totrue
if this options has not been set by user. Default istrue
.allowRunningInsecureContent
Boolean (optional) - Allow an https page to run JavaScript, CSS or plugins from http URLs. Default isfalse
.images
Boolean (optional) - Enables image support. Default istrue
.textAreasAreResizable
Boolean (optional) - Make TextArea elements resizable. Default istrue
.webgl
Boolean (optional) - Enables WebGL support. Default istrue
.plugins
Boolean (optional) - Whether plugins should be enabled. Default isfalse
.experimentalFeatures
Boolean (optional) - Enables Chromium's experimental features. Default isfalse
.scrollBounce
Boolean (optional) - Enables scroll bounce (rubber banding) effect on macOS. Default isfalse
.enableBlinkFeatures
String (optional) - A list of feature strings separated by,
, likeCSSVariables,KeyboardEventKey
to enable. The full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.disableBlinkFeatures
String (optional) - A list of feature strings separated by,
, likeCSSVariables,KeyboardEventKey
to disable. The full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.defaultFontFamily
Object (optional) - Sets the default font for the font-family.standard
String (optional) - Defaults toTimes New Roman
.serif
String (optional) - Defaults toTimes New Roman
.sansSerif
String (optional) - Defaults toArial
.monospace
String (optional) - Defaults toCourier New
.cursive
String (optional) - Defaults toScript
.fantasy
String (optional) - Defaults toImpact
.
defaultFontSize
Integer (optional) - Defaults to16
.defaultMonospaceFontSize
Integer (optional) - Defaults to13
.minimumFontSize
Integer (optional) - Defaults to0
.defaultEncoding
String (optional) - Defaults toISO-8859-1
.backgroundThrottling
Boolean (optional) - Whether to throttle animations and timers when the page becomes background. This also affects the Page Visibility API. Defaults totrue
.offscreen
Boolean (optional) - Whether to enable offscreen rendering for the browser window. Defaults tofalse
. See the offscreen rendering tutorial for more details.contextIsolation
Boolean (optional) - Whether to run Electron APIs and the specifiedpreload
script in a separate JavaScript context. Defaults tofalse
. The context that thepreload
script runs in will still have full access to thedocument
andwindow
globals but it will use its own set of JavaScript builtins (Array
,Object
,JSON
, etc.) and will be isolated from any changes made to the global environment by the loaded page. The Electron API will only be available in thepreload
script and not the loaded page. This option should be used when loading potentially untrusted remote content to ensure the loaded content cannot tamper with thepreload
script and any Electron APIs being used. This option uses the same technique used by Chrome Content Scripts. You can access this context in the dev tools by selecting the 'Electron Isolated Context' entry in the combo box at the top of the Console tab.nativeWindowOpen
Boolean (optional) - Whether to use nativewindow.open()
. Defaults tofalse
. Child windows will always have node integration disabled unlessnodeIntegrationInSubFrames
is true. Note: This option is currently experimental.webviewTag
Boolean (optional) - Whether to enable the<webview>
tag. Defaults tofalse
. Note: Thepreload
script configured for the<webview>
will have node integration enabled when it is executed so you should ensure remote/untrusted content is not able to create a<webview>
tag with a possibly maliciouspreload
script. You can use thewill-attach-webview
event on webContents to strip away thepreload
script and to validate or alter the<webview>
's initial settings.additionalArguments
String - A list of strings that will be appended toprocess.argv
in the renderer process of this app. Useful for passing small bits of data down to renderer process preload scripts.safeDialogs
Boolean (optional) - Whether to enable browser style consecutive dialog protection. Default isfalse
.safeDialogsMessage
String (optional) - The message to display when consecutive dialog protection is triggered. If not defined the default message would be used, note that currently the default message is in English and not localized.navigateOnDragDrop
Boolean (optional) - Whether dragging and dropping a file or link onto the page causes a navigation. Default isfalse
.autoplayPolicy
String (optional) - Autoplay policy to apply to content in the window, can beno-user-gesture-required
,user-gesture-required
,document-user-activation-required
. Defaults tono-user-gesture-required
.disableHtmlFullscreenWindowResize
Boolean (optional) - Whether to prevent the window from resizing when entering HTML Fullscreen. Default isfalse
.
When setting minimum or maximum window size with minWidth
/maxWidth
/ minHeight
/maxHeight
, it only constrains the users. It won't prevent you from passing a size that does not follow size constraints to setBounds
/setSize
or to the constructor of BrowserWindow
.
The possible values and behaviors of the type
option are platform dependent. Possible values are:
- On Linux, possible types are
desktop
,dock
,toolbar
,splash
,notification
. On macOS, possible types are
desktop
,textured
.- The
textured
type adds metal gradient appearance (NSTexturedBackgroundWindowMask
). - The
desktop
type places the window at the desktop background window level (kCGDesktopWindowLevel - 1
). Note that desktop window will not receive focus, keyboard or mouse events, but you can useglobalShortcut
to receive input sparingly.
- The
- On Windows, possible type is
toolbar
.
实例事件
使用 new BrowserWindow
创建的对象具有以下属性:
注意: 某些事件仅在特定的操作系统上可用, 这些方法会被标记出来。
Instance Events
Objects created with new BrowserWindow
emit the following events:
Note: Some events are only available on specific operating systems and are labeled as such.
事件: 'page-title-updated'
返回:
event
Eventtitle
StringexplicitSet
Boolean
文档更改标题时触发,调用event.preventDefault()
将阻止更改标题 explicitSet
is false when title is synthesized from file url.
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. explicitSet
is false when title is synthesized from file url.
事件: 'close'
返回:
event
Event
在窗口要关闭的时候触发。 它在DOM 的beforeunload
和 unload
事件之前触发. 调用event.preventDefault()
将阻止这个操作。
通常你想通过 beforeunload
处理器来决定是否关闭窗口,但是它也会在窗口重载的时候触发. 在 Electron 里,返回除 undefined
之外的任何值都将取消关闭. 例如:
window.onbeforeunload = (e) => {
console.log('I do not want to be closed')
// 与通常的浏览器不同,会提示给用户一个消息框,
//返回非空值将默认取消关闭
//建议使用对话框 API 让用户确认关闭应用程序.
e.returnValue = false // 相当于 `return false` ,但是不推荐使用
}
*注意: window.onbeforeunload = handler
和 window.addEventListener('beforeunload', handler)
的行为有细微的区别。 推荐总是显式地设置 event.returnValue
, 而不是仅仅返回一个值, 因为前者在Electron中作用得更为一致.*
Event: 'close'
Returns:
event
Event
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.
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 // equivalent to `return false` but not recommended
}
Note: There is a subtle difference between the behaviors of window.onbeforeunload = handler
and window.addEventListener('beforeunload', handler)
. It is recommended to always set the event.returnValue
explicitly, instead of only returning a value, as the former works more consistently within Electron.
事件: 'closed'
窗口已经关闭时触发。当你接收到这个事件的时候, 你应当删除对已经关闭的窗口的引用对象和避免再次使用它.
Event: 'closed'
Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more.
事件: 'session-end' Windows
因为强制关机或机器重启或会话注销而导致窗口会话结束时触发
Event: 'session-end' Windows
Emitted when window session is going to end due to force shutdown or machine restart or session log off.
事件: 'unresponsive'
网页变得未响应时触发
Event: 'unresponsive'
Emitted when the web page becomes unresponsive.
事件: 'responsive'
未响应的页面变成响应时触发
Event: 'responsive'
Emitted when the unresponsive web page becomes responsive again.
事件: 'blur'
当窗口失去焦点时触发
Event: 'blur'
Emitted when the window loses focus.
事件: 'focus'
当窗口获得焦点时触发
Event: 'focus'
Emitted when the window gains focus.
事件: 'show'
当窗口显示时触发
Event: 'show'
Emitted when the window is shown.
事件: 'hide'
当窗口隐藏时触发
Event: 'hide'
Emitted when the window is hidden.
事件: 'ready-to-show'
当页面已经渲染完成(但是还没有显示) 并且窗口可以被显示时触发
Event: 'ready-to-show'
Emitted when the web page has been rendered (while not being shown) and window can be displayed without a visual flash.
事件: 'maximize'
窗口最大化时触发
Event: 'maximize'
Emitted when window is maximized.
事件: 'unmaximize'
当窗口从最大化状态退出时触发
Event: 'unmaximize'
Emitted when the window exits from a maximized state.
事件: 'minimize'
窗口最小化时触发
Event: 'minimize'
Emitted when the window is minimized.
事件: 'restore'
当窗口从最小化状态恢复时触发
Event: 'restore'
Emitted when the window is restored from a minimized state.
事件: 'will-resize' macOS Windows
返回:
event
EventnewBounds
Rectangle
- 将要调整到的窗口尺寸。
在调整窗口大小之前发出。调用event.preventDefault()
会阻止窗口大小被调整。
请注意,仅在手动调整窗口大小时才会发出此信息。使用setBounds
或 setSize
调整窗口大小时不会发出此事件。
Event: 'will-resize' macOS Windows
Returns:
event
EventnewBounds
Rectangle
- Size the window is being resized to.
Emitted before the window is resized. Calling event.preventDefault()
will prevent the window from being resized.
Note that this is only emitted when the window is being resized manually. Resizing the window with setBounds
/setSize
will not emit this event.
事件: 'resize'
调整窗口大小后触发。
Event: 'resize'
Emitted after the window has been resized.
事件: 'will-move' Windows
返回:
event
EventnewBounds
Rectangle
- 将要移动的新的窗口位置。
在移动窗口之前发出。调用event.preventDefault()
会阻止窗口被移动。
请注意,仅在手动调整窗口大小时才会发出此信息。使用setBounds
或 setSize
调整窗口大小时不会发出此事件。
Event: 'will-move' Windows
Returns:
event
EventnewBounds
Rectangle
- Location the window is being moved to.
Emitted before the window is moved. Calling event.preventDefault()
will prevent the window from being moved.
Note that this is only emitted when the window is being resized manually. Resizing the window with setBounds
/setSize
will not emit this event.
事件: 'move'
窗口移动到新位置时触发
注意: 在 macOS 上,此事件是moved
的别名.
Event: 'move'
Emitted when the window is being moved to a new position.
Note: On macOS this event is an alias of moved
.
事件: 'moved' macOS
当窗口移动到新位置时触发一次
Event: 'moved' macOS
Emitted once when the window is moved to a new position.
事件: 'enter-full-screen'
窗口进入全屏状态时触发
Event: 'enter-full-screen'
Emitted when the window enters a full-screen state.
事件: 'leave-full-screen'
窗口离开全屏状态时触发
Event: 'leave-full-screen'
Emitted when the window leaves a full-screen state.
事件: 'enter-html-full-screen'
窗口进入由HTML API 触发的全屏状态时触发
Event: 'enter-html-full-screen'
Emitted when the window enters a full-screen state triggered by HTML API.
事件: 'leave-html-full-screen'
窗口离开由HTML API触发的全屏状态时触发
Event: 'leave-html-full-screen'
Emitted when the window leaves a full-screen state triggered by HTML API.
Event: 'always-on-top-changed'
返回:
event
EventisAlwaysOnTop
Boolean
设置或取消设置窗口总是在其他窗口的顶部显示时触发。
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.
事件: 'app-command' Windows**Linux
返回:
event
Eventcommand
String
请求一个应用程序命令时触发. 典型的是键盘上的媒体键或浏览器命令, 以及在Windows上的一些鼠标中内置的“后退”按钮。
命令是小写的,下划线替换为连字符,以及APPCOMMAND_
前缀将被删除。 例如 APPCOMMAND_BROWSER_BACKWARD
将被browser-backward
触发.
const { BrowserWindow } = require('electron')
let win = new BrowserWindow()
win.on('app-command', (e, cmd) => {
// 当用户点击鼠标返回按钮时,导航窗口会后退
if (cmd === 'browser-backward' && win.webContents.canGoBack()) {
win.webContents.goBack()
}
})
The following app commands are explictly supported on Linux:
browser-backward
browser-forward
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.
Commands are lowercased, underscores are replaced with hyphens, and the APPCOMMAND_
prefix is stripped off. e.g. APPCOMMAND_BROWSER_BACKWARD
is emitted as browser-backward
.
const { BrowserWindow } = require('electron')
let 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 explictly supported on Linux:
browser-backward
browser-forward
事件: 'scroll-touch-begin' macOS
滚轮事件阶段开始时触发
Event: 'scroll-touch-begin' macOS
Emitted when scroll wheel event phase has begun.
事件: 'scroll-touch-end' macOS
滚轮事件阶段结束时触发
Event: 'scroll-touch-end' macOS
Emitted when scroll wheel event phase has ended.
事件: 'scroll-touch-edge' macOS
滚轮事件阶段到达元素边缘时触发
Event: 'scroll-touch-edge' macOS
Emitted when scroll wheel event phase filed upon reaching the edge of element.
事件: 'swipe' macOS
返回:
event
Eventdirection
String
三指拖移时触发,可选的方向为 up
, right
, down
, left
.
Event: 'swipe' macOS
Returns:
event
Eventdirection
String
Emitted on 3-finger swipe. Possible directions are up
, right
, down
, left
.
事件: 'sheet-begin' macOS
窗口打开sheet(工作表) 时触发
Event: 'sheet-begin' macOS
Emitted when the window opens a sheet.
事件: 'sheet-end' macOS
窗口关闭sheet(工作表) 时触发
Event: 'sheet-end' macOS
Emitted when the window has closed a sheet.
事件: 'new-window-for-tab' macOS
当点击了系统的新标签按钮时触发
Event: 'new-window-for-tab' macOS
Emitted when the native new tab button is clicked.
静态方法
BrowserWindow
类有以下方法:
Static Methods
The BrowserWindow
class has the following static methods:
BrowserWindow.getAllWindows()
返回 BrowserWindow[]
- 所有打开的窗口的数组
BrowserWindow.getAllWindows()
Returns BrowserWindow[]
- An array of all opened browser windows.
BrowserWindow.getFocusedWindow()
返回 BrowserWindow | null
- 此应用程序中当前获得焦点的窗口,如果无就返回 null
.
BrowserWindow.getFocusedWindow()
Returns BrowserWindow | null
- The window that is focused in this application, otherwise returns null
.
BrowserWindow.fromWebContents(webContents)
webContents
WebContents
返回 BrowserWindow
- 拥有给定 webContents
的窗口.
BrowserWindow.fromWebContents(webContents)
webContents
WebContents
Returns BrowserWindow
- The window that owns the given webContents
.
BrowserWindow.fromBrowserView(browserView)
browserView
BrowserView
返回 BrowserWindow | null
-拥有给定 browserView
的窗口。如果给定视图未附加到任何窗口, 则返回 null
。
BrowserWindow.fromBrowserView(browserView)
browserView
BrowserView
Returns BrowserWindow | null
- The window that owns the given browserView
. If the given view is not attached to any window, returns null
.
BrowserWindow.fromId(id)
id
Integer
返回 BrowserWindow
-拥有给定 id
的窗口.
BrowserWindow.fromId(id)
id
Integer
Returns BrowserWindow
- The window with the given id
.
BrowserWindow.addExtension(path)
path
String
添加位于 path
的扩展,并且返回扩展名
该方法如果扩展的 manifest 缺失或不完整,该方法不会返回。
注意: 该 API 不能在 app
模块的 ready
事件之前调用.
BrowserWindow.addExtension(path)
path
String
Adds Chrome extension located at path
, and returns extension's name.
The method will also not return if the extension's manifest is missing or incomplete.
Note: This API cannot be called before the ready
event of the app
module is emitted.
BrowserWindow.removeExtension(name)
name
String
根据名字删除一个 Chrome 的扩展。
注意: 该 API 不能在 app
模块的 ready
事件之前调用.
BrowserWindow.removeExtension(name)
name
String
Remove a Chrome extension by name.
Note: This API cannot be called before the ready
event of the app
module is emitted.
BrowserWindow.getExtensions()
返回 Object
- 键是扩展名, 每个值都是一个包含 name
和 version
属性的对象.
注意: 该 API 不能在 app
模块的 ready
事件之前调用.
BrowserWindow.getExtensions()
Returns Object
- The keys are the extension names and each value is an Object containing name
and version
properties.
Note: This API cannot be called before the ready
event of the app
module is emitted.
BrowserWindow.addDevToolsExtension(path)
path
String
添加位于 path
的 DevTools 扩展,并且返回扩展名
扩展将被记住, 所以你只需要调用这个API一次, 这个API不是用于编程使用. 如果尝试添加已经加载的扩展, 此方法将不会返回, 而是会向控制台记录警告.
该方法如果扩展的 manifest 缺失或不完整,该方法不会返回。
注意: 该 API 不能在 app
模块的 ready
事件之前调用.
BrowserWindow.addDevToolsExtension(path)
path
String
Adds DevTools extension located at path
, and returns extension's name.
The extension will be remembered so you only need to call this API once, this API is not for programming use. If you try to add an extension that has already been loaded, this method will not return and instead log a warning to the console.
The method will also not return if the extension's manifest is missing or incomplete.
Note: This API cannot be called before the ready
event of the app
module is emitted.
BrowserWindow.removeDevToolsExtension(name)
name
String
根据名字删除一个 DevTools 的扩展。
注意: 该 API 不能在 app
模块的 ready
事件之前调用.
BrowserWindow.removeDevToolsExtension(name)
name
String
Remove a DevTools extension by name.
Note: This API cannot be called before the ready
event of the app
module is emitted.
BrowserWindow.getDevToolsExtensions()
返回 Object
- 键是扩展名, 每个值都是一个包含 name
和 version
属性的对象.
要检查是否安装了 DevTools 扩展,您可以运行以下内容:
const { BrowserWindow } = require('electron')
let installed = BrowserWindow.getDevToolsExtensions().hasOwnProperty('devtron')
console.log(installed)
注意: 该 API 不能在 app
模块的 ready
事件之前调用.
BrowserWindow.getDevToolsExtensions()
Returns Object
- The keys are the extension names and each value is an Object containing name
and version
properties.
To check if a DevTools extension is installed you can run the following:
const { BrowserWindow } = require('electron')
let installed = BrowserWindow.getDevToolsExtensions().hasOwnProperty('devtron')
console.log(installed)
Note: This API cannot be called before the ready
event of the app
module is emitted.
实例属性
使用 new BrowserWindow
创建的对象具有以下属性:
const { BrowserWindow } = require('electron')
// 在这个例子中,`win` 是我们的实例
let win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com')
Instance Properties
Objects created with new BrowserWindow
have the following properties:
const { BrowserWindow } = require('electron')
// In this example `win` is our instance
let win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('https://github.com')
win.webContents
窗口拥有的 WebContents
对象. 所有与网页相关的事件和操作都将通过它完成.
有关它的方法和事件, 请参见 webContents
documentation
win.webContents
A WebContents
object this window owns. All web page related events and operations will be done via it.
See the webContents
documentation for its methods and events.
win.id
Integer
窗口的唯一ID
win.id
A Integer
representing the unique ID of the window.
实例方法
使用 new BrowserWindow
创建的对象具有以下实例方法:
注意: 某些方法仅在特定的操作系统上可用, 这些方法会被标记出来。
Instance Methods
Objects created with new BrowserWindow
have the following instance methods:
Note: Some methods are only available on specific operating systems and are labeled as such.
win.destroy()
强制关闭窗口, 除了closed
之外,close
,unload
和 beforeunload
都不会被触发
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.
win.close()
尝试关闭窗口。这与用户手动点击窗口的关闭按钮效果相同。但页面也可以取消关闭。请看 close event
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()
聚焦于窗口
win.focus()
Focuses on the window.
win.blur()
取消窗口的聚焦
win.blur()
Removes focus from the window.
win.isFocused()
返回 Boolean
- 判断窗口是否聚焦
win.isFocused()
Returns Boolean
- Whether the window is focused.
win.isDestroyed()
返回 Boolean
-判断窗口是否被销毁
win.isDestroyed()
Returns Boolean
- Whether the window is destroyed.
win.show()
显示并聚焦于窗口
win.show()
Shows and gives focus to the window.
win.showInactive()
显示但不聚焦于窗口
win.showInactive()
Shows the window but doesn't focus on it.
win.hide()
隐藏窗口
win.hide()
Hides the window.
win.isVisible()
返回 Boolean
- 判断窗口是否可见
win.isVisible()
Returns Boolean
- Whether the window is visible to the user.
win.isModal()
返回 Boolean
- 判断是否为模态窗口
win.isModal()
Returns Boolean
- Whether current window is a modal window.
win.maximize()
最大化窗口。如果窗口尚未显示, 这也将会显示 (但不会聚焦)。
win.maximize()
Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already.
win.unmaximize()
取消窗口最大化
win.unmaximize()
Unmaximizes the window.
win.isMaximized()
返回 Boolean
- 判断窗口是否最大化
win.isMaximized()
Returns Boolean
- Whether the window is maximized.
win.minimize()
窗口最小化。在某些平台上, 最小化的窗口将显示在Dock中.
win.minimize()
Minimizes the window. On some platforms the minimized window will be shown in the Dock.
win.restore()
将窗口从最小化状态恢复到以前的状态。
win.restore()
Restores the window from minimized state to its previous state.
win.isMinimized()
返回 Boolean
-判断窗口是否最小化
win.isMinimized()
Returns Boolean
- Whether the window is minimized.
win.setFullScreen(flag)
flag
Boolean
设置窗口是否应处于全屏模式。
win.setFullScreen(flag)
flag
Boolean
Sets whether the window should be in fullscreen mode.
win.isFullScreen()
返回 Boolean
- 窗口当前是否已全屏
win.isFullScreen()
Returns Boolean
- Whether the window is in fullscreen mode.
win.setSimpleFullScreen(flag)
macOS
flag
Boolean
进入或离开简单的全屏模式。
简单全屏模式模拟 Mac OS X prior to Lion (10.7) 版本中发现的原生全屏行为。
win.setSimpleFullScreen(flag)
macOS
flag
Boolean
Enters or leaves simple fullscreen mode.
Simple fullscreen mode emulates the native fullscreen behavior found in versions of Mac OS X prior to Lion (10.7).
win.isSimpleFullScreen()
macOS
返回 Boolean
- 窗口是否为简单全屏模式(pre-Lion)。
win.isSimpleFullScreen()
macOS
Returns Boolean
- Whether the window is in simple (pre-Lion) fullscreen mode.
win.isNormal()
返回 Boolean
- 窗口是否处于正常状态(未最大化,未最小化,不在全屏模式下)。
win.isNormal()
Returns Boolean
- Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode).
win.setAspectRatio(aspectRatio[, extraSize])
macOS
aspectRatio
Float- 为内容视图保持的宽高比.extraSize
Size - 维持高宽比值时不包含的额外大小
这将使窗口保持长宽比。 额外的大小允许开发人员有空间 (以像素为单位), 不包括在纵横比计算中。 此 API 已经考虑了窗口大小和内容大小之间的差异。
想象一个使用高清视频播放器和相关控件的普通窗口。 假假如左边缘有15px, 右边缘有25px, 在播放器下面有50px. 为了保持16:9 的长宽比 (标准的HD长宽比为1920x1080), 我们可以调用这个api传入参数16/9 和[ 40,50 ]. 第二个参数不管网页中的额外的宽度和高度在什么位置, 只要它们存在就行. 在全部内部窗口中,加上任何额外的宽度和高度 。
使用 0
调用此函数,将会移除先前设置的宽高比。
win.setAspectRatio(aspectRatio[, extraSize])
macOS
aspectRatio
Float - The aspect ratio to maintain for some portion of the content view.extraSize
Size - 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.
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 [ 40, 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.
Calling this function with a value of 0
will remove any previously set aspect ratios.
win.setBackgroundColor(backgroundColor)
backgroundColor
String - 十六进制的窗口背景色,如#66CD00
、#FFF
和#80FFFFFF
。 (如果transparent
是true
的话,也支持alpha 通道。) 默认值为#FFF
(白色)。
设置窗体的背景颜色。详见 Setting backgroundColor
。
win.setBackgroundColor(backgroundColor)
backgroundColor
String - Window's background color as a hexadecimal value, like#66CD00
or#FFF
or#80FFFFFF
(alpha is supported iftransparent
istrue
). Default is#FFF
(white).
Sets the background color of the window. See Setting backgroundColor
.
win.previewFile(path[, displayName])
macOS
path
String -要用 QuickLook 预览的文件的绝对路径。 这一点很重要,因为Quick Look 使用了路径上的文件名和文件扩展名 来决定要打开的文件的内容类型。displayName
String (可选) - 在Quick Look 模态视图中显示的文件的名称。 这完全是视觉的,不会影响文件的内容类型。 默认值为path
.
使用 Quick Look来预览路径中的文件.
win.previewFile(path[, displayName])
macOS
path
String - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open.displayName
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 topath
.
Uses Quick Look to preview a file at a given path.
win.closeFilePreview()
macOS
关闭当前打开的 Quick Look 面板.
win.closeFilePreview()
macOS
Closes the currently open Quick Look panel.
win.setBounds(bounds[, animate])
bounds
Rectangleanimate
Boolean (可选) macOS
重新调整窗口大小并将其移动到提供的 bounds。当一些属性值没有被提供时,将不被更改。
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.setBounds(bounds[, animate])
bounds
Rectangleanimate
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
.
win.getBounds()
Returns Rectangle
- The bounds
of the window as Object
.
win.setContentBounds(bounds[, animate])
bounds
Rectangleanimate
Boolean (可选) macOS
调整窗口的工作区 (如网页) 的大小并将其移动到所提供的边界。
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.getContentBounds()
Returns Rectangle
- The bounds
of the window's client area as Object
.
win.getNormalBounds()
返回 Rectangle
- 包含正常状态下的窗口大小。
注意:无论当前的窗口状态为:最大化、最小化或者全屏,这个方法都将得到窗口在正常显示状态下的位置信息以及大小信息。 在正常状态下,getBounds 与 getNormalBounds 得到的边界信息 Rectangle
是一致的。
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
.
win.setEnabled(enable)
enable
Boolean
禁用或者启用窗口。
win.setEnabled(enable)
enable
Boolean
Disable or enable the window.
win.setSize(width, height[, animate])
width
Integerheight
Integeranimate
Boolean (可选) macOS
将窗口的大小调整为width
和height
. 如果width
或height
低于设定的最小值, 那么对应的大小将被截断至设定的最小值.
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()
返回 Integer []
-包含窗口的宽度和高度。
win.getSize()
Returns Integer[]
- Contains the window's width and height.
win.setContentSize(width, height[, animate])
width
Integerheight
Integeranimate
Boolean (可选) macOS
将窗口的工作区 (如网页) 的大小调整为 width
和 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()
返回 Integer []
-包含窗口的宽度和高度。
win.getContentSize()
Returns Integer[]
- Contains the window's client area's width and height.
win.setMinimumSize(width, height)
width
Integerheight
Integer
设置窗口最小化的 width
和height
.
win.setMinimumSize(width, height)
width
Integerheight
Integer
Sets the minimum size of window to width
and height
.
win.getMinimumSize()
返回 Integer []
-包含窗口最小化的宽度和高度。
win.getMinimumSize()
Returns Integer[]
- Contains the window's minimum width and height.
win.setMaximumSize(width, height)
width
Integerheight
Integer
设置窗口最大化的 width
和 height
.
win.setMaximumSize(width, height)
width
Integerheight
Integer
Sets the maximum size of window to width
and height
.
win.getMaximumSize()
返回 Integer []
-包含窗口最大化的宽度和高度。
win.getMaximumSize()
Returns Integer[]
- Contains the window's maximum width and height.
win.setResizable(resizable)
resizable
Boolean
设置用户是否可以手动调整窗口大小。
win.setResizable(resizable)
resizable
Boolean
Sets whether the window can be manually resized by user.
win.isResizable()
返回 Boolean
- 设置窗口是否可以被用户改变大小.
win.isResizable()
Returns Boolean
- Whether the window can be manually resized by user.
win.setMovable(movable)
macOS Windows
movable
Boolean
设置窗口是否可由用户移动。在 Linux 上无效。
win.setMovable(movable)
macOS Windows
movable
Boolean
Sets whether the window can be moved by user. On Linux does nothing.
win.isMovable()
macOS Windows
返回 Boolean
- 窗口是否可以被用户拖动
在 Linux 上总是返回 true
。
win.isMovable()
macOS Windows
Returns Boolean
- Whether the window can be moved by user.
On Linux always returns true
.
win.setMinimizable(minimizable)
macOS Windows
minimizable
Boolean
设置窗口是否可以最小化. 在 Linux 上无效.
win.setMinimizable(minimizable)
macOS Windows
minimizable
Boolean
Sets whether the window can be manually minimized by user. On Linux does nothing.
win.isMinimizable()
macOS Windows
返回 Boolean
-窗口是否可以最小化
在 Linux 上总是返回 true
。
win.isMinimizable()
macOS Windows
Returns Boolean
- Whether the window can be manually minimized by user
On Linux always returns true
.
win.setMaximizable(maximizable)
macOS Windows
maximizable
Boolean
设置窗口是否可以最大化. 在 Linux 上无效.
win.setMaximizable(maximizable)
macOS Windows
maximizable
Boolean
Sets whether the window can be manually maximized by user. On Linux does nothing.
win.isMaximizable()
macOS Windows
返回 Boolean
- 窗口是否可以最大化.
在 Linux 上总是返回 true
。
win.isMaximizable()
macOS Windows
Returns Boolean
- Whether the window can be manually maximized by user.
On Linux always returns true
.
win.setFullScreenable(fullscreenable)
fullscreenable
Boolean
设置点击最大化按钮是否可以全屏或最大化窗口.
win.setFullScreenable(fullscreenable)
fullscreenable
Boolean
Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.
win.isFullScreenable()
返回 Boolean
- 是否为全屏状态或窗口最大化
win.isFullScreenable()
Returns Boolean
- Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.
win.setClosable(closable)
macOS Windows
closable
Boolean
设置窗口是否可以人为关闭。在 Linux 上无效.
win.setClosable(closable)
macOS Windows
closable
Boolean
Sets whether the window can be manually closed by user. On Linux does nothing.
win.isClosable()
macOS Windows
返回 Boolean
- 窗口是否被用户关闭了.
在 Linux 上总是返回 true
。
win.isClosable()
macOS Windows
Returns Boolean
- Whether the window can be manually closed by user.
On Linux always returns true
.
win.setAlwaysOnTop(flag[, level][, relativeLevel])
flag
Booleanlevel
String (可选) macOS - 可以为下面的值normal
,floating
,torn-off-menu
,modal-panel
,main-menu
,status
,pop-up-menu
,screen-saver
, 和(参考值). 默认值为dock
floating
. 更多信息,请查阅 macOS docsrelativeLevel
Integer (可选) macOS - 设置此窗口相对于给定级别
的层数。. 默认值为0
. 请注意, Apple 不鼓励在屏幕保护程序
之上设置高于1的级别。
设置窗口是否应始终显示在其他窗口的顶部。设置之后, 仍然是一个普通窗口, 而不是一个无法聚焦的工具箱窗口。
win.setAlwaysOnTop(flag[, level][, relativeLevel])
flag
Booleanlevel
String (optional) macOS - Values includenormal
,floating
,torn-off-menu
,modal-panel
,main-menu
,status
,pop-up-menu
,screen-saver
, and(Deprecated). The default isdock
floating
. See the macOS docs for more details.relativeLevel
Integer (optional) macOS - The number of layers higher to set this window relative to the givenlevel
. The default is0
. Note that Apple discourages setting levels higher than 1 abovescreen-saver
.
Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on.
win.isAlwaysOnTop()
返回 Boolean
- 当前窗口是否始终在其它窗口之前.
win.isAlwaysOnTop()
Returns Boolean
- Whether the window is always on top of other windows.
win.moveTop()
无论焦点如何, 将窗口移至顶端(z轴上的顺序).
win.moveTop()
Moves window to top(z-order) regardless of focus
win.center()
将窗口移动到屏幕中央。
win.center()
Moves window to the center of the screen.
win.setPosition(x, y[, animate])
x
Integery
Integeranimate
Boolean (可选) macOS
将窗口移动到 x
和 y
。
win.setPosition(x, y[, animate])
x
Integery
Integeranimate
Boolean (optional) macOS
Moves window to x
and y
.
win.getPosition()
返回 Integer[]
- 返回一个包含当前窗口位置的数组.
win.getPosition()
Returns Integer[]
- Contains the window's current position.
win.setTitle(title)
title
String
将原生窗口的标题更改为 title
。
win.setTitle(title)
title
String
Changes the title of native window to title
.
win.getTitle()
返回 String
-原生窗口的标题。
Note: The title of the web page can be different from the title of the native window.
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 (可选)
更改macOS上的工作表的附件点。默认情况下, 工作表时在窗口框架下附加的,但是您可能想要将它们显示在 HTML-rendered 的工具栏。例如:
const { BrowserWindow } = require('electron')
let win = new BrowserWindow()
let toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
win.setSheetOffset(toolbarRect.height)
win.setSheetOffset(offsetY[, offsetX])
macOS
offsetY
FloatoffsetX
Float (optional)
Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example:
const { BrowserWindow } = require('electron')
let win = new BrowserWindow()
let toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
win.setSheetOffset(toolbarRect.height)
win.flashFrame(flag)
flag
Boolean
启动或停止闪烁窗口, 以吸引用户的注意。
win.flashFrame(flag)
flag
Boolean
Starts or stops flashing the window to attract user's attention.
win.setSkipTaskbar(skip)
skip
Boolean
使窗口不显示在任务栏中。
win.setSkipTaskbar(skip)
skip
Boolean
Makes the window not show in the taskbar.
win.setKiosk(flag)
flag
Boolean
进入或离开 kiosk 模式。
win.setKiosk(flag)
flag
Boolean
Enters or leaves the kiosk mode.
win.isKiosk()
返回 Boolean
- 判断窗口是否处于kiosk模式.
win.isKiosk()
Returns Boolean
- Whether the window is in kiosk mode.
win.getNativeWindowHandle()
返回 Buffer
- 窗口的平台特定句柄
Windows上句柄类型为 HWND
,macOS 上为 NSView*
,Linux 上为Window
(unsigned long
)
win.getNativeWindowHandle()
Returns Buffer
- The platform-specific handle of the window.
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
Integercallback
Function
挂钩窗口的消息。在 WndProc 中接收消息时调用callback
。
win.hookWindowMessage(message, callback)
Windows
message
Integercallback
Function
Hooks a windows message. The callback
is called when the message is received in the WndProc.
win.isWindowMessageHooked(message)
Windows
message
Integer
返回 Boolean
- true
或false
,具体取决于是否钩挂了消息.
win.isWindowMessageHooked(message)
Windows
message
Integer
Returns Boolean
- true
or false
depending on whether the message is hooked.
win.unhookWindowMessage(message)
Windows
message
Integer
取消窗口信息的钩子。
win.unhookWindowMessage(message)
Windows
message
Integer
Unhook the window message.
win.unhookAllWindowMessages()
Windows
取消所有窗口信息的钩子。
win.unhookAllWindowMessages()
Windows
Unhooks all of the window messages.
win.setRepresentedFilename(filename)
macOS
filename
String
设置窗口所代表的文件的路径名,并且将这个文件的图标放在窗口标题栏上。
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
返回 String
- 获取窗口当前文件路径.
win.getRepresentedFilename()
macOS
Returns String
- The pathname of the file the window represents.
win.setDocumentEdited(edited)
macOS
edited
Boolean
明确指出窗口文档是否可以编辑, 如果设置为true
则将标题栏的图标变成灰色.
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
.
win.isDocumentEdited()
macOS
返回 Boolean
- 判断当前窗口文档是否可编辑.
win.isDocumentEdited()
macOS
Returns Boolean
- Whether the window's document has been edited.
win.focusOnWebView()
win.focusOnWebView()
win.blurWebView()
win.blurWebView()
win.capturePage([rect, ]callback)
rect
Rectangle (可选) - 捕获的区域callback
Functionimage
NativeImage
Captures a snapshot of the page within rect
. Upon completion callback
will be called with callback(image)
. The image
is an instance of NativeImage that stores data of the snapshot. Omitting rect
will capture the whole visible page.
马上将弃用
win.capturePage([rect, ]callback)
rect
Rectangle (optional) - The bounds to capturecallback
Functionimage
NativeImage
Captures a snapshot of the page within rect
. Upon completion callback
will be called with callback(image)
. The image
is an instance of NativeImage that stores data of the snapshot. Omitting rect
will capture the whole visible page.
Deprecated Soon
win.capturePage([rect])
rect
Rectangle (可选) - 捕获的区域
Returns Promise<NativeImage>
- Resolves with a NativeImage
Captures a snapshot of the page within rect
. Omitting rect
will capture the whole visible page.
win.capturePage([rect])
rect
Rectangle (optional) - The bounds to capture
Returns Promise<NativeImage>
- Resolves with a NativeImage
Captures a snapshot of the page within rect
. Omitting rect
will capture the whole visible page.
win.loadURL(url[, options])
url
Stringoptions
Object (可选)httpReferrer
(String | Referrer) (可选) - 一个 HTTP Referrer url。userAgent
String (可选) - 发起请求的 userAgent.extraHeaders
String (可选) - 用 "n" 分割的额外标题postData
(UploadRawData[] | UploadFile[] | UploadBlob[]) (可选)baseURLForDataURL
String (可选) - 要加载的数据文件的根 url(带有路径分隔符). 只有当指定的url
是一个数据 url 并需要加载其他文件时,才需要这样做。
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
).
Same as webContents.loadURL(url[, options])
.
url
可以是远程地址 (例如 http://
),也可以是 file://
协议的本地HTML文件的路径.
为了确保文件网址格式正确, 建议使用Node的 url.format
方法:
let url = require('url').format({
protocol: 'file',
slashes: true,
pathname: require('path').join(__dirname, 'index.html')
})
win.loadURL(url)
您可以通过执行以下操作, 使用带有网址编码数据的 POST
请求加载网址:
win.loadURL('http://localhost:8000/post', {
postData: [{
type: 'rawData',
bytes: Buffer.from('hello=world')
}],
extraHeaders: 'Content-Type: application/x-www-form-urlencoded'
})
win.loadURL(url[, options])
url
Stringoptions
Object (optional)httpReferrer
(String | Referrer) (optional) - An HTTP Referrer url.userAgent
String (optional) - A user agent originating the request.extraHeaders
String (optional) - Extra headers separated by "n"postData
(UploadRawData[] | UploadFile[] | UploadBlob[]) (optional)baseURLForDataURL
String (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specifiedurl
is a data url and needs to load other files.
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
).
Same as 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.
To ensure that file URLs are properly formatted, it is recommended to use Node's url.format
method:
let 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 POST
request with URL-encoded data by doing the following:
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
Stringoptions
Object (可选)query
Object (可选) - 传递给url.format()
.search
String (可选) - 传递给url.format()
.hash
String (可选) - 传递给url.format()
.
Returns Promise<void>
- the promise will resolve when the page has finished loading (see did-finish-load
), and rejects if the page fails to load (see did-fail-load
).
类似于webContents.loadFile
,filePath
是一个HTML页相对的应用根目录的相对路径。更多信息,可参阅webContents
文档。
win.loadFile(filePath[, options])
filePath
Stringoptions
Object (optional)query
Object (optional) - Passed tourl.format()
.search
String (optional) - Passed tourl.format()
.hash
String (optional) - Passed tourl.format()
.
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
).
Same as webContents.loadFile
, filePath
should be a path to an HTML file relative to the root of your application. See the webContents
docs for more information.
win.reload()
与 webContents.reload
相同.
win.reload()
Same as webContents.reload
.
win.setMenu(menu)
Linux Windows
menu
Menu | null
Sets the menu
as the window's menu bar.
win.setMenu(menu)
Linux Windows
menu
Menu | null
Sets the menu
as the window's menu bar.
win.removeMenu()
Linux Windows
Remove the window's menu bar.
win.removeMenu()
Linux Windows
Remove the window's menu bar.
win.setProgressBar(progress[, options])
progress
Doubleoptions
Object (可选)mode
String Windows - 进度条的模式. 可以为none
,normal
,indeterminate
,error
, 或paused
.
设置进度栏中的进度值。有效范围是 [0, 1.0]。
当进度小于0时不显示进度; 当进度大于0时显示结果不确定.
在 Linux 平台上,只支持 Unity 桌面模式, 你需要在 package.json
中为 desktopName
指定 *.desktop
的文件名. 默认值为 app.getName().desktop
.
在 Windows 上, 可以传递模式。 可以接受的值为none
, normal
, indeterminate
, error
和 paused
. 如果没有设置模式 (但值在有效范围内) 的情况下调用 setProgressBar
, 默认值为normal
。
win.setProgressBar(progress[, options])
progress
Doubleoptions
Object (optional)mode
String Windows - Mode for the progress bar. Can benone
,normal
,indeterminate
,error
orpaused
.
Sets progress value in progress bar. Valid range is [0, 1.0].
Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1.
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.getName().desktop
.
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
String -提供给屏幕阅读器的描述文字
在当前任务栏图标上设置一个 16 x 16 像素的图标, 通常用于传达某种应用程序状态或被动地通知用户。
win.setOverlayIcon(overlay, description)
Windows
overlay
NativeImage | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter isnull
, the overlay is cleareddescription
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.
win.setHasShadow(hasShadow)
macOS
hasShadow
Boolean
设置窗口是否应该有阴影. 在 Windows 和 Linux 系统无效
win.setHasShadow(hasShadow)
hasShadow
Boolean
Sets whether the window should have a shadow.
win.hasShadow()
macOS
返回 Boolean
- 判断窗口是否有阴影.
在 Windows 和 Linux 上总是返回 true
.
win.hasShadow()
Returns Boolean
- Whether the window has a shadow.
win.setOpacity(opacity)
Windows macOS
opacity
Number - 介于0.0 ( 完全透明 ) 和1.0 ( 完全不透明 ) 之间
设置窗口的不透明度,在Linux系统上无效
win.setOpacity(opacity)
Windows macOS
opacity
Number - between 0.0 (fully transparent) and 1.0 (fully opaque)
Sets the opacity of the window. On Linux does nothing.
win.getOpacity()
Windows macOS
返回 Number
- 介于0.0 ( 完全透明) 和1.0 ( 完全不透明) 之间
win.getOpacity()
Windows macOS
Returns Number
- between 0.0 (fully transparent) and 1.0 (fully opaque)
win.setShape(rects)
Windows Linux 实验性
rects
Rectangle[] - 设置窗口的形状. 传入空列表会使窗口恢复至矩形.
对窗口形状的设置决定了窗口内系统允许绘制与用户交互的区域. 在给定的区域外, 没有像素会被绘制, 且没有鼠标事件会被登记. 在该区域外的鼠标事件将不会被该窗口接收, 而是落至该窗口后方的任意窗口.
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[]
返回 Boolean
- 按钮是否成功添加
将指定的一组按钮添加到菜单栏的缩图工具栏上。 返回一个 Boolean
对象表示是否成功地添加了缩略图.
由于空间有限, 缩图工具栏中的按钮数量不要超过7个。 一旦设置了缩略图工具栏,则无法删除。 但你可以通过调用 API 传递一个空数组来清除按钮.
buttons
是一个 Button
对象的数组:
Button
Objecticon
NativeImage - 在缩图工具栏上显示的图标.click
Functiontooltip
String (可选) - 按钮的提示文本.flags
String - 控制按钮特定的状态和行为. 默认为['enabled']
.
flags
属性是一个数组,包含以下String
类型的值:
enabled
- 该按钮处于活动状态并可供用户使用.disabled
- 该按钮被禁用。 它存在,但有一个显示状态表明它不会响应用户操作。dismissonclick
- 当按钮被点击时,缩略图窗口立即关闭。nobackground
- 不可以画按钮边框,只能使用图片背景。hidden
- 该按钮对用户不可见。noninteractive
- 该按钮已启用,但处于未激活状态; 没有绘制按钮按下状态。 这个值用于通知功能的按钮实例。
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.
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.
The buttons
is an array of Button
objects:
Button
Objecticon
NativeImage - The icon showing in thumbnail toolbar.click
Functiontooltip
String (optional) - The text of the button's tooltip.flags
String - Control specific states and behaviors of the button. By default, it is['enabled']
.
The flags
is an array that can include following String
s:
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 窗口的区域
将窗口的区域设置为在任务栏中悬停在窗口上方时显示的缩略图图像。 通过指定空区域:{ x: 0, y: 0, width: 0, height: 0 }
,可以重置整个窗口的缩略图。
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 }
.
win.setThumbnailToolTip(toolTip)
Windows
toolTip
String
设置在任务栏中悬停在窗口缩略图上时显示的工具提示。
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
options
ObjectappId
String (可选) - 窗口的 App User Model ID. 该项必须设置, 否则其他选项将没有效果.appIconPath
String (可选) -窗口的 Relaunch Icon.appIconIndex
Integer (可选) -appIconPath
中的图标索引. 当appIconPath
没设置时则忽略. 默认值为0
.relaunchCommand
String (可选) - 窗口的 重新启动命令.relaunchDisplayName
String (可选) - 窗口的重新启动显示名称.
设置窗口任务栏按钮的属性。
注意: relaunchCommand
和 relaunchDisplayName
必须一起设置. 如果这些属性中的一个没有设置, 那么两者都不会被使用.
win.setAppDetails(options)
Windows
options
ObjectappId
String (optional) - Window's App User Model ID. It has to be set, otherwise the other options will have no effect.appIconPath
String (optional) - Window's Relaunch Icon.appIconIndex
Integer (optional) - Index of the icon inappIconPath
. Ignored whenappIconPath
is not set. Default is0
.relaunchCommand
String (optional) - Window's Relaunch Command.relaunchDisplayName
String (optional) - Window's Relaunch Display Name.
Sets the properties for the window's taskbar button.
Note: relaunchCommand
and relaunchDisplayName
must always be set together. If one of those properties is not set, then neither will be used.
win.showDefinitionForSelection()
macOS
和 webContents.showDefinitionForSelection()
相同.
win.showDefinitionForSelection()
macOS
Same as webContents.showDefinitionForSelection()
.
win.setIcon(icon)
Windows Linux
icon
NativeImage
设置窗口图标
win.setIcon(icon)
Windows Linux
icon
NativeImage
Changes window icon.
win.setWindowButtonVisibility(visible)
macOS
visible
Boolean
设置是否窗口交通灯需要显示。
当titleBarStyle
是 customButtonsOnHover
的时候,不可调用。
win.setWindowButtonVisibility(visible)
macOS
visible
Boolean
Sets whether the window traffic light buttons should be visible.
This cannot be called when titleBarStyle
is set to customButtonsOnHover
.
win.setAutoHideMenuBar(hide)
hide
Boolean
设置窗口的菜单栏是否自动隐藏。设置后只有当用户按下 Alt
键时才显示菜单栏.
如果菜单栏已经可见, 调用 setAutoHideMenuBar(true)
时不会立刻隐藏.
win.setAutoHideMenuBar(hide)
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
key.
If the menu bar is already visible, calling setAutoHideMenuBar(true)
won't hide it immediately.
win.isMenuBarAutoHide()
返回 Boolean
- 判断窗口的菜单栏是否自动隐藏.
win.isMenuBarAutoHide()
Returns Boolean
- Whether menu bar automatically hides itself.
win.setMenuBarVisibility(visible)
Windows Linux
visible
Boolean
设置窗口的菜单栏是否可见. 如果设为可见, 菜单栏自动隐藏时, 用户仍然可以按下 Alt
键来显示.
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
key.
win.isMenuBarVisible()
返回 Boolean
- 判断窗口的菜单栏是否可见.
win.isMenuBarVisible()
Returns Boolean
- Whether the menu bar is visible.
win.setVisibleOnAllWorkspaces(visible[, options])
visible
Booleanoptions
Object (可选)visibleOnFullScreen
Boolean (可选) macOS - 设置是否窗口可以在全屏窗口之上显示。
设置窗口是否在所有工作空间上可见
注意: 该 API 在 Windows 上无效.
win.setVisibleOnAllWorkspaces(visible[, options])
visible
Booleanoptions
Object (optional)visibleOnFullScreen
Boolean (optional) macOS - Sets whether the window should be visible above fullscreen windows
Sets whether the window should be visible on all workspaces.
Note: This API does nothing on Windows.
win.isVisibleOnAllWorkspaces()
返回 Boolean
- 判断窗口是否在所有工作空间上可见.
注意: 该 API 在 Windows 上始终返回 false.
win.isVisibleOnAllWorkspaces()
Returns Boolean
- Whether the window is visible on all workspaces.
Note: This API always returns false on Windows.
win.setIgnoreMouseEvents(ignore[, options])
ignore
Booleanoptions
Object (可选)forward
Boolean (可选) macOS Windows - 如果为 true, 传递鼠标移动消息给 Chromium,鼠标相关事件将可用,如mouseleave
。 仅当ignore </ 0>为 true 时才被使用。 如果 <code>ignore
为 false, 转发始终是禁用的,不管这个值是什么。
忽略窗口内的所有鼠标事件
在此窗口中发生的所有鼠标事件将被传递到此窗口下面的窗口, 但如果此窗口具有焦点, 它仍然会接收键盘事件
win.setIgnoreMouseEvents(ignore[, options])
ignore
Booleanoptions
Object (optional)forward
Boolean (optional) macOS Windows - If true, forwards mouse move messages to Chromium, enabling mouse related events such asmouseleave
. Only used whenignore
is true. Ifignore
is false, forwarding is always disabled regardless of this value.
Makes the window ignore all mouse events.
All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events.
win.setContentProtection(enable)
macOS Windows
enable
Boolean
防止窗口内容被其他应用捕获
在macOS中, 它设置 NSWindow的 sharingType为 NSWindowSharingNone. 在Windows中, 它设置 WDA_MONITOR
调用 SetWindowDisplayAffinity.
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. On Windows it calls SetWindowDisplayAffinity with WDA_MONITOR
.
win.setFocusable(focusable)
Windows
focusable
Boolean
设置窗口是否可聚焦
win.setFocusable(focusable)
Windows
focusable
Boolean
Changes whether the window can be focused.
win.setParentWindow(parent)
parent
BrowserWindow
设置 parent
为当前窗口的父窗口. 为null
时表示将当前窗口转为顶级窗口
win.setParentWindow(parent)
parent
BrowserWindow
Sets parent
as current window's parent window, passing null
will turn current window into a top-level window.
win.getParentWindow()
返回 BrowserWindow
- 父窗口.
win.getParentWindow()
Returns BrowserWindow
- The parent window.
win.getChildWindows()
返回 BrowserWindow[]
- 首页的子窗口.
win.getChildWindows()
Returns BrowserWindow[]
- All child windows.
win.setAutoHideCursor(autoHide)
macOS
autoHide
Boolean
设置输入时是否隐藏光标
win.setAutoHideCursor(autoHide)
macOS
autoHide
Boolean
Controls whether to hide cursor when typing.
win.selectPreviousTab()
macOS
当启用本地选项卡,并且窗口中有另一个标签时,选择上一个选项卡。
win.selectPreviousTab()
macOS
Selects the previous tab when native tabs are enabled and there are other tabs in the window.
win.selectNextTab()
macOS
当启用本地选项卡,并且窗口中有另一个标签时,选择下一个选项卡。
win.selectNextTab()
macOS
Selects the next tab when native tabs are enabled and there are other tabs in the window.
win.mergeAllWindows()
macOS
当启用本地选项卡并且存在多个打开窗口时,将所有窗口合并到一个带有多个选项卡的窗口中。
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
如果启用了本机选项卡并且当前窗口中有多个选项卡,则将当前选项卡移动到新窗口中。
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
如果启用了本机选项卡并且当前窗口中只有一个选项卡,则切换选项卡栏是否可见。
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
在该窗口中添加一个窗口作为选项卡,位于窗口实例的选项卡之后。
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 - 可以为appearance-based
,light
,dark
,titlebar
,selection
,menu
,popover
,sidebar
,medium-light
或ultra-dark
. 更多详细信息,请查阅 macOS documentation
在浏览器窗口中添加一个动态效果. 设置为null
或空字符串将移除窗口的动态效果。
win.setVibrancy(type)
macOS
type
String - Can beappearance-based
,light
,dark
,titlebar
,selection
,menu
,popover
,sidebar
,medium-light
orultra-dark
. See the macOS documentation for more details.
Adds a vibrancy effect to the browser window. Passing null
or an empty string will remove the vibrancy effect on the window.
win.setTouchBar(touchBar)
macOS 实验
touchBar
TouchBar
设置窗口的触摸条布局 设置为 null
或undefined
将清除触摸条. 此方法只有在macOS 10.12.1+且设备支持触摸条TouchBar时可用.
注意: TouchBar API目前为实验性质,以后的Electron版本可能会更改或删除。
win.setTouchBar(touchBar)
macOS Experimental
touchBar
TouchBar
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 and is running on macOS 10.12.1+.
Note: The TouchBar API is currently experimental and may change or be removed in future Electron releases.
win.setBrowserView(browserView)
实验
browserView
BrowserView. Attach browserView to win. If there is some other browserViews was attached they will be removed from this window.
win.setBrowserView(browserView)
Experimental
browserView
BrowserView. Attach browserView to win. If there is some other browserViews was attached they will be removed from this window.
win.getBrowserView()
实验功能
Returns BrowserView | null
- an BrowserView what is attached. Returns null
if none is attached. Throw error if multiple BrowserViews is attached.
win.getBrowserView()
Experimental
Returns BrowserView | null
- an BrowserView what is attached. Returns null
if none is attached. Throw error if multiple BrowserViews is attached.
win.addBrowserView(browserView)
实验
browserView
BrowserView
Replacement API for setBrowserView supporting work with multi browser views.
win.addBrowserView(browserView)
Experimental
browserView
BrowserView
Replacement API for setBrowserView supporting work with multi browser views.
win.removeBrowserView(browserView)
实验
browserView
BrowserView
win.removeBrowserView(browserView)
Experimental
browserView
BrowserView
win.getBrowserViews()
实验功能
Returns array of BrowserView
what was an attached with addBrowserView or setBrowserView.
注意: BrowserView 的 API目前为实验性质,可能会更改或删除。
win.getBrowserViews()
Experimental
Returns array of BrowserView
what was an attached with addBrowserView or setBrowserView.
Note: The BrowserView API is currently experimental and may change or be removed in future Electron releases.
属性
Properties
win.excludedFromShownWindowsMenu
macOS
A Boolean
property that determines whether the window is excluded from the application’s Windows menu. false
by default.
const win = new BrowserWindow({ height: 600, width: 600 })
const template = [
{
role: 'windowmenu'
}
]
win.excludedFromShownWindowsMenu = true
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
win.excludedFromShownWindowsMenu
macOS
A Boolean
property that determines whether the window is excluded from the application’s Windows menu. false
by default.
const win = new BrowserWindow({ height: 600, width: 600 })
const template = [
{
role: 'windowmenu'
}
]
win.excludedFromShownWindowsMenu = true
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)