BaseWindow
Create and control windows.
Process: Main
Note
BaseWindow
provides a flexible way to compose multiple web views in a single window. For windows with only a single, full-size web view, theBrowserWindow
class may be a simpler option.
This module cannot be used until the ready
event of the app
module is emitted.
// In the main process.
const { BaseWindow, WebContentsView } = require('electron')
const win = new BaseWindow({ width: 800, height: 600 })
const leftView = new WebContentsView()
leftView.webContents.loadURL('https://electronjs.org')
win.contentView.addChildView(leftView)
const rightView = new WebContentsView()
rightView.webContents.loadURL('https://github.com/electron/electron')
win.contentView.addChildView(rightView)
leftView.setBounds({ x: 0, y: 0, width: 400, height: 600 })
rightView.setBounds({ x: 400, y: 0, width: 400, height: 600 })
Ventana principal y ventana secundaria
By using parent
option, you can create child windows:
const { BaseWindow } = require('electron')
const parent = new BaseWindow()
const child = new BaseWindow({ parent })
The child
window will always show on top of the parent
window.
Ventanas modales
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 { BaseWindow } = require('electron')
const parent = new BaseWindow()
const child = new BaseWindow({ parent, modal: true })
Notas según la plataforma
- En macOS las ventanas modales se mostrarán como hojas adjuntas a la ventana principal.
- 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
. - En Linux, muchos entornos de escritorio no admiten ocultar una ventana modal.
Class: BaseWindow
Create and control windows.
Process: Main
BaseWindow
is an EventEmitter.
It creates a new BaseWindow
with native properties as set by the options
.
new BaseWindow([options])
When setting minimum or maximum window size with minWidth
/maxWidth
/
minHeight
/maxHeight
, it only constrains the users. It won't prevent you from
passing a size that does not follow size constraints to setBounds
/setSize
or
to the constructor of BrowserWindow
.
The possible values and behaviors of the type
option are platform dependent.
Los valores posibles son:
- On Linux, possible types are
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.
- The
- On macOS, possible types are
desktop
,textured
,panel
.- The
textured
type adds metal gradient appearance (NSWindowStyleMaskTexturedBackground
). - The
desktop
type places the window at the desktop background window level (kCGDesktopWindowLevel - 1
). Note that desktop window will not receive focus, keyboard or mouse events, but you can useglobalShortcut
to receive input sparingly. - The
panel
type enables the window to float on top of full-screened apps by adding theNSWindowStyleMaskNonactivatingPanel
style mask,normally reserved for NSPanel, at runtime. Also, the window will appear on all spaces (desktops).
- The
- On Windows, possible type is
toolbar
.
Eventos de Instancia
Objects created with new BaseWindow
emit the following events:
Note: Some events are only available on specific operating systems and are labeled as such.
Evento: "close"
Devuelve:
event
Event
Aparece cuando la ventana se va a cerrar. 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. Por ejemplo:
window.onbeforeunload = (e) => {
console.log('I do not want to be closed')
// Unlike usual browsers that a message box will be prompted to users, returning
// a non-void value will silently cancel the close.
// It is recommended to use the dialog API to let the user confirm closing the
// application.
e.returnValue = false
}
Note: There is a subtle difference between the behaviors of window.onbeforeunload = handler
and window.addEventListener('beforeunload', handler)
. It is recommended to always set the event.returnValue
explicitly, instead of only returning a value, as the former works more consistently within Electron.
Evento: "closed"
Emitted when the window is closed. Después de haber recibido este evento, debe eliminar la referencia a la ventana y evitar volverla a usar.
Event: 'session-end' Windows
Aparece cuando la sesión de la ventana va a terminarse debido a un cierre forzoso o el reinicio de la máquina o el cierre de la sesión.
Evento: "blur"
Aparece cuando la ventana pierde el enfoque.
Evento: "focus"
Aparece cuando la ventana recupera el enfoque.
Evento: "show"
Aparece cuando se muestra la ventana.
Evento: "hide"
Aparece cuando se oculta la ventana.
Evento: "maximize"
Aparece cuando se maximiza la ventana.
Evento: "unmaximize"
Aparece cuando la ventana sale de un estado maximizado.
Evento: "minimize"
Aparece cuando se minimiza la ventana.
Evento: "restore"
Aparece cuando se restaura la ventana de un estado minimizado.
Event: 'will-resize' macOS Windows
Devuelve:
event
EventnewBounds
Rectangle - Size the window is being resized to.details
Objectedge
(string) - The edge of the window being dragged for resizing. Can bebottom
,left
,right
,top-left
,top-right
,bottom-left
orbottom-right
.
Emitido antes de que la ventana sea redimensionada. Calling event.preventDefault()
will prevent the window from being resized.
Tenga en cuenta que esto solo es emitido cuando la venta está siendo redimensionada de forma manual. Resizing the window with setBounds
/setSize
will not emit this event.
The possible values and behaviors of the edge
option are platform dependent. Los valores posibles son:
- On Windows, possible values are
bottom
,top
,left
,right
,top-left
,top-right
,bottom-left
,bottom-right
. - On macOS, possible values are
bottom
andright
.- The value
bottom
is used to denote vertical resizing. - The value
right
is used to denote horizontal resizing.
- The value
Evento: "resize"
Emitido después que la ventana se haya redimensionada.
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
Devuelve:
event
EventnewBounds
Rectangle - Location the window is being moved to.
Emitted before the window is moved. On Windows, calling event.preventDefault()
will prevent the window from being moved.
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"
Aparece cuando la ventana se mueve a una nueva posición.
Event: 'moved' macOS Windows
Aparece solo una vez cuando la ventana se mueve a una nueva posición.
Note: On macOS this event is an alias of move
.
Evento: "enter-full-screen"
Aparece cuando la ventana entra en un estado pantalla completa.
Evento: "leave-full-screen"
Aparece cuando la ventana sale del estado pantalla completa.
Evento: 'always-on-top-changed'
Devuelve:
event
EventisAlwaysOnTop
boolean
Emitido cuando la ventana es configurada o no configurada para mostrarse siempre en la parte superior de las otras ventanas.
Event: 'app-command' Windows Linux
Devuelve:
event
Eventcommand
string
Emitted when an App Command is invoked. Estos están generalmente relacionados a las teclas del teclado o a los comandos del navegador, así como el botón "Back" está en algunos ratones en 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 { BaseWindow } = require('electron')
const win = new BaseWindow()
win.on('app-command', (e, cmd) => {
// Navigate the window back when the user hits their mouse back button
if (cmd === 'browser-backward') {
// Find the appropriate WebContents to navigate.
}
})
Los siguientes comandos de aplicación están explícitamente soportados en Linux:
browser-backward
browser-forward
Event: 'swipe' macOS
Devuelve:
event
Eventdirection
string
Emitted on 3-finger swipe. Possible directions are up
, right
, down
, left
.
El método subyacente a este evento esta construido para manejar el viejo estilo de desplazamiento del trackpad de macOS, donde el contenido de la pantalla no se mueve con el manotazo. 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
Devuelve:
event
Eventrotation
Float
Emitido en el gesto de rotación de trackpad. Continuamente emitido hasta que el gesto de rotación se termine. 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
. Los valores de rotación en sentido antihorario son positivos, mientras que los valores de rotación en sentido horario son negativos.
Event: 'sheet-begin' macOS
Aparece cuando la ventana abre una hoja.
Event: 'sheet-end' macOS
Aparece cuando la ventana cierra una hoja.
Event: 'new-window-for-tab' macOS
Aparece cuando se hace clic al botón de nueva pestaña nativa.
Event: 'system-context-menu' Windows
Devuelve:
event
Eventpoint
Point - The screen coordinates the context menu was triggered at
Emitido cuando el menú contextual del sistema es activado en la ventana, esto normalmente solo es activado cuando el usuario hace click derecho en el área que no es del cliente de la ventana. 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.
Métodos Estáticos
The BaseWindow
class has the following static methods:
BaseWindow.getAllWindows()
Returns BaseWindow[]
- An array of all opened browser windows.
BaseWindow.getFocusedWindow()
Returns BaseWindow | null
- The window that is focused in this application, otherwise returns null
.
BaseWindow.fromId(id)
id
Integer
Returns BaseWindow | null
- The window with the given id
.
Propiedades de la instancia
Objects created with new BaseWindow
have the following properties:
const { BaseWindow } = require('electron')
// In this example `win` is our instance
const win = new BaseWindow({ width: 800, height: 600 })
win.id
Readonly
A Integer
property representing the unique ID of the window. Each ID is unique among all BaseWindow
instances of the entire Electron application.
win.contentView
A View
property for the content view of the window.
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
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 Alt
key.
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 { Menu, BaseWindow } = require('electron')
const win = new BaseWindow({ 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. Esta cadena no es directamente visible para los usuarios.
Métodos de Instancia
Objects created with new BaseWindow
have the following instance methods:
Note: Some methods are only available on specific operating systems and are labeled as such.
win.setContentView(view)
view
View
Sets the content view of the window.
win.getContentView()
Returns View - The content view of the window.
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()
Trate de cerrar la ventana. Esto tiene el mismo efecto que un usuario pulsando manualmente el botón cerrar de la ventana. The web page may cancel the close though. See the close event.
win.focus()
Enfoca la ventana.
win.blur()
Elimina el enfoque de la ventana.
win.isFocused()
Returns boolean
- Whether the window is focused.
win.isDestroyed()
Returns boolean
- Whether the window is destroyed.
win.show()
Muestra la ventana y la enfoca.
win.showInactive()
Muestra la ventana pero no la enfoca.
win.hide()
Oculta la ventana.
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()
Maximiza la ventana. This will also show (but not focus) the window if it isn't being displayed already.