Skip to main content

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事件

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. 加载页面时,如果窗口尚未显示,则当渲染器进程首次渲染页面时,将发出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. 请注意,使用此事件意味着即使showfalse,渲染器也将被视为“可见”并进行绘制。This event will never fire if you use paintWhenInitiallyHidden: false如果使用paintWhenInitiallyHidden: false,则此事件永远不会激发

Setting the backgroundColor property设置backgroundColor属性

For 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窗口的顶部。

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:模式窗口是禁用父窗口的子窗口,要创建模式窗口,必须同时设置parentmodal选项:

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. 如果该窗口被另一个窗口遮挡(即完全覆盖),则可见性状态将是hiddenOn other platforms, the visibility state will be hidden only when the window is minimized or explicitly hidden with win.hide().在其他平台上,只有当窗口最小化或使用win.hide()显式隐藏时,可见性状态才会是hidden
  • If a BrowserWindow is created with show: false, the initial visibility state will be visible despite the window actually being hidden.如果使用show: false创建BrowserWindow,则初始可见性状态将是visible,尽管窗口实际上是隐藏的。
  • If backgroundThrottling is disabled, the visibility state will remain visible 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 dialog.在Linux上,模式窗口的类型将更改为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])

  • options Object (optional)
    • width Integer (optional) - Window's width in pixels. Default is 800.窗口的宽度(以像素为单位)。默认值为800
    • height Integer (optional) - Window's height in pixels. Default is 600.窗口的高度(以像素为单位)。默认值为600
    • x Integer (optional) - (required if y is used) Window's left offset from screen. (如果使用y,则为必需)窗口与屏幕的左偏移。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.(如果使用x,则为必需)窗口与屏幕的顶部偏移。默认设置为使窗口居中。
    • useContentSize boolean (optional) - The width and height 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. widthheight将用作网页的大小,这意味着实际窗口的大小将包括窗框的大小,并略大。Default is false.默认值为false
    • center boolean (optional) - Show window in the center of the screen. 在屏幕中央显示窗口。Default is false.默认值为false
    • minWidth Integer (optional) - Window's minimum width. Default is 0.窗口的最小宽度。默认值为0
    • minHeight Integer (optional) - Window's minimum height. Default is 0.窗口的最小高度。默认值为0
    • 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 is true.窗口是否可调整大小。默认值为true
    • movable boolean (optional) macOS Windows - Whether window is movable. 窗口是否可移动。This is not implemented on Linux. 这并没有在Linux上实现。Default is true.默认值为true
    • minimizable boolean (optional) macOS Windows - Whether window is minimizable. 窗口是否可最小化。This is not implemented on Linux. Default is true.这并没有在Linux上实现。默认值为true
    • maximizable boolean (optional) macOS Windows - Whether window is maximizable. This is not implemented on Linux. 窗口是否可最大化。这并没有在Linux上实现。Default is true.默认值为true
    • closable boolean (optional) macOS Windows - Whether window is closable. This is not implemented on Linux. 窗口是否可关闭。这并没有在Linux上实现。Default is true.默认值为true
    • focusable boolean (optional) - Whether the window can be focused. Default is true. 窗口是否可以聚焦。默认值为trueOn Windows setting focusable: false also implies setting skipTaskbar: true. 在Windows上,设置focusable: false也意味着设置skipTaskbar: trueOn Linux setting focusable: false makes the window stop interacting with wm, so the window will always stay on top in all workspaces.在Linux上,设置focusable: false会使窗口停止与wm交互,因此该窗口在所有工作区中始终处于顶部。
    • alwaysOnTop boolean (optional) - Whether the window should always stay on top of other windows. 该窗口是否应始终位于其他窗口的顶部。Default is false.默认值为false
    • fullscreen boolean (optional) - Whether the window should show in fullscreen. 窗口是否应全屏显示。When explicitly set to false the fullscreen button will be hidden or disabled on macOS. 当明确设置为false时,macOS上的全屏按钮将被隐藏或禁用。Default is false.默认值为false
    • 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. 在macOS上,还有最大化/缩放按钮是否应切换全屏模式或最大化窗口。Default is true.默认值为true
    • simpleFullscreen boolean (optional) macOS - Use pre-Lion fullscreen on macOS. 在macOS上使用Lion之前的全屏。Default is false.默认值为false
    • skipTaskbar boolean (optional) macOS Windows - Whether to show the window in taskbar. 是否在任务栏中显示窗口。Default is false.默认值为false
    • kiosk boolean (optional) - Whether the window is in kiosk mode. 窗口是否处于信息亭模式。Default is false.默认值为false
    • title string (optional) - Default window title. 默认窗口标题。Default is "Electron". 默认为"Electron"If the HTML tag <title> is defined in the HTML file loaded by loadURL(), this property will be ignored.如果HTML标记<title>是在loadURL()加载的HTML文件中定义的,则此属性将被忽略。
    • icon (NativeImage | string) (optional) - The window icon. 窗口图标。On Windows it is recommended to use ICO icons to get best visual effects, you can also leave it undefined so the executable's icon will be used.在Windows上,建议使用ICO图标以获得最佳视觉效果,您也可以不定义它,以便使用可执行文件的图标。
    • show boolean (optional) - Whether window should be shown when created. 创建窗口时是否应显示。Default is true.默认值为true
    • paintWhenInitiallyHidden boolean (optional) - Whether the renderer should be active when show is false and it has just been created. showfalse并且渲染器刚刚创建时,渲染器是否应处于活动状态。In order for document.visibilityState to work correctly on first load with show: false you should set this to false. 为了使document.visibilityState在第一次加载show: false时正确工作,您应该将其设置为falseSetting this to false will cause the ready-to-show event to not fire. 将此设置为false将导致ready-to-show事件不启动。Default is true.默认值为true
    • frame boolean (optional) - Specify false to create a frameless window. 指定false以创建无框架窗口Default is true.默认值为true
    • parent BrowserWindow (optional) - Specify parent window. 指定父窗口。Default is null.默认值为null
    • modal boolean (optional) - Whether this is a modal window. 这是否是一个模态窗口。This only works when the window is a child window. 只有当窗口是子窗口时,这才有效。Default is false.默认值为false
    • acceptFirstMouse boolean (optional) macOS - Whether clicking an inactive window will also click through to the web contents. 单击非活动窗口是否也会单击到web内容。Default is false on macOS. 在macOS上,默认值为falseThis option is not configurable on other platforms.此选项在其他平台上不可配置。
    • disableAutoHideCursor boolean (optional) - Whether to hide cursor when typing. 键入时是否隐藏游标。Default is false.默认值为false
    • autoHideMenuBar boolean (optional) - Auto hide the menu bar unless the Alt key is pressed. 除非按下Alt键,否则自动隐藏菜单栏。Default is false.默认值为false
    • enableLargerThanScreen boolean (optional) macOS - Enable the window to be resized larger than screen. 使窗口的大小大于屏幕。Only relevant for macOS, as other OSes allow larger-than-screen windows by default. 仅与macOS相关,因为其他操作系统默认情况下允许大于屏幕的窗口。Default is false.默认值为false
    • backgroundColor string (optional) - The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. 窗口的背景颜色为十六进制、RGB、RGBA、HSL、HSLA或命名的CSS颜色格式。Alpha in #AARRGGBB format is supported if transparent is set to true. 如果transparent设置为true,则支持#AARGGBB格式的Alpha。Default is #FFF (white). 默认值为#FFF(白色)。See win.setBackgroundColor for more information.有关详细信息,请参阅win.setBackgroundColor
    • hasShadow boolean (optional) - Whether window should have a shadow. 窗口是否应该有阴影。Default is true.默认值为true
    • opacity number (optional) macOS Windows - Set the initial opacity of the window, between 0.0 (fully transparent) and 1.0 (fully opaque). 设置窗口的初始不透明度,介于0.0(完全透明)和1.0(完全不透明)之间。This is only implemented on Windows and macOS.这仅在Windows和macOS上实现。
    • darkTheme boolean (optional) - Forces using dark theme for the window, only works on some GTK+3 desktop environments. 强制使用深色主题作为窗口,仅适用于某些GTK+3桌面环境。Default is false.默认值为false
    • transparent boolean (optional) - Makes the window transparent. 使窗口透明Default is false. 默认值为falseOn Windows, does not work unless the window is frameless.在Windows上,除非窗口是无框架的,否则不起作用。
    • type string (optional) - The type of window, default is normal window. 窗口类型,默认为普通窗口。See more about this below.请参阅下面的详细信息。
    • visualEffectState string (optional) macOS - Specify how the material appearance should reflect window activity state on macOS. 指定材质外观应如何反映macOS上的窗口活动状态。Must be used with the vibrancy property. 必须与vibrancy属性一起使用。Possible values are:可能的值为:
      • followWindow - The backdrop should automatically appear active when the window is active, and inactive when it is not. 当窗口处于活动状态时,背景应自动显示为活动状态,而当不处于非活动状态时则显示为非活动状态。This is the default.这是默认设置。
      • active - The backdrop should always appear active.背景应始终显示为活动状态。
      • inactive - The backdrop should always appear inactive.背景应始终显示为非活动状态。
    • titleBarStyle string (optional) macOS Windows - The style of window title bar. 窗口标题栏的样式。Default is default. 默认值为defaultPossible values are:可能的值为:
      • default - Results in the standard title bar for macOS or Windows respectively.分别在macOS或Windows的标准标题栏中显示结果。
      • hidden - Results in a hidden title bar and a full size content window. 结果是一个隐藏的标题栏和一个全尺寸的内容窗口。On macOS, the window still has the standard window controls (“traffic lights”) in the top left. 在macOS上,窗口的左上角仍然有标准的窗口控件(“红绿灯”)。On Windows, when combined with titleBarOverlay: true it will activate the Window Controls Overlay (see titleBarOverlay for more information), otherwise no window controls will be shown.在Windows上,当与titleBarOverlay: true组合时将激活“窗口控件叠加”(有关详细信息,请参阅titleBarOverlay),否则将不会显示任何窗口控件。
      • hiddenInset macOS - Only on macOS, results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge.仅在macOS上,它会产生一个隐藏的标题栏,具有另一种外观,红绿灯按钮从窗口边缘稍微插入一些。
      • customButtonsOnHover macOS - Only on macOS, results in a hidden title bar and a full size content window, the traffic light buttons will display when being hovered over in the top left of the window. 只有在macOS上,才会出现一个隐藏的标题栏和一个全尺寸的内容窗口,当红绿灯按钮悬停在窗口的左上角时,就会显示。Note: This option is currently experimental.该选项目前处于试验阶段。
    • trafficLightPosition Point (optional) macOS - Set a custom position for the traffic light buttons in frameless windows.为无框车窗中的红绿灯按钮设置自定义位置。
    • roundedCorners boolean (optional) macOS - Whether frameless window should have rounded corners on macOS. 在macOS上,无框架窗口是否应该有圆角。Default is true. 默认值为trueSetting this property to false will prevent the window from being fullscreenable.将此属性设置为false将使窗口无法全屏显示。
    • fullscreenWindowTitle boolean (optional) macOS Deprecated - Shows the title in the title bar in full screen mode on macOS for hiddenInset titleBarStyle. 在macOS上以全屏模式在标题栏中显示hiddenInsettitleBarStyle的标题。Default is false.默认值为false
    • thickFrame boolean (optional) - Use WS_THICKFRAME style for frameless windows on Windows, which adds standard window frame. 对windows上的无框架窗口使用WS_THICKFRAME样式,这样可以添加标准窗框。Setting it to false will remove window shadow and window animations. 将其设置为false将删除窗口阴影和窗口动画。Default is true.默认值为true
    • vibrancy string (optional) macOS - Add a type of vibrancy effect to the window, only on macOS. 只在macOS上为窗口添加一种充满活力的效果。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, or under-page. 可以是appearance-basedlightdarktitlebarselectionmenupopoversidebarmedium-lightultra-darkheadersheetwindowhudfullscreen-uitooltipcontentunder-windowunder-pagePlease note that appearance-based, light, dark, medium-light, and ultra-dark are deprecated and have been removed in macOS Catalina (10.15).请注意,macOS Catalina(10.15)中不推荐使用appearance-basedlightdarkmedium-lightultra-dark
    • zoomToPageWidth boolean (optional) macOS - Controls the behavior on macOS when option-clicking the green stoplight button on the toolbar or by clicking the Window > Zoom menu item. 控制macOS上选项单击工具栏上的绿色红绿灯按钮或单击“窗口>缩放”菜单项时的行为。If true, 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. 如果为true,则缩放时窗口将增长到网页的首选宽度,如果为false,则窗口将缩放到屏幕的宽度。This will also affect the behavior when calling maximize() directly. 这也会影响直接调用maximize()时的行为。Default is false.默认值为false
    • tabbingIdentifier string (optional) macOS - Tab group name, allows opening the window as a native tab on macOS 10.12+. 选项卡组名称,允许在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 your app and window to receive the new-window-for-tab event.这还将一个原生的新选项卡按钮添加到窗口的选项卡栏中,并允许您的app和窗口接收new-window-for-tab事件。
    • webPreferences Object (optional) - Settings of web page's features.网页功能的设置。
      • devTools boolean (optional) - Whether to enable DevTools. 是否启用DevTools。If it is set to false, can not use BrowserWindow.webContents.openDevTools() to open DevTools. 如果设置为false,则不能使用BrowserWindow.webContents.openDevTools()打开DevTools。Default is true.默认值为true
      • nodeIntegration boolean (optional) - Whether node integration is enabled. 是否启用节点集成。Default is false.默认值为false
      • nodeIntegrationInWorker boolean (optional) - Whether node integration is enabled in web workers. 是否在web工作程序中启用节点集成。Default is false. 默认值为falseMore 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. 用于在子框架(如iframe和子窗口)中启用Node.js支持的实验选项。All your preloads will load for every iframe, you can use process.isMainFrame to determine if you are in the main frame or not.所有预加载都将为每个iframe加载,您可以使用process.isMainFrame来确定您是否在主框架中。
      • 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. 无论节点集成是打开还是关闭,此脚本都将始终可以访问节点API。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. 如果设置,这将对与窗口关联的渲染器进行沙盒处理,使其与Chromium OS级别的沙盒兼容,并禁用Node.js引擎。This is not the same as the nodeIntegration option and the APIs available to the preload script are more limited. 这与nodeIntegration选项不同,并且可用于预加载脚本的API受到更多限制。Read more about the option here.请在此处阅读有关该选项的更多信息。
      • session Session (optional) - Sets the session used by the page. 设置页面使用的会话。Instead of passing the Session object directly, you can also choose to use the partition option instead, which accepts a partition string. 您也可以选择使用partition选项,而不是直接传递Session对象,该选项接受分区字符串。When both session and partition are provided, session will be preferred. 当同时提供sessionpartition时,session将是首选。Default is the default session.默认为默认会话。
      • partition string (optional) - Sets the session used by the page according to the session's partition string. 根据会话的分区字符串设置页面使用的会话。If partition starts with persist:, the page will use a persistent session available to all pages in the app with the same partition. 如果partitionpersist:开头,则页面将使用可用于应用程序中具有相同partition的所有页面的持久会话。If there is no persist: prefix, the page will use an in-memory session. 如果没有persist:前缀,则页面将使用内存中的会话。By assigning the same partition, multiple pages can share the same session. 通过分配相同的partition,多个页面可以共享同一会话。Default is the default session.默认为默认会话。
      • zoomFactor number (optional) - The default zoom factor of the page, 3.0 represents 300%. 页面的默认缩放因子3.0表示300%Default is 1.0.默认值为1.0
      • javascript boolean (optional) - Enables JavaScript support. 启用JavaScript支持。Default is true.默认值为true
      • webSecurity boolean (optional) - When false, it will disable the same-origin policy (usually using testing websites by people), and set allowRunningInsecureContent to true if this options has not been set by user. 如果为false,它将禁用同源策略(通常由用户使用测试网站),如果用户尚未设置此选项,则将allowRunningInsecureContent设置为trueDefault is true.默认值为true
      • allowRunningInsecureContent boolean (optional) - Allow an https page to run JavaScript, CSS or plugins from http URLs. 允许https页面从http URL运行JavaScript、CSS或插件。Default is false.默认值为false
      • images boolean (optional) - Enables image support. 启用图像支持。Default is true.默认值为true
      • imageAnimationPolicy string (optional) - Specifies how to run image animations (E.g. GIFs). 指定如何运行图像动画(例如GIF)。Can be animate, animateOnce or noAnimation. 可以是animateanimateOncenoAnimationDefault is animate.默认值为animate
      • textAreasAreResizable boolean (optional) - Make TextArea elements resizable. 使TextArea元素的大小可调整。Default is true.默认值为true
      • webgl boolean (optional) - Enables WebGL support. 启用WebGL支持。Default is true.默认值为true
      • plugins boolean (optional) - Whether plugins should be enabled. 是否应启用插件。Default is false.默认值为false
      • experimentalFeatures boolean (optional) - Enables Chromium's experimental features. 启用Chromium的实验功能。Default is false.默认值为false
      • scrollBounce boolean (optional) macOS - Enables scroll bounce (rubber banding) effect on macOS. 在macOS上启用滚动反弹(橡皮筋)效果。Default is false.默认值为false
      • enableBlinkFeatures string (optional) - A list of feature strings separated by ,, like CSSVariables,KeyboardEventKey to enable. ,分隔的功能字符串列表,如要启用的CSSVariables,KeyboardEventKeyThe full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.支持的功能字符串的完整列表可以在RuntimeEnabledFeatures.json5文件中找到。
      • disableBlinkFeatures string (optional) - A list of feature strings separated by ,, like CSSVariables,KeyboardEventKey to disable. ,分隔的功能字符串列表,如要禁用的CSSVariables,KeyboardEventKeyThe full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.支持的功能字符串的完整列表可以在RuntimeEnabledFeatures.json5文件中找到。
      • defaultFontFamily Object (optional) - Sets the default font for the font-family.设置字体族的默认字体。
        • standard string (optional) - Defaults to Times New Roman.默认为Times New Roman
        • serif string (optional) - Defaults to Times New Roman.默认为Times New Roman
        • sansSerif string (optional) - Defaults to Arial.默认为Arial
        • monospace string (optional) - Defaults to Courier New.默认为Courier New
        • cursive string (optional) - Defaults to Script.默认为Script
        • fantasy string (optional) - Defaults to Impact.默认为Impact
      • defaultFontSize Integer (optional) - Defaults to 16.默认为16
      • defaultMonospaceFontSize Integer (optional) - Defaults to 13.默认为13
      • minimumFontSize Integer (optional) - Defaults to 0.默认为0
      • defaultEncoding string (optional) - Defaults to ISO-8859-1.默认为ISO-8859-1
      • backgroundThrottling boolean (optional) - Whether to throttle animations and timers when the page becomes background. 当页面成为背景时,是否限制动画和计时器。This also affects the Page Visibility API. 这也会影响页面可见性APIDefaults to true.默认为true
      • offscreen boolean (optional) - Whether to enable offscreen rendering for the browser window. 是否为浏览器窗口启用屏幕外渲染。Defaults to false. 默认为falseSee the offscreen rendering tutorial for more details.有关详细信息,请参阅屏幕外渲染教程
      • contextIsolation boolean (optional) - Whether to run Electron APIs and the specified preload script in a separate JavaScript context. 是否在单独的JavaScript上下文中运行Electron API和指定的preload脚本。Defaults to true. 默认为trueThe context that the preload script runs in will only have access to its own dedicated document and window globals, as well as its own set of JavaScript builtins (Array, Object, JSON, etc.), which are all invisible to the loaded content. preload脚本运行的上下文将只能访问其自己的专用documentwindow全局变量,以及其自己的一组JavaScript内置项(ArrayObjectJSON等),这些内容对加载的内容都是不可见的。The Electron API will only be available in the preload script and not the loaded page. Electron API将仅在preload脚本中可用,而不在加载的页面中可用。This option should be used when loading potentially untrusted remote content to ensure the loaded content cannot tamper with the preload script and any Electron APIs being used. 加载可能不受信任的远程内容时应使用此选项,以确保加载的内容不会篡改preload脚本和正在使用的任何Electron API。This option uses the same technique used by Chrome Content Scripts. 此选项使用与Chrome内容脚本相同的技术。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.您可以在开发工具中访问此上下文,方法是在Console选项卡顶部的组合框中选择“Electron Isolated context”条目。
      • webviewTag boolean (optional) - Whether to enable the <webview> tag. 是否启用<webview>标记Defaults to false. 默认为falseNote: The preload script configured for the <webview> will have node integration enabled when it is executed so you should ensure remote/untrusted content is not able to create a <webview> tag with a possibly malicious preload script. <webview>配置的preload脚本在执行时将启用节点集成,因此应确保远程/不受信任的内容无法使用可能恶意的preload剧本创建<webview>标记。You can use the will-attach-webview event on webContents to strip away the preload script and to validate or alter the <webview>'s initial settings.您可以在webContents上使用will-attach-webview事件来剥离preload脚本,并验证或更改<webview>的初始设置。
      • additionalArguments string[] (optional) - A list of strings that will be appended to process.argv in the renderer process of this app. 将在该应用程序的渲染器进程中附加到process.argv的字符串列表。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 is false.默认值为false
      • safeDialogsMessage string (optional) - The message to display when consecutive dialog protection is triggered. 触发连续对话保护时要显示的消息。If not defined the default message would be used, note that currently the default message is in English and not localized.如果未定义,将使用默认消息,请注意,当前默认消息为英语,未本地化。
      • disableDialogs boolean (optional) - Whether to disable dialogs completely. 是否完全禁用对话框。Overrides safeDialogs. 覆盖safeDialogsDefault is false.默认值为false
      • navigateOnDragDrop boolean (optional) - Whether dragging and dropping a file or link onto the page causes a navigation. 将文件或链接拖放到页面上是否会导致导航。Default is false.默认值为false
      • autoplayPolicy string (optional) - Autoplay policy to apply to content in the window, can be no-user-gesture-required, user-gesture-required, document-user-activation-required. 自动播放策略应用于窗口中的内容,可以是no-user-gesture-requireduser-gesture-requireddocument-user-activation-requiredDefaults to no-user-gesture-required.默认为no-user-gesture-required
      • disableHtmlFullscreenWindowResize boolean (optional) - Whether to prevent the window from resizing when entering HTML Fullscreen. 输入HTML全屏时是否阻止窗口调整大小。Default is false.默认值为false
      • accessibleTitle string (optional) - An alternative title string provided only to accessibility tools such as screen readers. 仅为屏幕阅读器等辅助功能工具提供的可选标题字符串。This string is not directly visible to users.用户无法直接看到此字符串。
      • spellcheck boolean (optional) - Whether to enable the builtin spellchecker. 是否启用内置拼写检查器。Default is true.默认值为true
      • enableWebSQL boolean (optional) - Whether to enable the WebSQL api. 是否启用WebSQL apiDefault is true.默认值为true
      • v8CacheOptions string (optional) - Enforces the v8 code caching policy used by blink. 强制执行blink使用的v8代码缓存策略。Accepted values are接受的值为
        • none - Disables code caching禁用代码缓存
        • code - Heuristic based code caching基于启发式的代码缓存
        • bypassHeatCheck - Bypass code caching heuristics but with lazy compilation绕过代码缓存启发式,但使用延迟编译
        • bypassHeatCheckAndEagerCompile - Same as above except compilation is eager. 和上面一样,只是急于编译。Default policy is code.默认策略为code
      • enablePreferredSizeMode boolean (optional) - Whether to enable preferred size mode. 是否启用首选尺寸模式。The preferred size is the minimum size needed to contain the layout of the document—without requiring scrolling. 首选大小是包含文档布局而不需要滚动所需的最小大小。Enabling this will cause the preferred-size-changed event to be emitted on the WebContents when the preferred size changes. 启用此选项将导致在首选大小更改时在WebContents上发出preferred-size-changed事件。Default is false.默认值为false
    • titleBarOverlay Object | Boolean (optional) - When using a frameless window in conjunction with win.setWindowButtonVisibility(true) on macOS or using a titleBarStyle so that the standard window controls ("traffic lights" on macOS) are visible, this property enables the Window Controls Overlay JavaScript APIs and CSS Environment Variables. 当在macOS上将无框窗口与win.setWindowButtonVisibility(true)结合使用,或使用titleBarStyle以使标准窗口控件(macOS上的“红绿灯”)可见时,此属性将启用窗口控件覆盖JavaScript APICSS环境变量Specifying true will result in an overlay with default system colors. 指定true将产生具有默认系统颜色的覆盖。Default is false.默认值为false
      • color String (optional) Windows - The CSS color of the Window Controls Overlay when enabled. 启用时窗口控件覆盖的CSS颜色。Default is the system color.默认为系统颜色。
      • symbolColor String (optional) Windows - The CSS color of the symbols on the Window Controls Overlay when enabled. 启用时,窗口控件覆盖上的符号的CSS颜色。Default is the system color.默认为系统颜色。
      • height Integer (optional) macOS Windows - The height of the title bar and Window Controls Overlay in pixels. 标题栏和窗口控件覆盖的高度(以像素为单位)。Default is system height.默认值为系统高度。

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/setSizeBrowserWindow的构造函数。

