BrowserWindow
Crier e controle janelas de navegação.
Process: Main
Este módulo não pode ser usado até que o evento ready do módulo app seja emitido.
// No processo main.
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
Enquanto a página é carregada, o evento ready-to-show será disparado quando o processo de renderização estiver renderizado completamente a página pela primeira vez, caso a janela ainda não tenha sido exibida. Exibindo a janela após este evento não resultará em um flash visual:
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ show: false })
win.once('ready-to-show', () => {
win.show()
})
Este evento geralmente é emitido depois do evento did-finish-load, porém para páginas com vários recursos remotos, tal evento pode ser emitido antes.
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
Para um aplicativo complexo, o evento ready-to-show poderia ser emitido tarde demais, fazendo com que o aplicativo aparente lentidão. Neste caso, é recomendado exibir a janela imediatamente e utilizar a propriedade backgroundColor com cor semelhante a cor de fundo do seu aplicativo:
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.
Janelas parent e child
Ao utilizar a opção parent, é possível criar janelas secundarias:
const { BrowserWindow } = require('electron')
const top = new BrowserWindow()
const child = new BrowserWindow({ parent: top })
child.show()
top.show()
A janela secundaria (child) sempre será exibida em frente a janela principal (top).
Janelas Modais
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()
})
Visibilidade de página
A API de visibilidade de página funciona da seguinte forma:
- Em todas as plataformas, o estado de visibilidade verifica quando a janela é ocultada/minimizada ou não.
- Adicionalmente, no macOS, o estado de visibilidade também verifica o estado de oclusão da janela. Se a janela estive obstruída (ou seja, completamente coberta) por outra janela, o estado de visibilidade será
hidden. Em outras plataformas, o estado de visibilidade seráhiddensomente quando a janela for minimizada ou explicitamente ocultada com o métodowin.hide(). - Se um
BrowserWindowé criado com a propriedadeshow: false, a visibilidade inicial serávisibleindependente da janela estar de fato ocultada. - Se a propriedade
backgroundThrottlingestive desativado, o estado de visibilidade continuarávisiblemesmo que a janela esteja minimizada, ocultada ou escondida.
É recomendado que você pause operações "caras" quando o estado de visibilidadade for hidden com o objetivo de minimizar o consumo de energia.
Avisos de plataformas
- No macOS, janelas modal serão exibidas como "folhas" vinculadas a janela principal.
- No macOS, as janelas secundarias manterão a posição relativa com a janela principal quando a mesma se mover, enquanto que no Windows e Linux as janelas secundarias não se movem.
- No Linux, o tipo de janelas modais será modificado para
dialog. - No Linux, vários ambientes desktop não há suporte para esconder uma janela modal.
- 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
Crier e controle janelas de navegação.
Process: Main
BrowserWindow é um EventEmitter.
O mesmo cria um novo BrowserWindow com propriedades nativas informadas como a opção options.
[!WARNING] Electron's built-in classes cannot be subclassed in user code. For more information, see the FAQ.
new BrowserWindow([options])
Eventos de instância
Objects created with new BrowserWindow emit the following events:
[!NOTE] Some events are only available on specific operating systems and are labeled as such.
Evento: 'page-title-updated'
Retorna:
eventEventtitlestringexplicitSetboolean
Emitido quando o documento mudou seu título, chamando event.preventDefault() impedirá que o título da janela nativa mude. explicitSet is false when title is synthesized from file URL.
Evento: 'close'
Retorna:
eventEvent
Emitted when the window is going to be closed. It's emitted before the beforeunload and unload event of the DOM. Calling event.preventDefault() will cancel the close.
Usually you would want to use the beforeunload handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than undefined would cancel the close. Como por exemplo:
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 = 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.
Evento: '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: 'query-session-end' Windows
Retorna:
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.
Evento: 'session-end' Windows
Retorna:
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.
Evento: 'unresponsive'
Emitted when the web page becomes unresponsive.
Evento: 'responsive'
Emitted when the unresponsive web page becomes responsive again.
Evento: 'blur'
Emitted when the window loses focus.
Evento: 'focus'
Emitted when the window gains focus.
Evento: 'show'
Emitted when the window is shown.
Evento: 'hide'
Emitted when the window is hidden.
Evento: '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. This event will never fire if you use paintWhenInitiallyHidden: false
Evento: 'maximize'
Emitted when window is maximized.
Evento: 'unmaximize'
Emitted when the window exits from a maximized state.
Evento: 'minimize'
Emitted when the window is minimized.
Evento: 'restore'
Emitted when the window is restored from a minimized state.
Event: 'will-resize' macOS Windows
Retorna:
eventEventnewBoundsRectangle - Size the window is being resized to.- Objeto
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. Possible values are:
- 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
Evento: '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.
Event: 'will-move' macOS Windows
Retorna:
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.
Evento: '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.
Evento: 'enter-full-screen'
Emitted when the window enters a full-screen state.
Evento: 'leave-full-screen'
Emitted when the window leaves a full-screen state.
Evento: 'enter-html-full-screen'
Emitted when the window enters a full-screen state triggered by HTML API.
Evento: 'leave-html-full-screen'
Emitted when the window leaves a full-screen state triggered by HTML API.
Evento: 'always-on-top-changed'
Retorna:
eventEventisAlwaysOnTopboolean
Emitted when the window is set or unset to show always on top of other windows.
Event: 'app-command' Windows Linux
Retorna:
eventEventcommandstring
Emitted when an App Command is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows.
Commands are lowercased, underscores are replaced with hyphens, and the APPCOMMAND_ prefix is stripped off. e.g. APPCOMMAND_BROWSER_BACKWARD is emitted as browser-backward.
const { BrowserWindow } = require('electron')
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:
browser-backwardbrowser-forward
Event: 'swipe' macOS
Retorna:
eventEventdirectionstring
Emitted on 3-finger swipe. Possible directions are up, right, down, left.
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. 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'.
Event: 'rotate-gesture' macOS
Retorna:
eventEventrotationFloat
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. The last emitted event upon a rotation gesture will always be of value 0. Counter-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.
Evento: 'new-window-for-tab' macOS
Emitted when the user clicks the native macOS new tab button. The new tab button is only visible if the current BrowserWindow has a tabbingIdentifier.
You must create a window in this handler in order for macOS tabbing to work as expected.
Event: 'system-context-menu' Windows Linux
Retorna:
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).
Métodos estáticos
A classe BrowserWindow tem os seguintes métodos estáticos:
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.
BrowserWindow.fromWebContents(webContents)
webContentsWebContents
Returns BrowserWindow | null - The window that owns the given webContents or null if the contents are not owned by a window.
BrowserWindow.fromBrowserView(browserView) Descontinuado
browserViewBrowserView
[!NOTE] The
BrowserViewclass is deprecated, and replaced by the newWebContentsViewclass.
Returns BrowserWindow | null - The window that owns the given browserView. If the given view is not attached to any window, returns null.
BrowserWindow.fromId(id)
idInteiro
Returns BrowserWindow | null - The window with the given id.
Propriedades da Instância
Objectos criados com new BrowserWindow posuem as seguintes propriedades:
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. All web page related events and operations will be done via it.
See the webContents documentation for its methods and events.
win.id Readonly
A Integer property representing the unique ID of the window. 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.
If the menu bar is already visible, setting this property to true won't hide it immediately.
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
A boolean property that determines whether the window can be manually minimized by user.
On Linux the setter is a no-op, although the getter returns true.
win.maximizable macOS Windows
A boolean property that determines whether the window can be manually maximized by user.
On Linux the setter is a no-op, although the getter returns true.
win.fullScreenable
A boolean property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.
win.resizable
A boolean property that determines whether the window can be manually resized by user.
win.closable macOS Windows
A boolean property that determines whether the window can be manually closed by user.
On Linux the setter is a no-op, although the getter returns true.
win.movable macOS Windows
A boolean property that determines Whether the window can be moved by user.
On Linux the setter is a no-op, although the getter returns true.
win.excludedFromShownWindowsMenu macOS
A boolean property that determines whether the window is excluded from the application’s Windows menu. false by default.
const win = new BrowserWindow({ height: 600, width: 600 })
const template = [
{
role: 'windowmenu'
}
]
win.excludedFromShownWindowsMenu = true
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
win.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.
Métodos de Instância
Objectos criados com new BrowserWindow possuem os seguintes métodos de instâncias:
[!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.
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()
Focuses on the window.
On Wayland (Linux), the desktop environment may show a notification or flash the app icon if the window or app is not already focused.
win.blur()
Removes focus from the window.
Not supported on Wayland (Linux).
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.
Not supported on Wayland (Linux).
win.hide()
Hides the window.
win.isVisible()
Returns boolean - Whether the window is visible to the user in the foreground of the app.
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.
win.restore()
Restores the window from minimized state to its previous state.
win.isMinimized()
Returns boolean - Whether the window is minimized.
win.setFullScreen(flag)
flagboolean
Sets whether the window should be in fullscreen mode.
[!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()
Returns boolean - Whether the window is in fullscreen mode.
[!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
Enters or leaves simple fullscreen mode.
Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7).
win.isSimpleFullScreen() macOS
Returns boolean - Whether the window is in simple (pre-Lion) fullscreen mode.
win.isNormal()
Returns boolean - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode).
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.
This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size.
Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and { 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.
To reset an aspect ratio, pass 0 as the aspectRatio value: