BrowserWindow
Создавайте окна браузера и управляйте ими.
Process: Main
Этот модуль нельзя использовать до тех пор, пока событие ready в app не будет готово к использованию.
// В основном процессе.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
// Загрузка удаленного URL
win.loadURL('https://github.com')
// Или загрузка локального HTML файла
win.loadFile('index.html')
Настройки окна
Класс 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.
Использование события ready-to-show
При загрузке страницы, после отрисовки страницы будет происходить событие ready-to-show, которое будет происходить первый раз, если окно до этого еще не было показано. Окно, показанное после этого события, не будет иметь визуальной ступенчатой подгрузки:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => {
win.show()
})
Обычно это событие происходит после события did-finish-load. Однако, страницы, включающие в себя удаленные ресурсы, могут продолжать подгружаться после происхождения события did-finish-load.
Пожалуйста, обратите внимание, что использование этого события означает, что рендерер будет считаться "видимым" и отрисуется, даже если show является false. Это событие никогда не сработает, если вы используете paintWhenInitiallyHidden: false
Указание значения свойства backgroundColor
Для больших приложений событие ready-to-show может вызываться слишком поздно, что может замедлить приложение. В этом случае рекомендуется показать окно немедленно, и использовать backgroundColor, задающий цвет фона Вашего приложения:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ backgroundColor: '#2e2c29' })
win.loadURL('https://github.com')
Обратите внимание, что даже для приложений, использующих ready-to-show события, всё равно рекомендуется установить backgroundColor, чтобы придать приложению более естественный вид.
Приведем несколько примеров возможных значений backgroundColor:
const win = new BrowserWindow()
win.setBackgroundColor('hsl(230, 100%, 50%)')
win.setBackgroundColor('rgb(255, 145, 145)')
win.setBackgroundColor('#ff00a3')
win.setBackgroundColor('blueviolet')
For more information about these color types see valid options in win.setBackgroundColor.
Родительские и дочерние окна
С помощью параметра parent, Вы можете создавать дочерние окна:
const { BrowserWindow } = require('electron')
const top = new BrowserWindow()
const child = new BrowserWindow({ parent: top })
child.show()
top.show()
Окно child будет всегда показано поверх окна top.
Модальные окна
A modal window is a child window that disables parent window. To create a modal window, you have to set both the parent and modal options:
const { BrowserWindow } = require('electron')
const top = new BrowserWindow()
const child = new BrowserWindow({ parent: top, modal: true, show: false })
child.loadURL('https://github.com')
child.once('ready-to-show', () => {
child.show()
})
Видимость страниц
API видимости страниц работает следующим образом:
- На всех платформах состояние видимости отслеживает скрыто/уменьшено окно или нет.
- Кроме того, на macOS, состояние видимости также отслеживает состояние перекрытия окна. Если окно перекрыто (т.е. полностью покрыто) другим окном, состояние видимости будет
hidden. На других платформах состояние видимости будетhidden, только когда окно уменьшено или явно скрыто при помощиwin.hide(). - Если
BrowserWindowсоздано сshow: false, первоначальное состояние видимости будетvisible, несмотря на фактически скрытое окно. - Если
backgroundThrottlingотключено, состояние видимости останетсяvisible, даже если окно уменьшено, закрыто или скрыто.
Рекомендуется приостановить дорогостоящие операции, когда состояние видимости hidden, для того чтобы свести к минимуму потребление энергии.
Платформа заметок
- На macOS модальные окна будут отображены в виде страниц, прикрепленных к родительскому окну.
- На macOS дочерние окна будут находиться относительно родительского окна, во время передвижения родительского окна, тем временем на Windows и Linux дочерние окна не будут двигаться.
- На Linux тип модального окна будет поменян в
dialog. - На Linux многие среды рабочего стола не поддерживают скрытие модального окна.
Class: BrowserWindow extends BaseWindow
Создавайте окна браузера и управляйте ими.
Process: Main
BrowserWindow является EventEmitter.
Так создается новый экземпляр BrowserWindow с нативными свойствами, установленными в options.
[!WARNING] Electron's built-in classes cannot be subclassed in user code. For more information, see the FAQ.
new BrowserWindow([options])
События экземпляра
Объекты созданные с помощью new BrowserWindow имеют следующие события:
[!NOTE] Some events are only available on specific operating systems and are labeled as such.
Событие: 'page-title-updated'
Возвращает:
eventEventtitlestringexplicitSetboolean
Вызывается, когда документ меняет свой заголовок, вызов event.preventDefault() предотвратит изменение заголовка родного окна. explicitSet является false, когда заголовок синтезирован из url файла.
Событие: 'close'
Возвращает:
eventEvent
Происходит при закрытии окна. Оно происходит перед событиями beforeunload и unload в DOM. Вызов event.preventDefault() предотвратит закрытие.
Скорее всего, Вы захотите использовать обработчик beforeunload, чтобы решить, когда окно должно быть закрыто, который также будет вызываться, когда окно перезагружается. В Electron возврат любого значения, отличного от undefined, предотвратит закрытие. Например:
window.onbeforeunload = (e) => {
console.log('Я не хочу быть закрыт')
// В отличие от браузеров, пользователю будет показано окно с сообщением.
// Возврат любого значения незаметно отменит закрытие.
// Рекомендуется использовать dialog API, чтобы дать пользователям
// возможность подтвердить закрытие приложения.
e.returnValue = false
}
[!NOTE] There is a subtle difference between the behaviors of
window.onbeforeunload = handlerandwindow.addEventListener('beforeunload', handler). It is recommended to always set theevent.returnValueexplicitly, instead of only returning a value, as the former works more consistently within Electron.
Событие: 'closed'
происходит когда окно приложения закрыто. After you have received this event you should remove the reference to the window and avoid using it any more.
Event: 'query-session-end' Windows
Возвращает:
eventWindowSessionEndEvent
Emitted when a session is about to end due to a shutdown, machine restart, or user log-off. Calling event.preventDefault() can delay the system shutdown, though it’s generally best to respect the user’s choice to end the session. However, you may choose to use it if ending the session puts the user at risk of losing data.
Событие: 'session-end' Windows
Возвращает:
eventWindowSessionEndEvent
Emitted when a session is about to end due to a shutdown, machine restart, or user log-off. Once this event fires, there is no way to prevent the session from ending.
Событие: 'unresponsive'
Вызывается, когда страница "не отвечает".
Событие: 'responsive'
Происходит, когда страница, которая "не отвечала", снова реагирует.
Событие: 'blur'
Вызывается, когда окно теряет фокус.
Событие: 'focus'
Вызывается, когда на окне фокусируются.
Событие: 'show'
Происходит, когда отображается окно.
Событие: 'hide'
Происходит, когда окно спрятано.
Событие: 'ready-to-show'
Происходит, когда веб-страница была отрисована (пока не отображена) и окно может быть отображено без визуального мерцания.
Пожалуйста, обратите внимание, что использование этого события означает, что рендерер будет считаться "видимым" и отрисуется, даже если show является false. Это событие никогда не сработает, если вы используете paintWhenInitiallyHidden: false
Событие: 'maximize'
Происходит, когда окно увеличивается до предела.
Событие: 'unmaximize'
Происходит, когда окно выходит из увеличенного состояния.
Событие: 'minimize'
Происходит, когда окно было свернуто.
Событие: 'restore'
Происходит, когда окно восстанавливается из свернутого состояния.
Событие: 'will-resize' macOS Windows
Возвращает:
eventEventnewBoundsRectangle - Size the window is being resized to.- Объект
detailsedge(string) - The edge of the window being dragged for resizing. Can bebottom,left,right,top-left,top-right,bottom-leftorbottom-right.
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.
The possible values and behaviors of the edge option are platform dependent. Возможные значения:
- On Windows, possible values are
bottom,top,left,right,top-left,top-right,bottom-left,bottom-right. - On macOS, possible values are
bottomandright.- The value
bottomis used to denote vertical resizing. - The value
rightis used to denote horizontal resizing.
- The value
Событие: 'resize'
Происходит после того, как изменился размер окна.
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.
Событие: 'will-move' macOS Windows
Возвращает:
eventEventnewBoundsRectangle - 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.
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.
Событие: 'move'
Происходит, когда окно перемещено на новое место.
Event: 'moved' macOS Windows
Происходит единожды, когда окно перемещается в новое положение.
[!NOTE] On macOS, this event is an alias of
move.
Событие: 'enter-full-screen'
Происходит, когда окно переходит в полноэкранный режим.
Событие: 'leave-full-screen'
Происходит, когда окно выходит из полноэкранного режима.
Событие: 'enter-html-full-screen'
Происходит, когда окно входит в полноэкранный режим с помощью HTML API.
Событие: 'leave-html-full-screen'
Происходит, когда окно выходит из полноэкранного режима с помощью HTML API.
Событие: 'always-on-top-changed'
Возвращает:
eventEventisAlwaysOnTopboolean
Происходит, когда окно переключает режим отображения поверх всех окон.
Событие: 'app-command' Windows Linux
Возвращает:
eventEventcommandstring
Emitted when an App Command is invoked. Обычно это касается клавиатурных медиа-клавиш или команд браузера, а также кнопки "Назад", встроенной в некоторые мыши на Windows.
Команды в нижнем регистре, подчеркивание заменено на дефисы, а префикс APPCOMMAND_ обрезан. например APPCOMMAND_BROWSER_BACKWARD происходит как browser-backward.
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.on('app-command', (e, cmd) => {
// Navigate the window back when the user hits their mouse back button
if (cmd === 'browser-backward' && win.webContents.canGoBack()) {
win.webContents.goBack()
}
})
Следующие команды приложения явно поддерживаются на Linux:
browser-backwardbrowser-forward
Событие: 'swipe' macOS
Возвращает:
eventEventdirectionstring
Emitted on 3-finger swipe. Possible directions are up, right, down, left.
Метод, лежащий в основе этого события, создан для обработки событий смахивания на устаревших трекпадах в стиле macOS, где содержимое на экране нельзя переместить смахнув. Большинство трекпадов macOS по умолчанию не настроены под этот вид смахивания, поэтому для того чтобы правильно работал 'Переход между страницами смахиванием' перейдите в Системные настройки > Трекпад > Другие жесты и включите "Смахивание двумя или тремя пальцами".
Событие: 'rotate-gesture' macOS
Возвращает:
eventEventrotationFloat
Генерируется жестом вращения трекпада. Непрерывно генерируется до тех пор, пока жест поворота не будет завершен. Значение rotation при каждом выбросе - угол поворота в градусах, отсчитанный от последнего выброса. Последнее событие на жесте вращения всегда будет иметь значение 0. Значения вращения против часовой стрелки положительные, по часовой стрелке отрицательные.
Событие: 'sheet-begin' macOS
Происходит, когда окно открывает лист.
Событие: 'sheet-end' macOS
Происходит, когда окно закрыло лист.
Событие: 'new-window-for-tab' macOS
Происходит, когда нажимается нативная кнопка новой вкладки.
Event: 'system-context-menu' Windows Linux
Возвращает:
eventEventpointPoint - The screen coordinates where the context menu was triggered.
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.
Calling event.preventDefault() will prevent the menu from being displayed.
To convert point to DIP, use screen.screenToDipPoint(point).
Статические методы
Класс BrowserWindow имеет следующие статические методы:
BrowserWindow.getAllWindows()
Возвращает BrowserWindow[] - массив всех открытых окон браузера.
BrowserWindow.getFocusedWindow()
Возвращает BrowserWindow | null - окно, которое сфокусировано в этом приложении, иначе возвращает null.
BrowserWindow.fromWebContents(webContents)
webContentsWebContents
Возвращает BrowserWindow | null - окно, которое владеет объектом webContents, или имеет null если не содержит контент.
BrowserWindow.fromBrowserView(browserView) Deprecated
browserViewBrowserView
[!NOTE] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
Возвращает BrowserWindow - окно, которое владеет объектом webContents. If the given view is not attached to any window, returns null.
BrowserWindow.fromId(id)
idInteger
Возвращает BrowserWindow | null - окно с указанным id.
Свойства экземпляра
Объекты, созданные с помощью 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 Только чтение
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 представляющее уникальный идентификатор окна. Each ID is unique among all BrowserWindow instances of the entire Electron application.
win.tabbingIdentifier macOS Readonly
A string (optional) property that is equal to the tabbingIdentifier passed to the BrowserWindow constructor or undefined if none was set.
win.autoHideMenuBar Linux Windows
A boolean property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single Alt key.
Если панель меню уже видна, установка этого свойства в true не будет скрывать ее немедленно.
win.simpleFullScreen
A boolean property that determines whether the window is in simple (pre-Lion) fullscreen mode.
win.fullScreen
A boolean property that determines whether the window is in fullscreen mode.
win.focusable Windows macOS
A boolean property that determines whether the window is focusable.
win.visibleOnAllWorkspaces macOS Linux
A boolean property that determines whether the window is visible on all workspaces.
[!NOTE] Always returns false on Windows.
win.shadow
A boolean property that determines whether the window has a shadow.
win.menuBarVisible Windows Linux
A boolean property that determines whether the menu bar should be visible.
[!NOTE] If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single
Altkey.
win.kiosk
A boolean property that determines whether the window is in kiosk mode.
win.documentEdited macOS
A boolean property that specifies whether the window’s document has been edited.
The icon in title bar will become gray when set to 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.
win.title
A string property that determines the title of the native window.
[!NOTE] The title of the web page can be different from the title of the native window.
win.minimizable macOS Windows
Свойство boolean определяет, может ли окно быть вручную свернуто пользователем.
В Linux setter это невозможно, хотя getter возвращает true.
win.maximizable macOS Windows
Свойство boolean определяет, может ли окно быть вручную развернуто пользователем.
В Linux setter это невозможно, хотя getter возвращает true.
win.fullScreenable
Свойство boolean которое определяет, может ли кнопка увеличить/зумировать окно переключать полноэкранный режим или увеличивать до предела окно.
win.resizable
Свойство boolean определяет, может ли окно быть вручную изменено пользователем.
win.closable macOS Windows
Свойство boolean определяет, может ли окно быть вручную закрыто пользователем.
В Linux setter это невозможно, хотя getter возвращает true.
win.movable macOS Windows
Свойство boolean определяет, может ли окно перемещаться пользователем.
В Linux setter это невозможно, хотя getter возвращает true.
win.excludedFromShownWindowsMenu macOS
A boolean property that determines whether the window is excluded from the application’s Windows menu. По умолчанию 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. This string is not directly visible to users.
win.snapped Windows Readonly
A boolean property that indicates whether the window is arranged via Snap.
Методы экземпляра
Объекты, созданные с помощью new BrowserWindow, имеют следующие методы экземпляра:
[!NOTE] Some methods are only available on specific operating systems and are labeled as such.
win.destroy()
Принудительно закрывает окно, события unload и beforeunload не произойдут для веб-страниц, а событие close также не будет происходить для этого окна, но гарантировано, что событие closed будет происходить.
win.close()
Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the close event.
win.focus()
Фокусирует окно.
win.blur()
Убирает фокус с окна.
win.isFocused()
Возвращает boolean - сфокусировано окно или нет.
win.isDestroyed()
Возвращает boolean - уничтожено окно или нет.
win.show()
Показывает и фокусирует окно.
win.showInactive()
Показывает окно, но не фокусирует его.
win.hide()
Скрывает окно.
win.isVisible()
Возвращает boolean — Видимо ли окно пользователю в фоновом режиме.
win.isModal()
Возвращает boolean - модальное текущее окно или нет.
win.maximize()
Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already.
win.unmaximize()
Выходит из увеличенного состояния окна.
win.isMaximized()
Возвращает boolean - увеличено окно до предела или нет.
win.minimize()
Minimizes the window. On some platforms the minimized window will be shown in the Dock.
win.restore()
Восстанавливает окно из свернутого состояния до его предыдущего состояния.
win.isMinimized()
Возвращает boolean - свернуто окно или нет.
win.setFullScreen(flag)
flagboolean
Устанавливает окно в полноэкранный режим.
[!NOTE] On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the 'enter-full-screen' or 'leave-full-screen' events.
win.isFullScreen()
Возвращает boolean - в полноэкранном режиме окно или нет.
[!NOTE] On macOS, fullscreen transitions take place asynchronously. When querying for a BrowserWindow's fullscreen status, you should ensure that either the 'enter-full-screen' or 'leave-full-screen' events have been emitted.
win.setSimpleFullScreen(flag) macOS
flagboolean
Входит или покидает простой полноэкранный режим.
Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7).
win.isSimpleFullScreen() macOS
Возвращает boolean - в простом полноэкранном режиме окно или нет.
win.isNormal()
Возвращает boolean - в нормальном состоянии (не увеличено до предела, не свернуто, не в полноэкранном режиме) окно или нет.
win.setAspectRatio(aspectRatio[, extraSize])
aspectRatioFloat - The aspect ratio to maintain for some portion of the content view.extraSizeSize (optional) macOS - The extra size not to be included while maintaining the aspect ratio.
Это заставит окно поддерживать соотношение сторон. Дополнительный размер позволяет разработчику иметь пространство, указанное в пикселях, которое не входит в расчеты соотношения сторон. Этот метод уже учитывает разницу между размером окна и размером его содержимого.
Рассмотрим нормально окно в HD видео-плеером, и связанными с ним контроллерами. Возможно, на левом крае есть 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 }. Второй аргумент не заботится о том, где дополнительная ширина и высота находятся внутри содержимого вида, в котором они существуют. Суммируйте любые области дополнительной ширины и высоты, которые у Вас есть, в общем представлении содержимого.
The aspect ratio is not respected when window is resized programmatically with APIs like win.setSize.
To reset an aspect ratio, pass 0 as the aspectRatio value: win.setAspectRatio(0).
win.setBackgroundColor(backgroundColor)
backgroundColorstring - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type.
Examples of valid backgroundColor values:
- 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.cpp
- Similar to CSS Color Module Level 3 keywords, but case-sensitive.
- e.g.
bluevioletorred
- e.g.
Sets the background color of the window. See Setting backgroundColor.
win.previewFile(path[, displayName]) macOS
pathstring - абсолютный путь до файла, для предпросмотра в QuickLook. Это важно, так как QuickLook использует имя файла и расширение файла из пути, чтобы определить тип содержимого файла для открытия.displayNamestring (опционально) - имя файла, для отображения в модальном виде QuickLook. Это чисто визуально и не влияет на тип содержимого файла. По умолчаниюpath.
Uses Quick Look to preview a file at a given path.
win.closeFilePreview() macOS
Closes the currently open Quick Look panel.
win.setBounds(bounds[, animate])
boundsPartial<Rectangle>animateboolean (необязательно) macOS
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()
// Установить все свойства границы
win.setBounds({ x: 440, y: 225, width: 800, height: 600 })
// Установить одно свойство границы
win.setBounds({ width: 100 })
// { x: 440, y: 225, width: 100, height: 600 }
console.log(win.getBounds())
[!NOTE] On macOS, the y-coordinate value cannot be smaller than the Tray height. The tray height has changed over time and depends on the operating system, but is between 20-40px. Passing a value lower than the tray height will result in a window that is flush to the tray.
win.getBounds()
Returns Rectangle - The bounds of the window as Object.
[!NOTE] On macOS, the y-coordinate value returned will be at minimum the Tray height. For example, calling
win.setBounds({ x: 25, y: 20, width: 800, height: 600 })with a tray height of 38 means thatwin.getBounds()will return{ x: 25, y: 38, width: 800, height: 600 }.
win.getBackgroundColor()
Returns string - Gets the background color of the window in Hex (#RRGGBB) format.
[!NOTE] The alpha value is not returned alongside the red, green, and blue values.
win.setContentBounds(bounds[, animate])
boundsRectangleanimateboolean (необязательно) macOS
Меняет размеры и перемещает клиентскую область окна (например, веб-страницу) на заданные границы.
win.getContentBounds()
Returns Rectangle - The bounds of the window's client area as Object.
win.getNormalBounds()
Returns Rectangle - Contains the window bounds of the normal state
[!NOTE] Whatever the current state of the window (maximized, minimized or in fullscreen), this function always returns the position and size of the window in normal state. In normal state,
getBoundsandgetNormalBoundsreturn the same Rectangle.
win.setEnabled(enable)
enableboolean
Включает или выключает окно.
win.isEnabled()
Returns boolean - whether the window is enabled.
win.setSize(width, height[, animate])
widthIntegerheightIntegeranimateboolean (необязательно) 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.setContentSize(width, height[, animate])
widthIntegerheightIntegeranimateboolean (необязательно) macOS
Меняет размер клиентской области окна (например, веб-страница) на width и height.
win.getContentSize()
Возвращает Integer[] - содержит ширину и высоту клиентской области окна.
win.setMinimumSize(width, height)
widthIntegerheightInteger
Устанавливает минимальный размер окна на width и height.
win.getMinimumSize()
Возвращает Integer[] - содержит минимальную ширину и высоту окна.
win.setMaximumSize(width, height)
widthIntegerheightInteger
Устанавливает максимальный размер окна на width и height.
win.getMaximumSize()
Возвращает Integer[] - содержит максимальную ширину и высоту окна.
win.setResizable(resizable)
resizableboolean
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
movableboolean
Sets whether the window can be moved by user. On Linux does nothing.
win.isMovable() macOS Windows
Возвращает boolean - может пользователь перемещать окно или нет.
На Linux всегда возвращает true.
win.setMinimizable(minimizable) macOS Windows
minimizableboolean
Sets whether the window can be manually minimized by user. On Linux does nothing.
win.isMinimizable() macOS Windows
Returns boolean - Whether the window can be manually minimized by the user.
На Linux всегда возвращает true.
win.setMaximizable(maximizable) macOS Windows
maximizableboolean
Sets whether the window can be manually maximized by user. On Linux does nothing.
win.isMaximizable() macOS Windows
Возвращает boolean - может пользователь вручную увеличивать до предела окно или нет.
На Linux всегда возвращает true.
win.setFullScreenable(fullscreenable)
fullscreenableboolean
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
closableboolean
Sets whether the window can be manually closed by user. On Linux does nothing.
win.isClosable() macOS Windows
Возвращает boolean - может пользователь вручную закрывать окно или нет.
На Linux всегда возвращает true.
win.setHiddenInMissionControl(hidden) macOS
hiddenboolean
Sets whether the window will be hidden when the user toggles into mission control.
win.isHiddenInMissionControl() macOS
Returns boolean - Whether the window will be hidden when the user toggles into mission control.
win.setAlwaysOnTop(flag[, level][, relativeLevel])
flagbooleanlevelstring (опционально) macOS Windows - Значения включаютnormal,floating,torn-off-menu,modal-panel,main-menu,status,pop-up-menu,screen-saverи(Устарело). По умолчаниюdockfloating, когдаflagустановлен true.levelсбрасывается наnormal, когда флаг устанавливается false. Обратите внимание, что отfloatingдоstatusвключительно, окно находится под Dock в macOS и под панелью задач в Windows. Отpop-up-menuи выше отображается над Dock на macOS и выше панели задач на Windows. Смотрите документацию macOS для подробностей.relativeLevelInteger (опционально) macOS - количество слоев выше, чтобы установить окно относительно заданногоlevel. По умолчанию -0. Обратите внимание, что Apple не рекомендует устанавливать уровни выше, чем 1 верхнегоscreen-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.moveAbove(mediaSourceId)
mediaSourceIdstring - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0".
Moves window above the source window in the sense of z-order. If the mediaSourceId is not of type window or if the window does not exist then this method throws an error.
win.moveTop()
Перемещает окно на верх(z-order) независимо от фокуса
win.center()
Перемещает окно в центр экрана.
win.setPosition(x, y[, animate])
xIntegeryIntegeranimateboolean (необязательно) macOS
Moves window to x and y.
win.getPosition()
Возвращает Integer[] - содержит текущую позицию окна.
win.setTitle(title)
titlestring
Изменяет название нативного окна на title.
win.getTitle()
Возвращает string - название нативного окна.
[!NOTE] The title of the web page can be different from the title of the native window.
win.setSheetOffset(offsetY[, offsetX]) macOS
offsetYFloatoffsetXFloat (опционально)
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. Например:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
const toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
win.setSheetOffset(toolbarRect.height)
win.flashFrame(flag)
History
| Version(s) | Changes |
|---|---|
None |
|
flagboolean
Начинает или останавливает мерцание окна, чтобы привлечь внимание пользователя.
win.setSkipTaskbar(skip) macOS Windows
skipboolean
Не отображает окно в панели задач.
win.setKiosk(flag)
flagboolean
Enters or leaves kiosk mode.
win.isKiosk()
Возвращает boolean - в режиме киоска окно или нет.
win.isTabletMode() Windows
Returns boolean - Whether the window is in Windows 10 tablet mode.
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.
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.
win.getMediaSourceId()
Returns string - Window id in the format of DesktopCapturerSource's id. For example "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. other_id is used to identify web contents (tabs) so within the same top level window.
win.getNativeWindowHandle()
Возвращает Buffer - Определенный для платформы маркер окна.
Нативный тип маркера это HWND на Windows, NSView* на macOS и Window (unsigned long) на Linux.
win.hookWindowMessage(message, callback) Windows
messageIntegercallbackFunctionwParamBuffer - ThewParamprovided to the WndProclParamBuffer - ThelParamprovided to the WndProc
Hooks a windows message. The callback is called when the message is received in the WndProc.
win.isWindowMessageHooked(message) Windows
messageInteger
Возвращает boolean - true или false, в зависимости от того, какое сообщение было перехвачено.
win.unhookWindowMessage(message) Windows
messageInteger
Пропускает сообщение окна.
win.unhookAllWindowMessages() Windows
Пропускает все сообщения окна.
win.setRepresentedFilename(filename) macOS
filenamestring
Устанавливает путь к файлу, который представляет окно, и иконки файла, которая будет отображаться в строке заголовка окна.
win.getRepresentedFilename() macOS
Возвращает string - путь до файла, который представляет окно.
win.setDocumentEdited(edited) macOS
editedboolean
Определяет, был ли отредактирован документ окна, иконка в заголовке станет серой, когда установлено true.
win.isDocumentEdited() macOS
Возвращает boolean - был ли изменен документ окна.
win.focusOnWebView()
win.blurWebView()
win.capturePage([rect, opts])
rectRectangle (optional) - The bounds to captureoptsObject (optional)stayHiddenboolean (optional) - Keep the page hidden instead of visible. По умолчанию -false.stayAwakeboolean (optional) - Keep the system awake instead of allowing it to sleep. По умолчанию -false.
Возвращает Promise<NativeImage> - разрешается с NativeImage
Захватывает снимок страницы в границах rect. Пропустив rect, будет сделан захват всей видимой страницы. If the page is not visible, rect may be empty. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that stayHidden is set to true.
win.loadURL(url[, options])
urlstring
Возвращает Promise<void> - промис будет разрешен, когда страница завершит загрузку (см. did-finish-load), и отклоняет, если страница не удачно загрузилась (см. did-fail-load).
Same as webContents.loadURL(url[, options]).
url может быть удаленным адресом (например, http://) или путем до локального HTML-файла, используя протокол file://.
To ensure that file URLs are properly formatted, it is recommended to use Node's url.format method:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
const url = require('node:url').format({
protocol: 'file',
slashes: true,
pathname: require('node:path').join(__dirname, 'index.html')
})
win.loadURL(url)
Вы можете загрузить URL, используя POST-запрос с зашифрованными URL данными, сделав следующее:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.loadURL('http://localhost:8000/post', {
postData: [{
type: 'rawData',
bytes: Buffer.from('hello=world')
}],
extraHeaders: 'Content-Type: application/x-www-form-urlencoded'
})
win.loadFile(filePath[, options])
filePathstring
Возвращает Promise<void> - промис будет разрешен, когда страница завершит загрузку (см. 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. See the webContents docs for more information.
win.reload()
Тоже, что и webContents.reload.
win.setMenu(menu) Linux Windows
menuMenu | null
Устанавливает menu в меню окна.
win.removeMenu() Linux Windows
Удаляет меню окна.
win.setProgressBar(progress[, options])
progressDouble
Устанавливает значение прогресса на шкале прогресса. Valid range is [0, 1.0].
Удаляет индикатор прогресса, когда прогресс меньше 0; Изменяет в режим indeterminate, когда прогресс больше 1.
На платформе Linux поддерживается только рабочая среда Unity, Вам необходимо указать имя файла *.desktop в поле desktopName в package.json. По умолчанию будет предполагаться {app.name}.desktop.
На Windows режим может быть передан. Accepted values are none, normal, indeterminate, error, and paused. Если Вы вызовете setProgressBar без установленного режима (но со значением в пределах допустимого диапозона), будет предполагаться normal.
win.setOverlayIcon(overlay, description) Windows
overlayNativeImage | null - the icon to display on the bottom right corner of the taskbar icon. Если параметрnull, оверлей будет очищенdescriptionstring - описание, которое будет представлено для доступности чтения с экрана
Устанавливает 16x16 пиксельный оверлей поверх текущей иконки в панели задач, обычно используется для передачи какого-либо статуса приложения или пассивного уведомления пользователя.
win.invalidateShadow() macOS
Invalidates the window shadow so that it is recomputed based on the current window shape.
BrowserWindows that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation.
win.setHasShadow(hasShadow)
hasShadowboolean
Устанавливает, будет ли окно иметь тень.
win.hasShadow()
Возвращает boolean - был ли вызов успешным.
win.setOpacity(opacity) Windows macOS
opacitynumber - между 0.0 (полная прозрачность) и 1.0 (полная видимость)
Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the [0, 1] range.
win.getOpacity()
Возвращает number - между 0.0 (полная прозрачность) и 1.0 (полная видимость). On Linux, always returns 1.
win.setShape(rects) Windows Linux Экспериментально
rectsRectangle[] - Sets a shape on the window. Passing an empty list reverts the window to being rectangular.
Установка формы окна, которая определяет область в окне, где система разрешает отрисовку и взаимодействие пользователя. Вне данного региона ни один пиксель не отрисуется и ни одно событие мыши не будет зарегистрировано. Вне региона события мыши не будут получены этим окном, но будет передаваться чему-либо позади окна.
win.setThumbarButtons(buttons) Windows
buttonsThumbarButton[]
Возвращает boolean - успешно ли добавлены кнопки
Добавляет панель миниатюр, с определенным набором кнопок, на слой кнопок в изображении эскиза окна в панели задач. Возвращает объект boolean, который указывает успешно ли добавлена панель миниатюр.
Количество кнопок в панели миниатюр не должно быть больше, чем 7, из-за ограничений. После установки панели миниатюр, панель не может быть удалена, из-за ограничений платформы. Но Вы можете вызвать метод с пустым массивом, чтобы убрать кнопки.
buttons является массивом объектов Button:
- Объект
ButtoniconNativeImage - The icon showing in thumbnail toolbar.clickFunctiontooltipstring (опционально) - текст всплывающей подсказки на кнопке.flagsstring[] (опционально) - Управление конкретными состояниями и поведением кнопки. По умолчанию, является['enabled'].
flags — это массив, который может включать следующие string:
enabled- кнопка активна и доступна пользователю.disabled- Кнопка отключена. Она присутствует, но имеет неактивное визуальное состояние и не будет реагировать на действия пользователя.dismissonclick- когда кнопка нажата, окно панели миниатюр закрывается немедленно.nobackground- не рисует границы кнопок, использует только изображение.hidden- кнопка не отображается пользователю.noninteractive- Кнопка включена, но не интерактивна; ни одно состояние кнопки не отображается. Это значение предназначено для случаев, когда кнопка используется в уведомлении.
win.setThumbnailClip(region) Windows
regionRectangle - Region of the window
Устанавливает область окна, которая будет показана в панели миниатюр, при наведении мыши на окно в панели задач. Вы можете сбросить панель миниатюры, чтобы показывалось окно полностью, указав пустую область: { x: 0, y: 0, width: 0, height: 0 }.
win.setThumbnailToolTip(toolTip) Windows
toolTipstring
Устанавливает всплывающую подсказку, которая будет отображена, при наведении мыши на панель миниатюры окна в панели задач.
win.setAppDetails(options) Windows
Устанавливает свойства для кнопки окна на панели задач.
relaunchCommand and relaunchDisplayName must always be set together. If one of those properties is not set, then neither will be used.
win.setAccentColor(accentColor) Windows
accentColorboolean | string - The accent color for the window. By default, follows user preference in System Settings.
Sets the system accent color and highlighting of active window border.
The accentColor parameter accepts the following values:
- Color string - Sets a custom accent color using standard CSS color formats (Hex, RGB, RGBA, HSL, HSLA, or named colors). Alpha values in RGBA/HSLA formats are ignored and the color is treated as fully opaque.
true- Uses the system's default accent color from user preferences in System Settings.false- Explicitly disables accent color highlighting for the window.
Примеры:
const win = new BrowserWindow({ frame: false })
// Set red accent color.
win.setAccentColor('#ff0000')
// RGB format (alpha ignored if present).
win.setAccentColor('rgba(255,0,0,0.5)')
// Use system accent color.
win.setAccentColor(true)
// Disable accent color.
win.setAccentColor(false)
win.getAccentColor() Windows
Returns string | boolean - the system accent color and highlighting of active window border in Hex RGB format.
If a color has been set for the window that differs from the system accent color, the window accent color will be returned. Otherwise, a boolean will be returned, with true indicating that the window uses the global system accent color, and false indicating that accent color highlighting is disabled for this window.
win.showDefinitionForSelection() macOS
Тоже, что и webContents.showDefinitionForSelection().
win.setIcon(icon) Windows Linux
iconNativeImage | string
Меняет иконку окна.
win.setWindowButtonVisibility(visible) macOS
visibleboolean
Устанавливает, должны ли быть видны кнопки контроля окна.
win.setAutoHideMenuBar(hide) Windows Linux
hideboolean
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() Windows Linux
Возвращает boolean - прячет ли меню себя автоматически.
win.setMenuBarVisibility(visible) Windows Linux
visibleboolean
Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single Alt key.
win.isMenuBarVisible() Windows Linux
Возвращает boolean - видна ли панель меню.
win.isSnapped() Windows
Returns boolean - whether the window is arranged via Snap.
The window is snapped via buttons shown when the mouse is hovered over window maximize button, or by dragging it to the edges of the screen.
win.setVisibleOnAllWorkspaces(visible[, options]) macOS Linux
visibleboolean
Устанавливает видимость окна на всех рабочих местах.
[!NOTE] This API does nothing on Windows.
win.isVisibleOnAllWorkspaces() macOS Linux
Возвращает boolean - видно ли окно на всех рабочих местах.
[!NOTE] This API always returns false on Windows.
win.setIgnoreMouseEvents(ignore[, options])
ignoreлогическое значение
Включает для окна игнорирование событий от мыши.
Все события мыши, произошедшие в этом окне, будут переданы окну позади этого окна, но, если это окно сфокусировано, оно все еще будет получать события клавиатуры.
win.setContentProtection(enable) macOS Windows
enableboolean
Предотвращает захват содержимого окна другими приложениями.
On Windows, it calls SetWindowDisplayAffinity with WDA_EXCLUDEFROMCAPTURE. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if WDA_MONITOR is applied capturing a black window.
On macOS, it sets the NSWindow's sharingType to NSWindowSharingNone. Unfortunately, due to an intentional change in macOS, newer Mac applications that use ScreenCaptureKit will capture your window despite win.setContentProtection(true). See here.
win.isContentProtected() macOS Windows
Returns boolean - whether or not content protection is currently enabled.
win.setFocusable(focusable) macOS Windows
focusableboolean
Меняет, может ли окно быть сфокусировано.
На macOS он не снимает фокус с окна.
win.isFocusable() macOS Windows
Returns boolean - Whether the window can be focused.
win.setParentWindow(parent)
parentBrowserWindow | null
Устанавливает parent как родителя текущего окна, передав null превратит текущее окно в окно верхнего уровня.
win.getParentWindow()
Возвращает BrowserWindow | null - родительское окно или null, если нет родителя.
win.getChildWindows()
Возвращает BrowserWindow[] - все дочерние окна.
win.setAutoHideCursor(autoHide) macOS
autoHideboolean
Контролирует скрытие курсора при вводе текста.
win.selectPreviousTab() macOS
Выбирает предыдущую вкладку, когда нативные вкладки включены и в окне присутствуют другие вкладки.
win.selectNextTab() macOS
Выбирает следующую вкладку, когда нативные вкладки включены и в окне присутствуют другие вкладки.
win.showAllTabs() macOS
Shows or hides the tab overview when native tabs are enabled.
win.mergeAllWindows() macOS
Объединяет все окна в одно окно с множественными вкладками, когда нативные вкладки включены и в присутствуют открытые окна больше, чем 1.
win.moveTabToNewWindow() macOS
Перемещает текущую вкладку в новое окно, если нативные вкладки включены и присутствует больше, чем одна вкладка, в текущем окне.
win.toggleTabBar() macOS
Переключает видимость вкладки, если включены нативные вкладки и присутствует только одна вкладка в текущем окне.
win.addTabbedWindow(browserWindow) macOS
browserWindowBrowserWindow
Добавляет окно, как вкладку, в это окно, после вкладки экземпляра окна.
win.setVibrancy(type[, options]) macOS
typestring | null - Can betitlebar,selection,menu,popover,sidebar,header,sheet,window,hud,fullscreen-ui,tooltip,content,under-window, orunder-page. Смотрите документацию macOS для подробностей.
Adds a vibrancy effect to the browser window. Passing null or an empty string will remove the vibrancy effect on the window. The animationDuration parameter only animates fading in or fading out the vibrancy effect. Animating between different types of vibrancy is not supported.
win.setBackgroundMaterial(material) Windows
- строка
materialauto- Let the Desktop Window Manager (DWM) automatically decide the system-drawn backdrop material for this window. This is the default.none- Don't draw any system backdrop.mica- Draw the backdrop material effect corresponding to a long-lived window.acrylic- Draw the backdrop material effect corresponding to a transient window.tabbed- Draw the backdrop material effect corresponding to a window with a tabbed title bar.
This method sets the browser window's system-drawn background material, including behind the non-client area.
See the Windows documentation for more details.
[!NOTE] This method is only supported on Windows 11 22H2 and up.
win.setWindowButtonPosition(position) macOS
positionPoint | null
Set a custom position for the traffic light buttons in frameless window. Passing null will reset the position to default.
win.getWindowButtonPosition() macOS
Returns Point | null - The custom position for the traffic light buttons in frameless window, null will be returned when there is no custom position.
win.setTouchBar(touchBar) macOS
touchBarTouchBar | null
Устанавливает слой сенсорной панели для текущего окна. Указав null или undefined очистит сенсорную панель. This method only has an effect if the machine has a touch bar.
[!NOTE] The TouchBar API is currently experimental and may change or be removed in future Electron releases.
win.setBrowserView(browserView) Experimental Deprecated
browserViewBrowserView | null - AttachbrowserViewtowin. If there are otherBrowserViews attached, they will be removed from this window.
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.getBrowserView() Experimental Deprecated
Returns BrowserView | null - The BrowserView attached to win. Returns null if one is not attached. Throws an error if multiple BrowserViews are attached.
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.addBrowserView(browserView) Experimental Deprecated
browserViewBrowserView
Заменяет метод setBrowserView, для поддержки работы с множественными видами браузера.
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.removeBrowserView(browserView) Experimental Deprecated
browserViewBrowserView
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.setTopBrowserView(browserView) Experimental Deprecated
browserViewBrowserView
Raises browserView above other BrowserViews attached to win. Throws an error if browserView is not attached to win.
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.getBrowserViews() Experimental Deprecated
Returns BrowserView[] - a sorted by z-index array of all BrowserViews that have been attached with addBrowserView or setBrowserView. The top-most BrowserView is the last element of the array.
[!WARNING] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
win.setTitleBarOverlay(options) Windows Linux
On a window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay.
On Linux, the symbolColor is automatically calculated to have minimum accessible contrast to the color if not explicitly set.