The possible values and behaviors of the type option are platform dependent. type选项的可能值和行为取决于平台。Possible values are:可能的值为:

  • On Linux, possible types are desktop, dock, toolbar, splash, notification.在Linux上,可能的类型是desktopdocktoolbarsplashnotification
  • On macOS, possible types are desktop, textured, panel.在MacOS上,可能的类型是desktoptexturedpanel
    • The textured type adds metal gradient appearance (NSWindowStyleMaskTexturedBackground).textured类型添加金属渐变外观(NSWindowStyleMaskTexturedBackground)。
    • The desktop 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 to receive input sparingly.请注意,桌面窗口不会接收焦点、键盘或鼠标事件,但您可以少量使用globalShortcut来接收输入。
    • The panel type enables the window to float on top of full-screened apps by adding the NSWindowStyleMaskNonactivatingPanel 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 toolbar.在Windows上,可能的类型是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 Event
  • title string
  • explicitSet boolean

Emitted when the document changed its title, calling event.preventDefault() will prevent the native window's title from changing. 当文档更改其标题时发出,调用event.preventDefault()将阻止本机窗口的标题更改。explicitSet is false when title is synthesized from file URL.当从文件URL合成标题时,explicitSetfalse

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. 它是在DOM的beforeunloadunload事件之前发出的。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 undefined would cancel the close. 在Electron中,返回除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 = handlerwindow.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. 请注意,使用此事件意味着即使showfalse,渲染器也将被视为“可见”并进行绘制。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 Event
  • newBounds Rectangle - Size the window is being resized to.调整窗口大小。
  • details Object
    • edge string - The edge of the window being dragged for resizing. 正在拖动以调整大小的窗口的边缘。Can be bottom, left, right, top-left, top-right, bottom-left or bottom-right.可以是bottomleftrighttop-lefttop-rightbottom-leftbottom-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 bottom, top, left, right, top-left, top-right, bottom-left, bottom-right.在Windows上,可能的值是bottomtopleftrighttop-lefttop-rightbottom-leftbottom-right
  • On macOS, possible values are bottom and right.在MacOS上,可能的值是bottomright
    • The value bottom 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 setBounds/setSize and setting the animate parameter to true will also emit this event once resizing has finished.在macOS上,使用setBounds/setSize调整窗口大小并将animate参数设置为true也会在调整大小完成后发出此事件。

