Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Electron BrowserWindow module


May 25, 2021 Electron


Table of contents


The BrowserWindow class gives you the power to create a browser window. For example:

// In the main process.
const BrowserWindow = require('electron').BrowserWindow;

// Or in the renderer process.
const BrowserWindow = require('electron').remote.BrowserWindow;

var win = new BrowserWindow({ width: 800, height: 600, show: false });
win.on('closed', function() {
  win = null;
});

win.loadURL('https://github.com');
win.show();

You can also use the Frameless Window API without creating windows through chrome.

Class: BrowserWindow

BrowserWindow is an EventEmitter .

Options allows you to create a BrowserWindow with essential properties.

new BrowserWindow([options])

  • options Object
    • width Integer - window width, unit pixels. The default is 800.
    • Height Integer - Window height, unit pixels. The default is 600.
    • x Integer - The left offset position of the window relative to the screen. Centered by default.
    • y Integer - The position of the window offset relative to the top of the screen. Centered by default.
    • UseContentSize Boolean - width and height use web pages size, which means that the size of the actual window should include the size of the window frame, slightly erred, which defaults to false.
    • Center Boolean - The window screen is centered.
    • minWidth Integer - The minimum width of the window, which defaults to 0.
    • minHeight Integer - Window minimum height, default to 0.
    • maxWidth Integer - maximum width of window, unlimited by default.
    • maxHeight Integer - maximum window height, unlimited by default.
    • Resizable Boolean - Whether the window size can be changed, the default is true.
    • Movable Boolean - Whether the window can be dragged. N ot valid on Linux. True by default.
    • minimizable Boolean - Whether the window can be minimized. N ot valid on Linux. True by default.
    • Maximizable Boolean - Whether the window can be maximized. N ot valid on Linux. True by default.
    • Closable Boolean - Whether the window can be closed. N ot valid on Linux. True by default.
    • AlwaysOnTop Boolean - Whether the window always appears before other windows. N ot valid on Linux. The default is false.
    • Fullscreen Boolean - Whether the window can be full screen. W hen the explicit setting value is Whon false, the full-screen button will be hidden and disabled at OS X. The default false.
    • Fullscreenable Boolean - On OS X, the full-screen button is available, which defaults to true.
    • SkipTaskbar Boolean - Whether to display the window in the taskbar. The default is false.
    • kiosk Boolean - kiosk way. The default is false.
    • Title String - Window default title. The default is Electron.
    • icon NativeImage - Window icon, if not set, the window will use the default icon available.
    • Show Boolean - Whether the window is displayed when it is created. True by default.
    • Frame Boolean - Specify false to create a Frameless Window . True by default.
    • AcceptFirstMouse Boolean - Whether to allow a click on the web view to activate the window. The default is false.
    • DisableAutoHideCursor Boolean - Whether to hide the mouse when typing. The default false.
    • autoHideMenuBar Boolean - Hide the menu bar unless you click Alt. The default is false.
    • EnableLargerThanScreen Boolean - Whether to allow changes to window size larger than the screen. The default is false.
    • BackgroundColor String - The background color value of the window is hete size, such as #66CD00 or #FFF or #80FFFFFF (transparency is supported). The default is to have a #000 (black) on Linux and Windows, and #FFF (or transparent).
    • HasShadow Boolean - Does the window have shadows? V alid only on OS X. True by default.
    • darkTheme Boolean - Uses the dark theme for windows and works only on desktop environments that have GTK3. The default is false.
    • Transparent Boolean - Window Transparent. The default is false.
    • Type String - Window type, default normal window, see more below.
    • TitleBarStyle String - Window Title Bar Style, see more below.
    • WebPreferences Object - Set up interface features, see more below.

The values and effects of type vary from platform to platform, specifically:

  • Linux, available values are desktop, dock, toolbar, splash, notification.
  • OS X, available values are desktop, textured.
    • Textured type Add Metal Gradient Effect (NSTexturedBackgroundWindowMask).
    • The desktop sets the window horizontally in the desktop background window (kCGDesktopWindowLevel - 1). Note that the desktop window is not focused and keyboard and mouse events cannot be supported, but you can use globalShortcut to resolve input issues.

