BrowserWindow | Electron
https://www.electronjs.org/docs/latest/api/browser-window • 291 KB fetched
Open original page
BrowserWindow | Electron
Skip to main content
Electron Docs API Blog Tools
* Electron Forge
* Electron Fiddle
Community
* Governance
* Showcase
* Resources
Releases English
* English
* Deutsch
* Español
* Français
* 日本語
* Português
* Русский
* 中文
Search
* Main Process Modules
* app
* autoUpdater
* BaseWindow
* BrowserView
* Deprecated
* BrowserWindow
* clipboard
* contentTracing
* crashReporter
* desktopCapturer
* dialog
* globalShortcut
* ImageView
* inAppPurchase
* ipcMain
* Menu
* MenuItem
* MessageChannelMain
* MessagePortMain
* nativeImage
* nativeTheme
* net
* netLog
* Notification
* powerMonitor
* powerSaveBlocker
* process
* protocol
* pushNotifications
* safeStorage
* screen
* session
* sharedTexture
* ShareMenu
* shell
* systemPreferences
* TouchBar
* Tray
* utilityProcess
* webContents
* WebContentsView
* webFrameMain
* View
* Renderer Process Modules
* Utility Process Modules
* Custom DOM Elements
* Chromium and Node.js
* Classes
* API Structures
*
* Main Process Modules
* BrowserWindow On this page
BrowserWindow
Create and control browser windows.
Process: Main
This module cannot be used until the ready event of the app
module is emitted.
// 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. 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
While loading the page, the ready-to-show event will be emitted when the renderer
process has rendered the page for the first time if the window has not been shown yet. Showing
the window after this event will have no visual flash:
const { BrowserWindow } = require ( 'electron' )
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.
Please note that using this event implies that the renderer will be considered "visible" and
paint even though show is false. This event will never fire if you use paintWhenInitiallyHidden: false
Setting the backgroundColor property
For a complex app, the ready-to-show event could be emitted too late, making
the app feel slow. In this case, it is recommended to show the window
immediately, and use a backgroundColor close to your app's background:
const { BrowserWindow } = require ( 'electron' )
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.
Some examples of valid backgroundColor values include:
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 and child windows
By using parent option, you can create child windows:
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.
Modal windows
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 ( )
} )
Page visibility
The Page Visibility API works as follows:
* On all platforms, the visibility state tracks whether the window is
hidden/minimized or not.
* Additionally, on macOS, the visibility state also tracks the window
occlusion state. If the window is occluded (i.e. fully covered) by another
window, the visibility state will be hidden . On other platforms, the
visibility state will be hidden only when the window is minimized or
explicitly hidden with win.hide() .
* If a BrowserWindow is created with show: false , the initial visibility
state will be visible despite the window actually being hidden.
* If backgroundThrottling is disabled, the visibility state will remain
visible even if the window is minimized, occluded, or hidden.
It is recommended that you pause expensive operations when the visibility
state is hidden in order to minimize power consumption.
Platform notices
* On macOS modal windows will be displayed as sheets attached to the parent window.
* On macOS the child windows will keep the relative position to parent window
when parent window moves, while on Windows and Linux child windows will not
move.
* On Linux the type of modal windows will be changed to dialog .
* On Linux many desktop environments do not support hiding a modal window.
* On Wayland (Linux) it is generally not possible to programmatically resize windows
after creation, or to position, move, focus, or blur windows without user input.
If your app needs these capabilities, run it in Xwayland by appending the flag
--ozone-platform=x11 .
Class: BrowserWindow extends BaseWindow
Create and control browser windows.
Process: Main
BrowserWindow is an EventEmitter .
It creates a new BrowserWindow with native properties as set by the options .
warning
Electron's built-in classes cannot be subclassed in user code.
For more information, see the FAQ .
new BrowserWindow([options])
* options BrowserWindowConstructorOptions (optional)
* webPreferences WebPreferences (optional) - Settings of web page's features.
* devTools boolean (optional) - Whether to enable DevTools. If it is set to false , can not use BrowserWindow.webContents.openDevTools() to open DevTools. Default is true .
* nodeIntegration boolean (optional) - Whether node integration is enabled.
Default is false .
* nodeIntegrationInWorker boolean (optional) - Whether node integration is
enabled in web workers. Default is false . Only workers created by a frame
that itself has access to Node.js (the main frame, or any frame when
nodeIntegrationInSubFrames is enabled) get it. More about this can be found
in Multithreading .
* nodeIntegrationInSubFrames boolean (optional) - Experimental option for
enabling Node.js support in sub-frames such as iframes and child windows. All your preloads will load for
every iframe, you can use process.isMainFrame to determine if you are
in the main frame or not.
* preload string (optional) - Specifies a script that will be loaded before other
scripts run in the page. This script will always have access to node APIs
no matter whether node integration is turned on or off. The value should
be the absolute file path to the script.
When node integration is turned off, the preload script can reintroduce
Node global symbols back to the global scope. See example
here .
* sandbox boolean (optional) - If set, this will sandbox the renderer
associated with the window, making it compatible with the Chromium
OS-level sandbox and disabling the Node.js engine. This is not the same as
the nodeIntegration option and the APIs available to the preload script
are more limited. Default is true since Electron 20. The sandbox will
automatically be disabled when nodeIntegration is set to true .
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. When
both session and partition are provided, session will be preferred.
Default is the default session.
* partition string (optional) - Sets the session used by the page according to the
session's partition string. If partition starts with persist: , the page
will use a persistent session available to all pages in the app with the
same partition . If there is no persist: prefix, the page will use an
in-memory session. By assigning the same partition , multiple pages can share
the same session. Default is the default session.
* zoomFactor number (optional) - The default zoom factor of the page, 3.0 represents
300% . Default is 1.0 .
* zoomMode string (optional) - The initial zoom mode for the page. See
contents.setZoomMode for available
modes. Default is 'default' .
* javascript boolean (optional) - Enables JavaScript support. Default is 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 option has not been set
by user. Default is true .
* allowRunningInsecureContent boolean (optional) - Allow an https page to run
JavaScript, CSS or plugins from http URLs. Default is false .
* images boolean (optional) - Enables image support. Default is true .
* imageAnimationPolicy string (optional) - Specifies how to run image animations (E.g. GIFs). Can be animate , animateOnce or noAnimation . Default is animate .
* textAreasAreResizable boolean (optional) - Make TextArea elements resizable. Default
is true .
* webgl boolean (optional) - Enables WebGL support. Default is true .
* plugins boolean (optional) - Whether plugins should be enabled. Default is false .
* experimentalFeatures boolean (optional) - Enables Chromium's experimental features.
Default is false .
* scrollBounce boolean (optional) macOS - Enables scroll bounce
(rubber banding) effect on macOS. Default is false .
* enableBlinkFeatures string (optional) - A list of feature strings separated by , , like
CSSVariables,KeyboardEventKey to enable. The full list of supported feature
strings can be found in the RuntimeEnabledFeatures.json5
file.
* disableBlinkFeatures string (optional) - A list of feature strings separated by , ,
like CSSVariables,KeyboardEventKey to disable. The full list of supported
feature strings can be found in the
RuntimeEnabledFeatures.json5 file.
* defaultFontFamily Object (optional) - Sets the default font for the font-family.
* standard string (optional) - Defaults to Times New Roman .
* serif string (optional) - Defaults to Times New Roman .
* sansSerif string (optional) - Defaults to Arial .
* monospace string (optional) - Defaults to Courier New .
* cursive string (optional) - Defaults to Script .
* fantasy string (optional) - Defaults to Impact .
* math string (optional) - Defaults to Latin Modern Math .
* defaultFontSize Integer (optional) - Defaults to 16 .
* defaultMonospaceFontSize Integer (optional) - Defaults to 13 .
* minimumFontSize Integer (optional) - Defaults to 0 .
* defaultEncoding string (optional) - Defaults to ISO-8859-1 .
* backgroundThrottling boolean (optional) - Whether to throttle animations and timers
when the page becomes background. This also affects the
Page Visibility 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. Defaults to true .
* offscreen Object | boolean (optional) - Whether to enable offscreen rendering for the browser
window. Defaults to false . See the
offscreen rendering tutorial for
more details.
* useSharedTexture boolean (optional) Experimental - Whether to use GPU shared texture for accelerated
paint event. Defaults to false . See the
offscreen rendering tutorial for
more details.
* sharedTexturePixelFormat string (optional) Experimental - The requested output format of the shared texture. Defaults to argb .
The name is originated from Chromium media::VideoPixelFormat enum suffix and only subset of them are supported.
The actual output pixel format and color space of the texture should refer to OffscreenSharedTexture object in the paint event.
* argb - The requested output texture format is 8-bit unorm RGBA, with SRGB SDR color space.
* rgbaf16 - The requested output texture format is 16-bit float RGBA, with scRGB HDR color space.
* nv12 - The requested output texture format is 12bpp with Y plane followed by a 2x2 interleaved UV plane, with REC709 color space.
* deviceScaleFactor number (optional) Experimental - The device scale factor of the offscreen rendering output. If not set, will use 1 as default.
* contextIsolation boolean (optional) - Whether to run Electron APIs and
the specified preload script in a separate JavaScript context. Defaults
to 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 (optional) - Whether to enable the <webview> tag .
Defaults to false . Note: 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. 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.
* 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. Default is 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 . Default is false .
* navigateOnDragDrop boolean (optional) - Whether dragging and dropping a
file or link onto the page causes a navigation. Default is 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 . Defaults to
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.
Default is true .
* enableWebSQL boolean (optional) - Whether to enable the WebSQL api .
Default is 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. Default is false .
* transparent boolean (optional) - Whether to enable background transparency for the guest page. Default is true . Note: The guest page's text and background colors are derived from the color scheme of its root element. When transparency is enabled, the text color will still change accordingly but the background will remain transparent.
* enableDeprecatedPaste boolean (optional) Deprecated - Whether to enable the paste execCommand . Default is false .
* focusOnNavigation boolean (optional) - Whether to focus the WebContents
when navigating. Default is true .
* paintWhenInitiallyHidden boolean (optional) - Whether the renderer should be active when show is false and it has just been created. In order for document.visibilityState to work correctly on first load with show: false you should set this to false . Setting this to false will cause the ready-to-show event to not fire. Default is true .
Instance Events
Objects created with new BrowserWindow emit the following events:
note
Some events are only available on specific operating systems and are
labeled as such.
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 fr
Links found on this page
- Skip to main content [direct]
- Electron [direct]
- Docs [direct]
- API [direct]
- Blog [direct]
- Electron Forge [direct]
- Electron Fiddle [direct]
- Governance [direct]
- Showcase [direct]
- Resources [direct]
- Releases [direct]
- Deutsch [direct]
- Español [direct]
- Français [direct]
- 日本語 [direct]
- Português [direct]
- Русский [direct]
- 中文 [direct]
- autoUpdater [direct]
- BaseWindow [direct]
- BrowserView Deprecated [direct]
- clipboard [direct]
- contentTracing [direct]
- crashReporter [direct]
- desktopCapturer [direct]
- dialog [direct]
- globalShortcut [direct]
- ImageView [direct]
- inAppPurchase [direct]
- ipcMain [direct]
- Menu [direct]
- MenuItem [direct]
- MessageChannelMain [direct]
- MessagePortMain [direct]
- nativeImage [direct]
- nativeTheme [direct]
- net [direct]
- netLog [direct]
- Notification [direct]
- powerMonitor [direct]
- powerSaveBlocker [direct]
- process [direct]
- protocol [direct]
- pushNotifications [direct]
- safeStorage [direct]
- screen [direct]
- session [direct]
- sharedTexture [direct]
- ShareMenu [direct]
- shell [direct]
- systemPreferences [direct]
- TouchBar [direct]
- Tray [direct]
- utilityProcess [direct]
- webContents [direct]
- WebContentsView [direct]
- webFrameMain [direct]
- View [direct]
- Custom DOM Elements [direct]
- Chromium and Node.js [direct]
- Classes [direct]
- API Structures [direct]
- Main [direct]
- Window Customization [direct]
- Page Visibility API [direct]
- EventEmitter [direct]
- the FAQ [direct]
- BrowserWindowConstructorOptions [direct]
- WebPreferences [direct]
- Multithreading [direct]
- here [direct]
- here [direct]
- RuntimeEnabledFeatures.json5 [direct]
- offscreen rendering tutorial [direct]
- media::VideoPixelFormat [direct]
- OffscreenSharedTexture [direct]
- Chrome Content Scripts [direct]
- WebSQL api [direct]
- color scheme [direct]
- execCommand [direct]