Event: 'will-move' macOS Windows

Returns:返回:

  • event Event
  • newBounds Rectangle - Location the window is being moved to.将窗口移动到的位置。

Emitted before the window is moved. 在窗口移动之前发射。On Windows, calling event.preventDefault() will prevent the window from being moved.在Windows上,调用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 move.:在macOS上,此事件是move的别名。

Event: 'enter-full-screen'

Emitted when the window enters a full-screen state.当窗口进入全屏状态时发出。

Event: 'leave-full-screen'

Emitted when the window leaves a full-screen state.当窗口离开全屏状态时发出。

Event: '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 Event
  • isAlwaysOnTop boolean

Emitted when the window is set or unset to show always on top of other windows.当窗口被设置或取消设置为始终显示在其他窗口的顶部时发出。

Event: 'app-command' Windows Linux

Returns:返回:

  • event Event
  • command 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 Event
  • direction string

Emitted on 3-finger swipe. 三指轻扫时发射。Possible directions are up, right, down, left.可能的方向有uprightdownleft

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 System Preferences > Trackpad > More Gestures must be set to 'Swipe with two or three fingers'.大多数macOS触控板不再配置为允许这种滑动,因此为了使其正确发出,“系统首选项”>“触控板”>“更多手势”中的“在页面之间滑动”首选项必须设置为“用两个或三个手指滑动”。