TitleBarStyle is only supported on OS X 10.10 Yosemite or later, with available values:

  • default and no value, which appears opaque standard gray on the Mac title bar.
  • Hidden Hide hides the title bar, which fills the entire window, and then it's still in the upper left corner, still controlled by the standard window.
  • Hidden-inset body is hidden, showing small control buttons at the edge of the window.

The webPreferences parameter is an object whose properties:

  • nodeIntegration Boolean - whether node is fully supported. True by default.
  • Preload String - The interface's other scripts preload a specified script before running. T his script will always be available using node APIs regardless of whether node integration is turned on or not. T he script path is absolute. W hen node integration is turned off, the preloaded script re-introduces node's global reference flag from the global scope. View the example here .
  • session Session - Set up the interface session. I nstead of ignoring the session object directly, you can also use partition instead, which accepts a partition string. W hen both session and partition are used, session has a higher priority. The default session is used by default.
  • partition String - Set the interface with the session string of session. I f partition starts with persist: this interface will use the same partition for all interfaces . I f there is no persist: prefix, the interface uses historical session. B y sharing the same partition, all interfaces use the same session. The default session is used by default.
  • ZoomFactor Number - Interface default zoom, 3.0 for 300%. Default 1.0 .
  • javascript Boolean - Turn on javascript support. True by default .
  • webSecurity Boolean - When set to false, it disables the rules of the same place (usually test clothing), and if there are 2 parameters set by non-users, set the values of allowDisplayInsecureContent and allowRunningInsecureContent to true . True by default .
  • AllowDisplayIngInsecureContent Boolean - allows an interface that uses https to show resources passed over by http URLs. The default false .
  • AllowRunningInsecureContent Boolean - Boolean - allows an interface that uses https to render html, css, javascript submitted by http URLs. The default is false.
  • Images Boolean - Turn on image usage support. True by default .
  • TextAreasAreResizable Boolean - textArea can be edited. True by default .
  • Webgl Boolean - Turn on WebGL Support. True by default .
  • Webaudio Boolean - Turn on WebAudio support. True by default .
  • Plugins Boolean - Whether plug-in support is turned on. The default is false .
  • Analfeatures Boolean - Turn on Chromium's testable features. The default is false .
  • AncastCanvasFeatures Boolean - Turn on Chromium's canvas testable features. The default is false .
  • DirectWrite Boolean - Open window of the DirectWrite font rendering system. True by default .
  • blinkFeatures String - With , list of features, such as CSSVariables, KeyboardEventKey . All supported features can be found in setFeatureEnabledFromString.
  • DefaultFontFamily Object - Set font-family default font.
    • Standard String - The default is Times New Roman .
    • Serif String - Times New Roman by default .
    • sansSerif String - Arial by default .
    • monospace String - Courier New by default .
  • defaultFontSize Integer - 16 by default .
  • defaultMonospaceFontSize Integer - default is 13 .
  • minimumFontSize Integer - 0 by default .
  • DefaultEncoding String - DEFAULT ISO-8859-1 .

Event

The BrowserWindow object can trigger the following events:

Note: Some events can only be triggered in a specific os environment and have been marked as much as possible.

Event: 'page-title-updated'

Return:

  • event Event

When the document changes the title, use event.preventDefault() to prevent the title of the original window from changing.

Event: 'close'

Return:

  • event Event

Triggered when the window is about to close. I t is triggered before the DOM's beforeunload and unload events. Use event.preventDefault() to cancel this operation

Usually you want to decide whether to close the window through the beforeunload processor, but it is also triggered when the window is overloaded. I n Electron, returning an empty string or false can cancel the shutdown. For example:

window.onbeforeunload = function(e) {
  console.log('I do not want to be closed');

  // Unlike usual browsers, in which a string should be returned and the user is
  // prompted to confirm the page unload, Electron gives developers more options.
  // Returning empty string or false would prevent the unloading now.
  // You can also use the dialog API to let the user confirm closing the application.
  e.returnValue = false;
};

Event: 'closed'

Triggered when the window is closed. When you receive this event, you should remove the reference object to the closed window and avoid using it again.

Event: 'unresponsive'

Trigger an event when the interface is stuck.

Event: 'responsive'

Triggered when interface recovery is stuck.

Event: 'blur'

Triggered when the window loses focus.

Event: 'focus'

Triggers when the window gets focus.

Event: 'maximize'

Triggered when the window is maximized.

Event: 'unmaximize'

Triggered when window exit is maximized.

Event: 'minimize'

Triggered when the window is minimized.

Event: 'restore'

Triggers when the window recovers from minimization.

Event: 'resize'

Triggered when the window size changes.

Event: 'move'

Triggered as the window moves.

Note: Alias moved in OS X .

Event: 'moved' OS X

Triggered as the window moves.

Event: 'enter-full-screen'

Triggered when the window enters full screen.

Event: 'leave-full-screen'

Triggered when the window exits full screen.

Event: 'enter-html-full-screen'

Triggered when the window enters full screen through html api.

Event: 'leave-html-full-screen'

Triggered when the window exits full screen through html api.

Event: 'app-command' Windows

Triggered when an App Command .aspx) is requested. Typically keyboard media or browser commands, the "Back" button on Windows will also be triggered as a mouse.

someWindow.on('app-command', function(e, cmd) {
  // Navigate the window back when the user hits their mouse back button
  if (cmd === 'browser-backward' && someWindow.webContents.canGoBack()) {
    someWindow.webContents.goBack();
  }
});

Event: 'scroll-touch-begin' OS X

Triggered at the beginning of the scroll bar event.

Event: 'scroll-touch-end' OS X

Triggered at the end of the scroll bar event.

Method

The BrowserWindow object has the following methods:

BrowserWindow.getAllWindows()

Returns an array of all objects that have windows open.

BrowserWindow.getFocusedWindow()

Returns to the app's current focus window, or null if not .

BrowserWindow.fromWebContents(webContents)

Find windows according to webContents.

BrowserWindow.fromId(id)

  • id Integer

Find windows based on id.

BrowserWindow.addDevToolsExtension(path)

  • path String

Add the developer toolbar extension at path and return the name of the extension.

This extension will be added to history so only need to use this API once and this api cannot be used for programming purposes.

BrowserWindow.removeDevToolsExtension(name)

  • name String

Remove the extension of the developer toolbar name name name.

The instance property

Instance objects created with new BrowserWindow have the following properties:

// In this example `win` is our instance
var win = new BrowserWindow({ width: 800, height: 600 });

win.webContents

This window's WebContents object, through which all interface-related events and methods are done.

View webContents documentation methods and events.

win.id

The unique id of the window.

The instance method

Instance objects created with new BrowserWindow are available in the following ways:

Note: Some methods can only be called in a specific os environment and have been landmarkd as much as possible.

win.destroy()

Force close window, unload and beforeunload will not fire, and close will not fire, but it guarantees closed trigger.

win.close()

Try closing the window as if the user had clicked the close button. Although the page may be de-closed, view close event .

win.focus()

The window gets focus.

win.isFocused()

Back to boolean, does the window get the focus?

win.show()

Show and focus the window.

win.showInactive()

Show window but don't get focus.

win.hide()

Hide the window.

win.isVisible()

Back to boolean, whether the window is visible.

win.maximize()

The window maximizes.

win.unmaximize()

Cancel window maximization.

win.isMaximized()

Back to boolean, whether the window is maximized.

win.minimize()

Window minimization. In some os, it will be displayed in the dock.

win.restore()

Restore the minimized window to its previous state.

win.isMinimized()

Back to boolean, whether the window is minimized.

win.setFullScreen(flag)

  • flag Boolean

Set whether the screen is full.

win.isFullScreen()

Back to boolean, whether the window is fully screened.

win.setAspectRatio(aspectRatio[, extraSize]) OS X

  • AspectRatio maintains the aspect ratio of part of the view content window.
  • ExtraSize Object (optional) - Extra size that is not included when maintaining aspect ratio values.
    • width Integer
    • height Integer

A window maintains the aspect ratio. ExtraSize allows developers to use it in pixels and is not included in aspectRatio. This API can be used to distinguish between the size of a window and the size of the content.

Imagine a normal controlled HD video player window. I f the left edge has 15 control pixels, the right edge has 25 control pixels, and under the player there are 50 control pixels. I n order to maintain a 16:9 aspect ratio within the player, we can call this api incoming parameters 16/9 and . Just add up all the extra height and width of the page.

