Перейти к основному содержанию

BrowserWindowConstructorOptions Object

  • width Integer (опционально) - ширина окна в пикселях. По умолчанию 800.
  • height Integer (опционально) - высота окна в пикселях. По умолчанию 600.
  • x Integer (опционально) - (обязателен, если используется y) отступ окна слева от экрана. Значение по умолчанию центрирует окно.
  • y Integer (опционально) - (обязателен, если используется x) отступ окна сверху от экрана. Значение по умолчанию центрирует окно.
  • useContentSize boolean (опционально) - width и height могут использоваться как размеры веб-страницы, это значит, что актуальный размер окна будет включать размер фрейма и будет немного крупнее. По умолчанию - false.
  • center boolean (опционально) - показывает окно в центре экрана. По умолчанию - false.
  • minWidth Integer (опционально) - минимальная ширина окна. По умолчанию 0.
  • minHeight Integer (опционально) - минимальная высота окна. По умолчанию 0.
  • maxWidth Integer (опционально) - максимальная ширина окна. По умолчанию нет ограничения.
  • maxHeight Integer (опционально) - максимальная высота окна. По умолчанию нет ограничения.
  • resizable boolean (опционально) - будет ли окно изменять размеры. По умолчанию - true.
  • movable boolean (опционально) macOS Windows - Возможно ли перемещение окна. Не реализовано в Linux. По умолчанию - true.
  • minimizable boolean (опционально) macOS Windows - Можно ли свернуть окно. Не реализовано в Linux. По умолчанию - true.
  • maximizable boolean (опционально) macOS Windows - Можно ли развернуть окно. Не реализовано в Linux. По умолчанию - true.
  • closable boolean (опционально) macOS Windows - Можно ли закрыть окно. Не реализовано в Linux. По умолчанию - true.
  • focusable boolean (опционально) - может ли быть окно в фокусе. По умолчанию - true. На Windows настройка focusable: false также подразумевает настройку skipTaskbar: true. На Linux настройка focusable: false прекращает взаимодействие окна с оконным менеджером, на Windows же всегда остается поверх всех рабочих областей.
  • alwaysOnTop boolean (опционально) - будет ли окно всегда оставаться поверх других окон. По умолчанию - false.
  • fullscreen boolean (опционально) - будет ли окно показываться во весь экран. Когда явно установлено false, на macOS кнопка полноэкранного режима будет скрыта или отключена. По умолчанию - false.
  • fullscreenable boolean (опционально) - может ли окно быть в полноэкранном режиме. На macOS также кнопка увеличить/зумировать должна переключить в полноэкранный режим или увеличить окно. По умолчанию - true.
  • simpleFullscreen boolean (optional) macOS - Use pre-Lion fullscreen on macOS. По умолчанию - false.
  • skipTaskbar boolean (optional) macOS Windows - Whether to show the window in taskbar. По умолчанию - false.
  • hiddenInMissionControl boolean (optional) macOS - Whether window should be hidden when the user toggles into mission control.
  • kiosk boolean (optional) - Whether the window is in kiosk mode. По умолчанию - false.
  • title string (опционально) - заголовок окна по умолчанию. По умолчанию "Electron". Если HTML-тег <title> определен в HTML-файле, загруженном с помощью loadURL(), то это свойство будет игнорироваться.
  • icon (NativeImage | string) (optional) - The window icon. На Windows рекомендуется использовать иконки ICO, чтобы получить лучший визуальный эффект, Вы также можете оставить неопределенным, чтобы был использован значок исполняемого файла.
  • show boolean (необязательно) - Будет ли показано окно, когда будет создано. По умолчанию - true.
  • paintWhenInitiallyHidden boolean (опционально) - Должен ли рендерер быть активным, когда show равен false и он только что создан. Для document.visibilityState для корректной работы при первой загрузке с show: false необходимо установить значение false. Установка этого в false приведёт к тому, что события ready-to-show не будут запускаться. По умолчанию - true.
  • frame boolean (optional) - Specify false to create a frameless window. По умолчанию - true.
  • parent BrowserWindow (optional) - Specify parent window. По умолчанию null.
  • modal boolean (optional) - Whether this is a modal window. This only works when the window is a child window. По умолчанию - false.
  • acceptFirstMouse boolean (optional) macOS - Whether clicking an inactive window will also click through to the web contents. По умолчанию false в macOS. This option is not configurable on other platforms.
  • disableAutoHideCursor boolean (optional) - Whether to hide cursor when typing. По умолчанию - false.
  • autoHideMenuBar boolean (optional) - Auto hide the menu bar unless the Alt key is pressed. По умолчанию - 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. По умолчанию - false.
  • backgroundColor string (optional) - The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if transparent is set to true. По умолчанию - #FFF (белый). See win.setBackgroundColor for more information.
  • hasShadow boolean (optional) - Whether window should have a shadow. По умолчанию - true.
  • opacity number (optional) macOS Windows - Set the initial opacity of the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This is only implemented on Windows and macOS.
  • darkTheme boolean (optional) - Forces using dark theme for the window, only works on some GTK+3 desktop environments. По умолчанию - false.
  • transparent boolean (опционально) - делает окно прозрачным. По умолчанию - false. В 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. Must be used with the vibrancy property. Возможные значения:
    • 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 строка (необязательно) macOS Windows - Стиль строки заголовка окна. По умолчанию default. Возможные значения:
    • по умолчанию - результаты в стандартной строке заголовка для macOS или Windows, соответственно.
    • скрытые - результаты в скрытой строке заголовка и окно полного размера. На macOS в левом верхнем углу окна все еще есть стандартное управление окном ("светофоры"). На Windows, когда в сочетании с заголовком titleBarOverlay: true он активирует Overlay Window Controls Overlay (см. 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.
    • 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. Примечание: Этот параметр в настоящее время экспериментален.
  • 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. По умолчанию - true. Setting this property to false will prevent the window from being fullscreenable.
  • thickFrame boolenan (необязательно) - Использовать стиль WS_THICKFRAME на окнах с отсутствием рамок на Windows, добавляющий стандартные рамки окна. Установив значение false, тень окна и анимация окна будут удалены. По умолчанию - true.
  • vibrancy string (optional) macOS - Add a type of vibrancy effect to the window, only on macOS. Can be appearance-based, titlebar, selection, menu, popover, sidebar, header, sheet, window, hud, fullscreen-ui, tooltip, content, under-window, or under-page.
  • backgroundMaterial string (optional) Windows - Set the window's system-drawn background material, including behind the non-client area. Can be auto, none, mica, acrylic or tabbed. See win.setBackgroundMaterial for more information.
  • 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. 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. This will also affect the behavior when calling maximize() directly. По умолчанию - false.
  • tabbingIdentifier string (optional) macOS - Tab group name, allows opening the window as a native tab. 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.
  • webPreferences WebPreferences (optional) - Settings of web page's features.
    • devTools boolean (опционально) - включает инструменты разработчика. Если значение false, нельзя будет использовать BrowserWindow.webContents.openDevTools(), чтобы открыть инструменты разработчика. По умолчанию - true.
    • nodeIntegration boolean (optional) - Whether node integration is enabled. По умолчанию - false.
    • nodeIntegrationInWorker boolean (опционально) - включает интеграцию NodeJS в веб-воркерах. По умолчанию - false. Больше об этом можно найти в многопоточности.
    • nodeIntegrationInSubFrames boolean (опционально) - экспериментальная опция для включения поддержки NodeJS в подфреймах, таких как iframes и дочерних окнах. Все Ваши предварительные загрузки будут загружены для каждого iframe, Вы можете использовать process.isMainFrame, чтобы определить в главном фрейме Вы или нет.
    • preload string (опционально) - Определяет скрипт, который будет загружен до других скриптов загружаемых в странице. Этот скрипт будет всегда иметь доступ к API NodeJS, вне зависимости включена или выключена интеграция NodeJS. Значение должно быть абсолютным путем к файлу скрипта. Когда интеграция NodeJS отключена, предварительно загруженный скрипт может повторно ввести глобальные символы NodeJS в глобальную область. Посмотреть пример здесь.
    • sandbox boolean (опционально) - если установлено true, то в окне будет запущена песочница, что делает ее совместимой с песочницей Chromium на уровне операционной системы, и отключает движок NodeJS. Это не тоже самое, что параметр nodeIntegration, доступные API для предзагруженных скриптов более ограничены. Узнать больше об этой опции можно здесь.
    • session Session (опционально) - устанавливает сессию, которая используется страницей. Вместо передачи экземпляр Session напрямую, вместо этого Вы можете также выбрать использование опции partition, которая принимает строку раздела. Когда оба session и partition определены, session будет предпочтительней. По умолчанию используется сессия по умолчанию.
    • partition string (опционально) - устанавливает сессию, используемую на странице в соответствии со строкой раздела сессии. Если partition начинается с persist:, страница будет использовать постоянную сессию, которая доступна всем страницам в приложении с тем же разделом. Если нет префикса persist:, страница будет использовать сессию в памяти. При присваивании одинакового раздела, разные страницы могут иметь одинаковую сессию. По умолчанию используется сессия по умолчанию.
    • zoomFactor number (optional) - The default zoom factor of the page, 3.0 represents 300%. По умолчанию 1.0.
    • javascript boolean (optional) - Enables JavaScript support. По умолчанию - true.
    • webSecurity boolean (опционально) - Когда false, отключается политика same-origin (обычно используется при тестировании вебсайтов людьми), и устанавливается allowRunningInsecureContent в true, если параметр не был установлен пользователем. По умолчанию - true.
    • allowRunningInsecureContent boolean (optional) - Allow an https page to run JavaScript, CSS or plugins from http URLs. По умолчанию - false.
    • images boolean (optional) - Enables image support. По умолчанию - true.
    • imageAnimationPolicy string (optional) - Specifies how to run image animations (E.g. GIFs). Can be animate, animateOnce or noAnimation. По умолчанию animate.
    • textAreasAreResizable boolean (optional) - Make TextArea elements resizable. Default is true.
    • webgl boolean (optional) - Enables WebGL support. По умолчанию - true.
    • plugins boolean (optional) - Whether plugins should be enabled. По умолчанию - false.
    • experimentalFeatures boolean (optional) - Enables Chromium's experimental features. По умолчанию - false.
    • scrollBounce boolean (optional) macOS - Enables scroll bounce (rubber banding) effect on macOS. По умолчанию - false.
    • enableBlinkFeatures string (опционально) - список строк функций, разделенных запятой, которые нужно включить, например CSSVariables,KeyboardEventKey. Полный список поддерживаемых возможностей можно найти в файле RuntimeEnabledFeatures.json5.
    • disableBlinkFeatures string (опционально) - Список функциональных возможностей для выключения, разделяются ',', например CSSVariables,KeyboardEventKey. Полный список поддерживаемых возможностей можно найти в файле RuntimeEnabledFeatures.json5.
    • defaultFontFamily Object (optional) - Sets the default font for the font-family.
      • standard string (опционально) - По умолчанию Times New Roman.
      • serif string (опционально) - по умолчанию Times New Roman.
      • sansSerif string (опционально) - По умолчанию Arial.
      • monospace string (опционально) - По умолчанию Courier New.
      • cursive string (опционально) - По умолчанию Script.
      • fantasy string (опционально) - По умолчанию Impact.
      • math string (optional) - Defaults to Latin Modern Math.
    • defaultFontSize Integer (опционально) - По умолчанию 16.
    • defaultMonospaceFontSize Integer (опционально) - По умолчанию 13.
    • minimumFontSize Integer (опционально) - По умолчанию 0.
    • defaultEncoding string (опционально) - По умолчанию ISO-8859-1.
    • backgroundThrottling boolean (опционально) - Отключать ли анимацию и таймеры, когда страница становится фоновой. Это также влияет на API видимости страницы. When at least one webContents displayed in a single browserWindow has disabled backgroundThrottling then frames will be drawn and swapped for the whole window and other webContents displayed by it. По умолчанию true.
    • offscreen boolean (опционально) - Включает отрисовку окна браузера вне экрана. По умолчанию false. Смотрите руководство отрисовки вне экрана для подробной информации.
    • contextIsolation boolean (опционально) - Запускать или нет API Electron и определенный скрипт preload в отдельном JavaScript-контексте. По умолчанию true. The 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. The Electron API will only be available in the preload script and not the loaded page. This option should be used when loading potentially untrusted remote content to ensure the loaded content cannot tamper with the preload script and any Electron APIs being used. This option uses the same technique used by Chrome Content Scripts. You can access this context in the dev tools by selecting the 'Electron Isolated Context' entry in the combo box at the top of the Console tab.
    • webviewTag boolean (опционально) - Включить ли <webview> tag. По умолчанию false. Примечание: Cкрипт preload, настроенный для <webview>, при запуске будет иметь интеграцию NodeJS, так что Вы должны убедиться, что удаленный/непроверенный контент не сможет создавать тег <webview> с возможно вредоносным скриптом preload. Вы можете использовать событие will-attach-webview на webContents, чтобы отключить скрипт preload и проверить или изменить начальные настройки <webview>.
    • additionalArguments string[] (optional) - A list of strings that will be appended to process.argv in the renderer process of this app. Useful for passing small bits of data down to renderer process preload scripts.
    • safeDialogs boolean (optional) - Whether to enable browser style consecutive dialog protection. По умолчанию - false.
    • safeDialogsMessage string (опционально) - Сообщение, которое будет отображено, когда сработает последовательная защита диалогов. Если не определено, будет использовано сообщение по умолчанию, обратите внимание, что текущее сообщение по умолчанию на английском и не переведено.
    • disableDialogs boolean (optional) - Whether to disable dialogs completely. Overrides safeDialogs. По умолчанию - false.
    • navigateOnDragDrop boolean (optional) - Whether dragging and dropping a file or link onto the page causes a navigation. По умолчанию - false.
    • autoplayPolicy string (опционально) - политика автовоспроизведения для применения к содержимому в окне, может быть no-user-gesture-required, user-gesture-required или document-user-activation-required. По умолчанию no-user-gesture-required.
    • disableHtmlFullscreenWindowResize boolean (optional) - Whether to prevent the window from resizing when entering HTML Fullscreen. Default is 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. По умолчанию - true.
    • enableWebSQL boolean (optional) - Whether to enable the WebSQL api. По умолчанию - true.
    • v8CacheOptions string (optional) - Enforces the v8 code caching policy used by blink. 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.
    • 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. По умолчанию - 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. Specifying true will result in an overlay with default system colors. По умолчанию - false.
    • color String (optional) Windows - The CSS color of the Window Controls Overlay when enabled. Default is the system color.
    • symbolColor String (optional) Windows - The CSS color of the symbols on the Window Controls Overlay when enabled. 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.

Когда установлен минимальный или максимальный размер окна, при помощи minWidth/maxWidth/minHeight/maxHeight, это ограничивает только пользователей. Это не позволит Вам установить размер, который не будет следовать ограничениям размера, в setBounds/setSize или в конструкторе BrowserWindow.

The possible values and behaviors of the type option are platform dependent. Возможные значения:

  • На Linux возможны типы desktop, dock, toolbar, splash, notification.
    • The desktop type places the window at the desktop background window level (kCGDesktopWindowLevel - 1). However, note that a desktop window will not receive focus, keyboard, or mouse events. You can still use globalShortcut to receive input sparingly.
    • The dock type creates a dock-like window behavior.
    • The toolbar type creates a window with a toolbar appearance.
    • The splash type behaves in a specific way. It is not draggable, even if the CSS styling of the window's body contains -webkit-app-region: drag. This type is commonly used for splash screens.
    • The notification type creates a window that behaves like a system notification.
  • On macOS, possible types are desktop, textured, panel.
    • Тип textured добавляет вид металлического градиента (NSWindowStyleMaskTexturedBackground).
    • Тип desktop размещает окно на уровень фонового окна рабочего стола (kCGDesktopWindowLevel - 1). Обратите внимание, что окно рабочего стола не будет получить события фокуса, клавиатуры или мыши, но Вы можете использовать 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. Also, the window will appear on all spaces (desktops).
  • На Windows возможен тип toolbar.