Event: 'rotate-gesture' macOS

Returns:返回:

  • event Event
  • rotation 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. 旋转手势上最后发出的事件的值将始终为0Counter-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 Event
  • point 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)

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)

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 BrowserWindow instances of the entire Electron application.在整个Electron应用程序的所有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 true.在Linux上,setter是无操作的,尽管getter返回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 true.在Linux上,setter是无操作的,尽管getter返回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 true.在Linux上,setter是无操作的,尽管getter返回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 true.在Linux上,setter是无操作的,尽管getter返回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.强制关闭窗口,网页将不会发出unloadbeforeunload事件,该窗口也不会发出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)
  • RGBA
    • rgba(([\d]+),\s([\d]+),\s([\d]+),\s*([\d.]+))
      • e.g. rgba(255, 255, 255, 1.0)
  • HSL
    • hsl((-?[\d.]+),\s([\d.]+)%,\s([\d.]+)%)
      • e.g. hsl(200, 20%, 50%)
  • HSLA
    • hsla((-?[\d.]+),\s([\d.]+)%,\s([\d.]+)%,\s*([\d.]+))
      • e.g. hsla(200, 20%, 50%, 0.5)
  • Color name颜色名称
    • Options are listed in SkParseColor.cppSkParseColor.cpp中列出的选项
    • Similar to CSS Color Module Level 3 keywords, but case-sensitive.类似于CSS颜色模块级别3关键字,但区分大小写。
      • e.g. blueviolet or red

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 Rectangle
  • animate 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 Integer
  • height Integer
  • animate 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 Integer
  • height Integer
  • animate 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 Integer
  • height 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 Integer
  • height 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 true.在Linux上,总是返回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 true.在Linux上,总是返回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 true.在Linux上,总是返回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 true.在Linux上,总是返回true

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

  • flag boolean
  • level string (optional) macOS Windows - Values include normal, floating, torn-off-menu, modal-panel, main-menu, status, pop-up-menu, screen-saver, and dock (Deprecated). 值包括normalfloatingtorn-off-menumodal-panelmain-menustatuspop-up-menuscreen-saverdock(建议弃用)。The default is floating when flag is true. flagtrue时,默认值为floatingThe level is reset to normal when the flag is false. flagfalse时,level将重置为normalNote that from floating to status 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. 默认值为0Note 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 Integer
  • y Integer
  • animate boolean (optional) macOS