win.setBounds(options[, animate])

  • options Object
    • x Integer
    • y Integer
    • width Integer
    • height Integer
  • Animate Boolean (optional) OS X

Reset the width value of the window and move to the specified x, y position.

win.getBounds()

Returns an object that contains the width, height, x coordinates, and y coordinates of the window.

win.setSize(width, height[, animate])

  • width Integer
  • height Integer
  • Animate Boolean (optional) OS X

Reset the width value of the window.

win.getSize()

Returns an array that contains the width and height of the window.

win.setContentSize(width, height[, animate])

  • width Integer
  • height Integer
  • Animate Boolean (optional) OS X

Reset the width value of the window client (such as the web interface).

win.getContentSize()

Returns an array that contains the width and height of the window client.

win.setMinimumSize(width, height)

  • width Integer
  • height Integer

Set the width and height value of the window minimization.

win.getMinimumSize()

Returns an array that contains the width and height of the window minimization.

win.setMaximumSize(width, height)

  • width Integer
  • height Integer

Set the width and height value of the window maximization.

win.getMaximumSize()

Returns an array that contains the maximum width and height of the window.

win.setResizable(resizable)

  • resizable Boolean

Set whether the window can be changed by the user size.

win.isResizable()

Back to boolean, whether the window can be changed by the user size.

win.setMovable(movable) OS X Windows

  • movable Boolean

Set whether the window can be dragged by the user. Linux is not valid.

win.isMovable() OS X Windows

Back to boolean, whether the window can be dragged by the user. Linux always returns true .

win.setMinimizable(minimizable) OS X Windows

  • minimizable Boolean

Set whether the window can be minimized. Linux is not valid.

win.isMinimizable() OS X Windows

Back to boolean, whether the window can be minimized. Linux always returns true .

win.setMaximizable(maximizable) OS X Windows

  • maximizable Boolean

Set whether the window can be maximized. Linux is not valid.

win.isMaximizable() OS X Windows

Back to boolean, whether the window can be maximized. Linux always returns true .

win.setFullScreenable(fullscreenable)

  • fullscreenable Boolean

Set whether the click maximize button can be full screen or maximize the window.

win.isFullScreenable()

Return to boolean and click on the maximize button whether the full screen or maximize the window.

win.setClosable(closable) OS X Windows

  • closable Boolean

Set whether the window can be closed artificially. Linux is not valid.

win.isClosable() OS X Windows

Back to boolean, whether the window can be artificially closed. Linux always returns true .

win.setAlwaysOnTop(flag)

  • flag Boolean

Whether to set this window is always on top of other windows. After setting up, this window is still an ordinary window, not a toolbox window that does not get focus.

win.isAlwaysOnTop()

Return to boolean, whether the current window is always before other windows.

win.center()

The window is centered.

win.setPosition(x, y[, animate])

  • x Integer
  • y Integer
  • Animate Boolean (optional) OS X

Move the window to the corresponding x and y coordinates.

win.getPosition()

Returns an array containing the current window position.

win.setTitle(title)

  • title String

Change the title of the original window.

win.getTitle()

Return to the title of the original window.

Note: Interface title may not be the same as window title.

win.flashFrame(flag)

  • flag Boolean

Start or stop the display window to get the user's attention.

win.setSkipTaskbar(skip)

  • skip Boolean

Let the window not appear in the taskbar.

win.setKiosk(flag)

  • flag Boolean

Enter or leave kiosk mode.

win.isKiosk()

Return to boolean whether to enter or leave kiosk mode.

win.getNativeWindowHandle()

Returns the handle to the window for this particular platform in buffer form.

The handle type on windows is HWND, OS X NSView, Linux Window .

win.hookWindowMessage(message, callback) Windows

  • message Integer
  • callback Function

Block windows messages and trigger callback functions when WndProc receives messages.

win.isWindowMessageHooked(message) Windows

  • message Integer

Return true or false to indicate whether the message has been intercepted.

win.unhookWindowMessage(message) Windows

  • message Integer

Do not block window messages.

win.unhookAllWindowMessages() Windows

Window messages are not blocked at all.

win.setRepresentedFilename(filename) OS X

  • filename String