Moves window to x and y.将窗口移动到xy

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 Float
  • offsetX 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 resize event can be be used to listen to changes to tablet mode.此API返回窗口是否处于平板电脑模式,调整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上是CGWindowIDuint64_t),在Linux上是windowunsigned 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 HWND on Windows, NSView* on macOS, and Window (unsigned long) on Linux.句柄的本机类型在Windows上为HWND,在macOS上为NSView*,在Linux上为Windowunsigned long)。

win.hookWindowMessage(message, callback) Windows

  • message Integer
  • callback Function
    • wParam any - The wParam provided to the WndProc提供给WndProc的wParam
    • lParam any - The lParam provided to the WndProc提供给WndProc的lParam

Hooks a windows message. 挂接一条windows消息。The callback is called when the message is received in the WndProc.当在WndProc中接收到消息时,会调用callback

win.isWindowMessageHooked(message) Windows

  • message Integer

Returns 返回boolean - true or false depending on whether the message is hooked.truefalse,具体取决于消息是否被钩住。

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
  • options Object (optional)
    • httpReferrer (string | Referrer) (optional) - An HTTP Referrer URL.HTTP Referrer URL。HTTP引用URL
    • userAgent string (optional) - A user agent originating the request.发起请求的用户代理。
    • extraHeaders string (optional) - Extra headers separated by "\n"用“\n”分隔的额外标头
    • postData (UploadRawData | UploadFile)[] (optional)
    • baseURLForDataURL string (optional) - Base URL (with trailing path separator) for files to be loaded by the data URL. 数据URL要加载的文件的基本URL(带尾随路径分隔符)。This is needed only if the specified url is a data URL and needs to load other files.只有当指定的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).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 POST request with URL-encoded data by doing the following:您可以通过执行以下操作,使用带有URL编码数据的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
  • options Object (optional)
    • query Record<string, string> (optional) - Passed to url.format().已传递到url.format()
    • search string (optional) - Passed to url.format().已传递到url.format()
    • hash string (optional) - Passed to url.format().已传递到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).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
  • options Object (optional)
    • mode string Windows - Mode for the progress bar. 进度条的模式。Can be none, normal, indeterminate, error or paused.可以是nonenormalindeterminateerrorpaused

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 *.desktop file name to desktopName field in package.json. 在Linux平台上,仅支持Unity桌面环境,您需要在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. 被接受的值是nonenormalindeterminateerrorpausedIf 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 cleared如果此参数为null,则清除覆盖
  • 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

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:buttonsButton对象的数组:

  • Button Object
    • icon NativeImage - The icon showing in thumbnail toolbar.缩略图工具栏中显示的图标。
    • click Function
    • tooltip 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 strings: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. relaunchCommandrelaunchDisplayName必须始终设置在一起。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

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 key.设置后,菜单栏将仅在用户按下单个Alt键时显示。

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 key.如果菜单栏是自动隐藏的,用户仍然可以通过按下单个Alt键来打开菜单栏。