Set the current file path of the window and place the icon of the file on the window title bar.

win.getRepresentedFilename() OS X

Gets the window's current file path.

win.setDocumentEdited(edited) OS X

  • edited Boolean

Make it clear whether the window document can be edited and, if so, turn the icon of the title bar gray.

win.isDocumentEdited() OS X

Back to boolean, whether the current window document is editable.

win.focusOnWebView()

win.blurWebView()

win.capturePage([rect, ]callback)

  • Rect Object (optional) - Capture Page location
    • x Integer
    • y Integer
    • width Integer
    • height Integer
  • callback Function

Capture a snapshot of the page in the rect. W hen complete, the callback function callback is called and the image . Image is an instance of NativeImage that stores snapshot information. If you do not set rect, all visible page will be captured.

win.print([options])

Similar to webContents.print

win.printToPDF(options, callback)

Similar to webContents.printToPDF (options, callback).

win.loadURL(url[, options])

Similar to webContents.loadURL (url, options). .

win.reload()

Similar to webContents.reload .

win.setMenu(menu) Linux Windows

  • menu Menu

Setting the menu of the menu bar and setting it to null means that the menu bar is not set.

win.setProgressBar(progress)

  • progress Double

Set the progress value in the progress bar, with a valid range of 0, 1.0.

The progress is not displayed when the progress is less than 0; The result is uncertain when the progress is greater than 0.

On libix, only unity desktop environments are supported, and you need to indicate the .desktop file and add the file name to package.json. By default, it is app.getName().desktop .

win.setOverlayIcon(overlay, description) Windows 7+

Add a 16 x 16 pixel icon to the current taskbar, usually to override the status of some apps or to prompt the user directly.

win.setHasShadow(hasShadow) OS X

  • hasShadow (Boolean)

Set whether the window should have shadows. Invalid in Windows and Linux systems.

win.hasShadow() OS X

Go back to boolean and set whether the window has shadows. True is always returned on Windows and Linux systems .

win.setThumbarButtons(buttons) Windows 7+

  • buttons Array

The taskbar button layout in the window is out to add a thumbnail toolbar with a special button. Return a Boolean object to indicate whether this thumbnail toolbar was successfully added.

Because of space, the number of buttons on the thumbnail toolbar should not exceed 7. O nce set, you can't move it because of platform restrictions. But you can use an empty array to call the api to clear the buttons .

All buttons are an array of Button objects:

  • Button Object
    • Icon NativeImage - Icon displayed on the toolbar.
    • click Function
    • tooltip String (optional) - tooltip text.
    • Flags Array (optional) - Controls the state and behavior of button. By default, it is 'enabled' .

Flags is an array that contains the following Strings:

  • enabled - button is active and open to the user.
  • Disabled -button is not available. Currently it has a visible state to indicate that it will not respond to your behavior.
  • dismissonclick - Click on button and this acronym window closes directly.
  • Nobackground - Does not draw borders, only uses images.
  • Hidden - button is not visible to the user.
  • noninteractive - button is available but not responsive; I t also does not show the status of the press. Its value means that this is an instance that uses button in the ticket.

win.showDefinitionForSelection() OS X

A pop-up dictionary is displayed Chinese the interface to find the selected words.

win.setAutoHideMenuBar(hide)

  • hide Boolean

Set whether the window's menu bar can be hidden automatically. Once set, it is displayed only when the user presses the Alt key.

If the menu bar is already visible, calling setAutoHideMenuBar (true) is not immediately hidden.

win.isMenuBarAutoHide()

Back to boolean, whether the window's menu bar can be automatically hidden.

win.setMenuBarVisibility(visible)

  • visible Boolean

Set whether the menu bar is visible. If the menu bar is automatically hidden, the user can still press the Alt key to display.

win.isMenuBarVisible()

Back to boolean, whether the menu bar is visible.

win.setVisibleOnAllWorkspaces(visible)

  • visible Boolean

Set whether the window is visible everywhere.

Note: This api is not valid in windows.

win.isVisibleOnAllWorkspaces()

Return to boolean and see if the window is visible everywhere.

Note: False is always returned on windows.

win.setIgnoreMouseEvents(ignore) OS X

  • ignore Boolean

Ignore all mouse events in the window.