win.isMenuBarVisible() Windows Linux

Returns 返回boolean - Whether the menu bar is visible.菜单栏是否可见。

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

  • visible boolean
  • options Object (optional)
    • visibleOnFullScreen boolean (optional) macOS - Sets whether the window should be visible above fullscreen windows.设置窗口是否应在全屏窗口上方可见。
    • skipTransformProcessType boolean (optional) macOS - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. 默认情况下,调用setVisibleOnAllWorkspaces将在UIElementApplicationForegroundApplication之间转换流程类型,以确保正确的行为。However, this will hide the window and dock for a short time every time it is called. 但是,每次调用它时,这将隐藏窗口并停靠一小段时间。If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType.如果您的窗口已经是UIElementApplication类型,则可以通过将true传递给skipTransformProcessType来绕过此转换。

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
  • options Object (optional)
    • forward boolean (optional) macOS Windows - If true, forwards mouse move messages to Chromium, enabling mouse related events such as mouseleave. 如果为true,则将鼠标移动消息转发到Chromium,从而启用鼠标相关事件,如mouseleaveOnly used when ignore is true. 仅在ignoretrue时使用。If ignore is false, forwarding is always disabled regardless of this value.如果ignorefalse,则无论该值如何,都将始终禁用转发。

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设置为NSWindowSharingNoneOn Windows it calls SetWindowDisplayAffinity with WDA_EXCLUDEFROMCAPTURE. 在Windows上,它使用WDA_EXCLUDEFROMCAPTURE调用SetWindowDisplayAffinity。For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if WDA_MONITOR is applied capturing a black window.对于Windows 10 2004版及以上版本,窗口将完全从捕获中删除,较旧的Windows版本的行为就像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, or under-page. 可以是appearance-basedlightdarktitlebarselectionmenupopoversidebarmedium-lightultra-darkheadersheetwindowhudfullscreen-uitooltipcontentunder-windowunder-pageSee 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-basedlightdarkmedium-lightultra-dark已被弃用,并将在即将推出的macOS版本中删除。

win.setTrafficLightPosition(position) macOS

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. 指定nullundefined将清除触摸条。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 to win. browserView附加到winIf there are other BrowserViews 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。如果未附加,则返回nullThrows an error if multiple BrowserViews are attached.如果附加了多个BrowserView,则引发错误。

win.addBrowserView(browserView) Experimental

Replacement API for setBrowserView supporting work with multi browser views.setBrowserView的替换API支持使用多浏览器视图。

win.removeBrowserView(browserView) Experimental

win.setTopBrowserView(browserView) Experimental

Raises browserView above other BrowserViews attached to win. browserView提升到其他附加到winBrowserView之上。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.已使用addBrowserViewsetBrowserView附加的所有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

  • options Object
    • color String (optional) Windows - The CSS color of the Window Controls Overlay when enabled.启用时窗口控件覆盖的CSS颜色。
    • symbolColor String (optional) Windows - The CSS color of the symbols on the Window Controls Overlay when enabled.启用时,窗口控件覆盖上的符号的CSS颜色。
    • height Integer (optional) Windows - The height of the title bar and Window Controls Overlay in pixels.标题栏和窗口控件覆盖的高度(以像素为单位)。

On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay.在已启用“窗口控件覆盖”的窗口上,此方法会更新标题栏覆盖的样式。