Author: saqibkhan

  • BrowserView

    Note The BrowserView class is deprecated, and replaced by the new WebContentsView class.

    BrowserView can be used to embed additional web content into a BrowserWindow. It is like a child window, except that it is positioned relative to its owning window. It is meant to be an alternative to the webview tag.

    Class: BrowserView

    Create and control views.

    Note The BrowserView class is deprecated, and replaced by the new WebContentsView class.

    Process: Main

    This module cannot be used until the ready event of the app module is emitted.

    Example

    // In the main process.
    const { app, BrowserView, BrowserWindow } = require('electron')

    app.whenReady().then(() => {
    const win = new BrowserWindow({ width: 800, height: 600 })

    const view = new BrowserView()
    win.setBrowserView(view)
    view.setBounds({ x: 0, y: 0, width: 300, height: 300 })
    view.webContents.loadURL('https://electronjs.org')
    })

    new BrowserView([options]) Experimental Deprecated

    • options Object (optional)
      • webPreferencesWebPreferences (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. 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. 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.
        • 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 options 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 animateanimateOnce 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 boolean (optional) – Whether to enable offscreen rendering for the browser window. Defaults to false. See the offscreen rendering tutorial for more details.
        • 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 (ArrayObjectJSON, 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 falseNote: 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-requireduser-gesture-requireddocument-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 trueNote: 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.

    Instance Properties

    Objects created with new BrowserView have the following properties:

    view.webContents Experimental Deprecated

    WebContents object owned by this view.

    Instance Methods

    Objects created with new BrowserView have the following instance methods:

    view.setAutoResize(options) Experimental Deprecated

    • options Object
      • width boolean (optional) – If true, the view’s width will grow and shrink together with the window. false by default.
      • height boolean (optional) – If true, the view’s height will grow and shrink together with the window. false by default.
      • horizontal boolean (optional) – If true, the view’s x position and width will grow and shrink proportionally with the window. false by default.
      • vertical boolean (optional) – If true, the view’s y position and height will grow and shrink proportionally with the window. false by default.

    view.setBounds(bounds) Experimental Deprecated

    Resizes and moves the view to the supplied bounds relative to the window.

    view.getBounds() Experimental Deprecated

    Returns Rectangle

    The bounds of this BrowserView instance as Object.

    view.setBackgroundColor(color) Experimental Deprecated

    • color string – Color in Hex, RGB, ARGB, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type.

    Examples of valid color values:

    • Hex
      • #fff (RGB)
      • #ffff (ARGB)
      • #ffffff (RRGGBB)
      • #ffffffff (AARRGGBB)
    • RGB
      • rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)
        • e.g. rgb(255, 255, 255)
    • RGBA
      • rgba\(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)\)
        • e.g. rgba(255, 255, 255, 1.0)
    • HSL
      • hsl\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)
        • e.g. hsl(200, 20%, 50%)
    • HSLA
      • hsla\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)
        • e.g. hsla(200, 20%, 50%, 0.5)
    • Color name
      • Options are listed in SkParseColor.cpp
      • Similar to CSS Color Module Level 3 keywords, but case-sensitive.
        • e.g. blueviolet or red

    Note: Hex format with alpha takes AARRGGBB or ARGBnot RRGGBBAA or RGB.

  • 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, the BrowserWindow 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 })

    Parent and child windows

    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.

    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 })

    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.

    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])

    • optionsBaseWindowConstructorOptions (optional)
      • width Integer (optional) – Window’s width in pixels. Default is 800.
      • height Integer (optional) – Window’s height in pixels. Default is 600.
      • x Integer (optional) – (required if y is used) Window’s left offset from screen. Default is to center the window.
      • y Integer (optional) – (required if x is used) Window’s top offset from screen. Default is to center the window.
      • useContentSize boolean (optional) – The width and height would be used as web page’s size, which means the actual window’s size will include window frame’s size and be slightly larger. Default is false.
      • center boolean (optional) – Show window in the center of the screen. Default is false.
      • minWidth Integer (optional) – Window’s minimum width. Default is 0.
      • minHeight Integer (optional) – Window’s minimum height. Default is 0.
      • maxWidth Integer (optional) – Window’s maximum width. Default is no limit.
      • maxHeight Integer (optional) – Window’s maximum height. Default is no limit.
      • resizable boolean (optional) – Whether window is resizable. Default is true.
      • movable boolean (optional) macOS Windows – Whether window is movable. This is not implemented on Linux. Default is true.
      • minimizable boolean (optional) macOS Windows – Whether window is minimizable. This is not implemented on Linux. Default is true.
      • maximizable boolean (optional) macOS Windows – Whether window is maximizable. This is not implemented on Linux. Default is true.
      • closable boolean (optional) macOS Windows – Whether window is closable. This is not implemented on Linux. Default is true.
      • focusable boolean (optional) – Whether the window can be focused. Default is true. On Windows setting focusable: false also implies setting skipTaskbar: true. On Linux setting focusable: false makes the window stop interacting with wm, so the window will always stay on top in all workspaces.
      • alwaysOnTop boolean (optional) – Whether the window should always stay on top of other windows. Default is false.
      • fullscreen boolean (optional) – Whether the window should show in fullscreen. When explicitly set to false the fullscreen button will be hidden or disabled on macOS. Default is false.
      • fullscreenable boolean (optional) – Whether the window can be put into fullscreen mode. On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. Default is true.
      • simpleFullscreen boolean (optional) macOS – Use pre-Lion fullscreen on macOS. Default is false.
      • skipTaskbar boolean (optional) macOS Windows – Whether to show the window in taskbar. Default is 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. Default is false.
      • title string (optional) – Default window title. Default is "Electron". If the HTML tag <title> is defined in the HTML file loaded by loadURL(), this property will be ignored.
      • icon (NativeImage | string) (optional) – The window icon. On Windows it is recommended to use ICO icons to get best visual effects, you can also leave it undefined so the executable’s icon will be used.
      • show boolean (optional) – Whether window should be shown when created. Default is true.
      • frame boolean (optional) – Specify false to create a frameless window. Default is true.
      • parent BaseWindow (optional) – Specify parent window. Default is null.
      • modal boolean (optional) – Whether this is a modal window. This only works when the window is a child window. Default is false.
      • acceptFirstMouse boolean (optional) macOS – Whether clicking an inactive window will also click through to the web contents. Default is false on macOS. This option is not configurable on other platforms.
      • disableAutoHideCursor boolean (optional) – Whether to hide cursor when typing. Default is false.
      • autoHideMenuBar boolean (optional) – Auto hide the menu bar unless the Alt key is pressed. Default is 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. Default is 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. Default is #FFF (white). See win.setBackgroundColor for more information.
      • hasShadow boolean (optional) – Whether window should have a shadow. Default is 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. Default is false.
      • transparent boolean (optional) – Makes the window transparent. Default is false. On Windows, does not work unless the window is frameless.
      • 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. Possible values are:
        • 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 string (optional) – The style of window title bar. Default is default. Possible values are:
        • default – Results in the standard title bar for macOS or Windows respectively.
        • hidden – Results in a hidden title bar and a full size content window. On macOS, the window still has the standard window controls (“traffic lights”) in the top left. On Windows and Linux, when combined with titleBarOverlay: true it will activate the Window Controls Overlay (see titleBarOverlay for more information), otherwise no window controls will be shown.
        • hiddenInset 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 – 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. Note: This option is currently experimental.
      • 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. Default is true. Setting this property to false will prevent the window from being fullscreenable.
      • thickFrame boolean (optional) – Use WS_THICKFRAME style for frameless windows on Windows, which adds standard window frame. Setting it to false will remove window shadow and window animations. Default is true.
      • vibrancy string (optional) macOS – Add a type of vibrancy effect to the window, only on macOS. Can be appearance-basedtitlebarselectionmenupopoversidebarheadersheetwindowhudfullscreen-uitooltipcontentunder-window, or under-page.
      • backgroundMaterial string (optional) Windows – Set the window’s system-drawn background material, including behind the non-client area. Can be autononemicaacrylic 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. Default is 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.

    When setting minimum or maximum window size with minWidth/maxWidthminHeight/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. Possible values are:

    • On Linux, possible types are desktopdocktoolbarsplashnotification.
      • 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 desktoptexturedpanel.
      • 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 use globalShortcut to receive input sparingly.
      • 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).
    • On Windows, possible type is toolbar.

    Instance Events

    Objects created with new BaseWindow emit the following events:

    Note: Some events are only available on specific operating systems and are labeled as such.

    Event: ‘close’

    Returns:

    • event Event

    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. For example:

    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.

    Event: ‘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: ‘session-end’ Windows

    Emitted when window session is going to end due to force shutdown or machine restart or session log off.

    Event: ‘blur’

    Emitted when the window loses focus.

    Event: ‘focus’

    Emitted when the window gains focus.

    Event: ‘show’

    Emitted when the window is shown.

    Event: ‘hide’

    Emitted when the window is hidden.

    Event: ‘maximize’

    Emitted when window is maximized.

    Event: ‘unmaximize’

    Emitted when the window exits from a maximized state.

    Event: ‘minimize’

    Emitted when the window is minimized.

    Event: ‘restore’

    Emitted when the window is restored from a minimized state.

    Event: ‘will-resize’ macOS Windows

    Returns:

    • event Event
    • newBounds Rectangle – Size the window is being resized to.
    • details Object
      • edge (string) – The edge of the window being dragged for resizing. Can be bottomleftrighttop-lefttop-rightbottom-left or bottom-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 bottomtopleftrighttop-lefttop-rightbottom-leftbottom-right.
    • On macOS, possible values are bottom and right.
      • The value bottom is used to denote vertical resizing.
      • The value right is used to denote horizontal resizing.

    Event: ‘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

    Returns:

    • event Event
    • newBounds 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.

    Event: ‘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.

    Event: ‘enter-full-screen’

    Emitted when the window enters a full-screen state.

    Event: ‘leave-full-screen’

    Emitted when the window leaves a full-screen state.

    Event: ‘always-on-top-changed’

    Returns:

    • event Event
    • isAlwaysOnTop boolean

    Emitted when the window is set or unset to show always on top of other windows.

    Event: ‘app-command’ Windows Linux

    Returns:

    • event Event
    • command string

    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 { 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.
    }
    })

    The following app commands are explicitly supported on Linux:

    • browser-backward
    • browser-forward

    Event: ‘swipe’ macOS

    Returns:

    • event Event
    • direction string

    Emitted on 3-finger swipe. Possible directions are uprightdownleft.

    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

    Returns:

    • event Event
    • rotation Float

    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.

    Event: ‘new-window-for-tab’ macOS

    Emitted when the native new tab button is clicked.

    Event: ‘system-context-menu’ Windows

    Returns:

    • event Event
    • point Point – The screen coordinates the context menu was triggered at

    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.

    Static Methods

    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.

    Instance Properties

    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

    Integer property representing the unique ID of the window. Each ID is unique among all BaseWindow instances of the entire Electron application.

    win.contentView

    View property for the content view of the window.

    win.tabbingIdentifier macOS Readonly

    string (optional) property that is equal to the tabbingIdentifier passed to the BrowserWindow constructor or undefined if none was set.

    win.autoHideMenuBar

    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

    boolean property that determines whether the window is in simple (pre-Lion) fullscreen mode.

    win.fullScreen

    boolean property that determines whether the window is in fullscreen mode.

    win.focusable Windows macOS

    boolean property that determines whether the window is focusable.

    win.visibleOnAllWorkspaces macOS Linux

    boolean property that determines whether the window is visible on all workspaces.

    Note: Always returns false on Windows.

    win.shadow

    boolean property that determines whether the window has a shadow.

    win.menuBarVisible Windows Linux

    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

    boolean property that determines whether the window is in kiosk mode.

    win.documentEdited macOS

    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

    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

    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

    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

    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

    boolean property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.

    win.resizable

    boolean property that determines whether the window can be manually resized by user.

    win.closable macOS Windows

    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

    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

    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

    string property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users.

    Instance Methods

    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)

    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()

    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.

    win.blur()

    Removes focus from the window.

    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.

    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)

    • flag boolean

    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.

    win.setSimpleFullScreen(flag) macOS

    • flag boolean

    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])

    • aspectRatio Float – The aspect ratio to maintain for some portion of the content view.
    • extraSize Size (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 @1920×1080) 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: win.setAspectRatio(0).

    win.setBackgroundColor(backgroundColor)

    • backgroundColor string – Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type.

    Examples of valid backgroundColor values:

    • Hex
      • #fff (shorthand RGB)
      • #ffff (shorthand ARGB)
      • #ffffff (RGB)
      • #ffffffff (ARGB)
    • RGB
      • rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)
        • e.g. rgb(255, 255, 255)
    • RGBA
      • rgba\(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)\)
        • e.g. rgba(255, 255, 255, 1.0)
    • HSL
      • hsl\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)
        • e.g. hsl(200, 20%, 50%)
    • HSLA
      • hsla\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)
        • e.g. hsla(200, 20%, 50%, 0.5)
    • Color name
      • Options are listed in SkParseColor.cpp
      • Similar to CSS Color Module Level 3 keywords, but case-sensitive.
        • e.g. blueviolet or red

    Sets the background color of the window. See Setting backgroundColor.

    win.previewFile(path[, displayName]) macOS

    • path string – The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open.
    • displayName string (optional) – The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to path.

    Uses Quick Look to preview a file at a given path.

    win.closeFilePreview() macOS

    Closes the currently open Quick Look panel.

    win.setBounds(bounds[, animate])

    • bounds Partial<Rectangle>
    • animate boolean (optional) macOS

    Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values.

    const { BaseWindow } = require('electron')
    const win = new BaseWindow()

    // set all bounds properties
    win.setBounds({ x: 440, y: 225, width: 800, height: 600 })

    // set a single bounds property
    win.setBounds({ width: 100 })

    // { x: 440, y: 225, width: 100, height: 600 }
    console.log(win.getBounds())

    Note: On macOS, the y-coordinate value cannot be smaller than the Tray height. The tray height has changed over time and depends on the operating system, but is between 20-40px. Passing a value lower than the tray height will result in a window that is flush to the tray.

    win.getBounds()

    Returns Rectangle – The bounds of the window as Object.

    Note: On macOS, the y-coordinate value returned will be at minimum the Tray height. For example, calling win.setBounds({ x: 25, y: 20, width: 800, height: 600 }) with a tray height of 38 means that win.getBounds() will return { x: 25, y: 38, width: 800, height: 600 }.

    win.getBackgroundColor()

    Returns string – Gets the background color of the window in Hex (#RRGGBB) format.

    See Setting backgroundColor.

    Note: The alpha value is not returned alongside the red, green, and blue values.

    win.setContentBounds(bounds[, animate])

    • bounds Rectangle
    • animate boolean (optional) macOS

    Resizes and moves the window’s client area (e.g. the web page) to the supplied bounds.

    win.getContentBounds()

    Returns Rectangle – The bounds of the window’s client area as Object.

    win.getNormalBounds()

    Returns Rectangle – Contains the window bounds of the normal state

    Note: whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same Rectangle.

    win.setEnabled(enable)

    • enable boolean

    Disable or enable the window.

    win.isEnabled()

    Returns boolean – whether the window is enabled.

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

    • width Integer
    • height Integer
    • animate boolean (optional) macOS

    Resizes the window to width and height. If width or height are below any set minimum size constraints the window will snap to its minimum size.

    win.getSize()

    Returns Integer[] – Contains the window’s width and height.

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

    • width Integer
    • height Integer
    • animate boolean (optional) macOS

    Resizes the window’s client area (e.g. the web page) to width and height.

    win.getContentSize()

    Returns Integer[] – Contains the window’s client area’s width and height.

    win.setMinimumSize(width, height)

    • width Integer
    • height Integer

    Sets the minimum size of window to width and height.

    win.getMinimumSize()

    Returns Integer[] – Contains the window’s minimum width and height.

    win.setMaximumSize(width, height)

    • width Integer
    • height Integer

    Sets the maximum size of window to width and height.

    win.getMaximumSize()

    Returns Integer[] – Contains the window’s maximum width and height.

    win.setResizable(resizable)

    • resizable boolean

    Sets whether the window can be manually resized by the user.

    win.isResizable()

    Returns boolean – Whether the window can be manually resized by the user.

    win.setMovable(movable) macOS Windows

    • movable boolean

    Sets whether the window can be moved by user. On Linux does nothing.

    win.isMovable() macOS Windows

    Returns boolean – Whether the window can be moved by user.

    On Linux always returns true.

    win.setMinimizable(minimizable) macOS Windows

    • minimizable boolean

    Sets whether the window can be manually minimized by user. On Linux does nothing.

    win.isMinimizable() macOS Windows

    Returns boolean – Whether the window can be manually minimized by the user.

    On Linux always returns true.

    win.setMaximizable(maximizable) macOS Windows

    • maximizable boolean

    Sets whether the window can be manually maximized by user. On Linux does nothing.

    win.isMaximizable() macOS Windows

    Returns boolean – Whether the window can be manually maximized by user.

    On Linux always returns true.

    win.setFullScreenable(fullscreenable)

    • fullscreenable boolean

    Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.

    win.isFullScreenable()

    Returns boolean – Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.

    win.setClosable(closable) macOS Windows

    • closable boolean

    Sets whether the window can be manually closed by user. On Linux does nothing.

    win.isClosable() macOS Windows

    Returns boolean – Whether the window can be manually closed by user.

    On Linux always returns true.

    win.setHiddenInMissionControl(hidden) macOS

    • hidden boolean

    Sets whether the window will be hidden when the user toggles into mission control.

    win.isHiddenInMissionControl() macOS

    Returns boolean – Whether the window will be hidden when the user toggles into mission control.

    win.setAlwaysOnTop(flag[, level][, relativeLevel])

    • flag boolean
    • level string (optional) macOS Windows – Values include normalfloatingtorn-off-menumodal-panelmain-menustatuspop-up-menuscreen-saver, and dock (Deprecated). The default is floating when flag is true. The level is reset to normal when the flag is false. Note that from floating to status included, the window is placed below the Dock on macOS and below the taskbar on Windows. From pop-up-menu to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the macOS docs for more details.
    • relativeLevel Integer (optional) macOS – The number of layers higher to set this window relative to the given level. The default is 0. Note that Apple discourages setting levels higher than 1 above screen-saver.

    Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on.

    win.isAlwaysOnTop()

    Returns boolean – Whether the window is always on top of other windows.

    win.moveAbove(mediaSourceId)

    • mediaSourceId string – Window id in the format of DesktopCapturerSource’s id. For example “window:1869:0”.

    Moves window above the source window in the sense of z-order. If the mediaSourceId is not of type window or if the window does not exist then this method throws an error.

    win.moveTop()

    Moves window to top(z-order) regardless of focus

    win.center()

    Moves window to the center of the screen.

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

    • x Integer
    • y Integer
    • animate boolean (optional) macOS

    Moves window to x and y.

    win.getPosition()

    Returns Integer[] – Contains the window’s current position.

    win.setTitle(title)

    • title string

    Changes the title of native window to title.

    win.getTitle()

    Returns string – The title of the native window.

    Note: The title of the web page can be different from the title of the native window.

    win.setSheetOffset(offsetY[, offsetX]) macOS

    • offsetY Float
    • offsetX Float (optional)

    Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example:

    const { BaseWindow } = require('electron')
    const win = new BaseWindow()

    const toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
    win.setSheetOffset(toolbarRect.height)

    win.flashFrame(flag)

    • flag boolean

    Starts or stops flashing the window to attract user’s attention.

    win.setSkipTaskbar(skip) macOS Windows

    • skip boolean

    Makes the window not show in the taskbar.

    win.setKiosk(flag)

    • flag boolean

    Enters or leaves kiosk mode.

    win.isKiosk()

    Returns boolean – Whether the window is in kiosk mode.

    win.isTabletMode() Windows

    Returns boolean – Whether the window is in Windows 10 tablet mode.

    Since Windows 10 users can use their PC as tablet, under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons.

    This API returns whether the window is in tablet mode, and the resize event can be be used to listen to changes to tablet mode.

    win.getMediaSourceId()

    Returns string – Window id in the format of DesktopCapturerSource’s id. For example “window:1324:0”.

    More precisely the format is window:id:other_id where id is HWND on Windows, CGWindowID (uint64_t) on macOS and Window (unsigned long) on Linux. other_id is used to identify web contents (tabs) so within the same top level window.

    win.getNativeWindowHandle()

    Returns Buffer – The platform-specific handle of the window.

    The native type of the handle is HWND on Windows, NSView* on macOS, and Window (unsigned long) on Linux.

    win.hookWindowMessage(message, callback) Windows

    • message Integer
    • callback Function
      • wParam Buffer – The wParam provided to the WndProc
      • lParam Buffer – The lParam provided to the WndProc

    Hooks a windows message. The callback is called when the message is received in the WndProc.

    win.isWindowMessageHooked(message) Windows

    • message Integer

    Returns boolean – true or false depending on whether the message is hooked.

    win.unhookWindowMessage(message) Windows

    • message Integer

    Unhook the window message.

    win.unhookAllWindowMessages() Windows

    Unhooks all of the window messages.

    win.setRepresentedFilename(filename) macOS

    • filename string

    Sets the pathname of the file the window represents, and the icon of the file will show in window’s title bar.

    win.getRepresentedFilename() macOS

    Returns string – The pathname of the file the window represents.

    win.setDocumentEdited(edited) macOS

    • edited boolean

    Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to true.

    win.isDocumentEdited() macOS

    Returns boolean – Whether the window’s document has been edited.

    win.setMenu(menu) Linux Windows

    • menu Menu | null

    Sets the menu as the window’s menu bar.

    win.removeMenu() Linux Windows

    Remove the window’s menu bar.

    win.setProgressBar(progress[, options])

    • progress Double
    • options Object (optional)
      • mode string Windows – Mode for the progress bar. Can be nonenormalindeterminateerror or paused.

    Sets progress value in progress bar. Valid range is [0, 1.0].

    Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1.

    On Linux platform, only supports Unity desktop environment, you need to specify the *.desktop file name to desktopName field in package.json. By default, it will assume {app.name}.desktop.

    On Windows, a mode can be passed. Accepted values are nonenormalindeterminateerror, and paused. If you call setProgressBar without a mode set (but with a value within the valid range), normal will be assumed.

    win.setOverlayIcon(overlay, description) Windows

    • overlay NativeImage | null – the icon to display on the bottom right corner of the taskbar icon. If this parameter is null, the overlay is cleared
    • description string – a description that will be provided to Accessibility screen readers

    Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user.

    win.invalidateShadow() macOS

    Invalidates the window shadow so that it is recomputed based on the current window shape.

    BaseWindows that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation.

    win.setHasShadow(hasShadow)

    • hasShadow boolean

    Sets whether the window should have a shadow.

    win.hasShadow()

    Returns boolean – Whether the window has a shadow.

    win.setOpacity(opacity) Windows macOS

    • opacity number – between 0.0 (fully transparent) and 1.0 (fully opaque)

    Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the [0, 1] range.

    win.getOpacity()

    Returns number – between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1.

    win.setShape(rects) Windows Linux Experimental

    • rects Rectangle[] – Sets a shape on the window. Passing an empty list reverts the window to being rectangular.

    Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window.

    win.setThumbarButtons(buttons) Windows

    Returns boolean – Whether the buttons were added successfully

    Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a boolean object indicates whether the thumbnail has been added successfully.

    The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform’s limitation. But you can call the API with an empty array to clean the buttons.

    The buttons is an array of Button objects:

    • Button Object
      • icon NativeImage – The icon showing in thumbnail toolbar.
      • click Function
      • tooltip string (optional) – The text of the button’s tooltip.
      • flags string[] (optional) – Control specific states and behaviors of the button. By default, it is ['enabled'].

    The flags is an array that can include following strings:

    • enabled – The button is active and available to the user.
    • disabled – The button is disabled. It is present, but has a visual state indicating it will not respond to user action.
    • dismissonclick – When the button is clicked, the thumbnail window closes immediately.
    • nobackground – Do not draw a button border, use only the image.
    • hidden – The button is not shown to the user.
    • noninteractive – The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification.

    win.setThumbnailClip(region) Windows

    • region Rectangle – Region of the window

    Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: { x: 0, y: 0, width: 0, height: 0 }.

    win.setThumbnailToolTip(toolTip) Windows

    • toolTip string

    Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar.

    win.setAppDetails(options) Windows

    • options Object
      • appId string (optional) – Window’s App User Model ID. It has to be set, otherwise the other options will have no effect.
      • appIconPath string (optional) – Window’s Relaunch Icon.
      • appIconIndex Integer (optional) – Index of the icon in appIconPath. Ignored when appIconPath is not set. Default is 0.
      • relaunchCommand string (optional) – Window’s Relaunch Command.
      • relaunchDisplayName string (optional) – Window’s Relaunch Display Name.

    Sets the properties for the window’s taskbar button.

    Note: relaunchCommand and relaunchDisplayName must always be set together. If one of those properties is not set, then neither will be used.

    win.setIcon(icon) Windows Linux

    Changes window icon.

    win.setWindowButtonVisibility(visible) macOS

    • visible boolean

    Sets whether the window traffic light buttons should be visible.

    win.setAutoHideMenuBar(hide) Windows Linux

    • hide boolean

    Sets 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, calling setAutoHideMenuBar(true) won’t hide it immediately.

    win.isMenuBarAutoHide() Windows Linux

    Returns boolean – Whether menu bar automatically hides itself.

    win.setMenuBarVisibility(visible) Windows Linux

    • visible boolean

    Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single Alt key.

    win.isMenuBarVisible() Windows Linux

    Returns boolean – Whether the menu bar is visible.

    win.setVisibleOnAllWorkspaces(visible[, options]) macOS Linux

    • visible boolean
    • options Object (optional)
      • visibleOnFullScreen boolean (optional) macOS – Sets whether the window should be visible above fullscreen windows.
      • skipTransformProcessType boolean (optional) macOS – Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType.

    Sets whether the window should be visible on all workspaces.

    Note: This API does nothing on Windows.

    win.isVisibleOnAllWorkspaces() macOS Linux

    Returns boolean – Whether the window is visible on all workspaces.

    Note: This API always returns false on Windows.

    win.setIgnoreMouseEvents(ignore[, options])

    • ignore boolean
    • options Object (optional)
      • forward boolean (optional) macOS Windows – If true, forwards mouse move messages to Chromium, enabling mouse related events such as mouseleave. Only used when ignore is true. If ignore is false, forwarding is always disabled regardless of this value.

    Makes the window ignore all mouse events.

    All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events.

    win.setContentProtection(enable) macOS Windows

    • enable boolean

    Prevents the window contents from being captured by other apps.

    On macOS it sets the NSWindow’s sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with WDA_EXCLUDEFROMCAPTURE. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if WDA_MONITOR is applied capturing a black window.

    win.setFocusable(focusable) macOS Windows

    • focusable boolean

    Changes whether the window can be focused.

    On macOS it does not remove the focus from the window.

    win.isFocusable() macOS Windows

    Returns boolean – Whether the window can be focused.

    win.setParentWindow(parent)

    • parent BaseWindow | null

    Sets parent as current window’s parent window, passing null will turn current window into a top-level window.

    win.getParentWindow()

    Returns BaseWindow | null – The parent window or null if there is no parent.

    win.getChildWindows()

    Returns BaseWindow[] – All child windows.

    win.setAutoHideCursor(autoHide) macOS

    • autoHide boolean

    Controls whether to hide cursor when typing.

    win.selectPreviousTab() macOS

    Selects the previous tab when native tabs are enabled and there are other tabs in the window.

    win.selectNextTab() macOS

    Selects the next tab when native tabs are enabled and there are other tabs in the window.

    win.showAllTabs() macOS

    Shows or hides the tab overview when native tabs are enabled.

    win.mergeAllWindows() macOS

    Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window.

    win.moveTabToNewWindow() macOS

    Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window.

    win.toggleTabBar() macOS

    Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window.

    win.addTabbedWindow(baseWindow) macOS

    • baseWindow BaseWindow

    Adds a window as a tab on this window, after the tab for the window instance.

    win.setVibrancy(type) macOS

    • type string | null – Can be titlebarselectionmenupopoversidebarheadersheetwindowhudfullscreen-uitooltipcontentunder-window, or under-page. See the macOS documentation for more details.

    Adds a vibrancy effect to the window. Passing null or an empty string will remove the vibrancy effect on the window.

    win.setBackgroundMaterial(material) Windows

    • material string
      • auto – Let the Desktop Window Manager (DWM) automatically decide the system-drawn backdrop material for this window. This is the default.
      • none – Don’t draw any system backdrop.
      • mica – Draw the backdrop material effect corresponding to a long-lived window.
      • acrylic – Draw the backdrop material effect corresponding to a transient window.
      • tabbed – Draw the backdrop material effect corresponding to a window with a tabbed title bar.

    This method sets the browser window’s system-drawn background material, including behind the non-client area.

    See the Windows documentation for more details.

    Note: This method is only supported on Windows 11 22H2 and up.

    win.setWindowButtonPosition(position) macOS

    • position Point | null

    Set a custom position for the traffic light buttons in frameless window. Passing null will reset the position to default.

    win.getWindowButtonPosition() macOS

    Returns Point | null – The custom position for the traffic light buttons in frameless window, null will be returned when there is no custom position.

    win.setTouchBar(touchBar) macOS

    • touchBar TouchBar | null

    Sets the touchBar layout for the current window. Specifying null or undefined clears the touch bar. This method only has an effect if the machine has a touch bar.

    Note: The TouchBar API is currently experimental and may change or be removed in future Electron releases.

    win.setTitleBarOverlay(options) Windows Linux

    • options Object
      • color String (optional) – The CSS color of the Window Controls Overlay when enabled.
      • symbolColor String (optional) – The CSS color of the symbols on the Window Controls Overlay when enabled.
      • height Integer (optional) – The height of the title bar and Window Controls Overlay in pixels.

    On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay.

    On Linux, the symbolColor is automatically calculated to have minimum accessible contrast to the color if not explicitly set.

  • AutoUpdater

    Enable apps to automatically update themselves.

    Process: Main

    See also: A detailed guide about how to implement updates in your application.

    autoUpdater is an EventEmitter.

    Platform Notices

    Currently, only macOS and Windows are supported. There is no built-in support for auto-updater on Linux, so it is recommended to use the distribution’s package manager to update your app.

    In addition, there are some subtle differences on each platform:

    macOS

    On macOS, the autoUpdater module is built upon Squirrel.Mac, meaning you don’t need any special setup to make it work. For server-side requirements, you can read Server Support. Note that App Transport Security (ATS) applies to all requests made as part of the update process. Apps that need to disable ATS can add the NSAllowsArbitraryLoads key to their app’s plist.

    Note: Your application must be signed for automatic updates on macOS. This is a requirement of Squirrel.Mac.

    Windows

    On Windows, you have to install your app into a user’s machine before you can use the autoUpdater, so it is recommended that you use the electron-winstallerElectron Forge or the grunt-electron-installer package to generate a Windows installer.

    When using electron-winstaller or Electron Forge make sure you do not try to update your app the first time it runs (Also see this issue for more info). It’s also recommended to use electron-squirrel-startup to get desktop shortcuts for your app.

    The installer generated with Squirrel will create a shortcut icon with an Application User Model ID in the format of com.squirrel.PACKAGE_ID.YOUR_EXE_WITHOUT_DOT_EXE, examples are com.squirrel.slack.Slack and com.squirrel.code.Code. You have to use the same ID for your app with app.setAppUserModelId API, otherwise Windows will not be able to pin your app properly in task bar.

    Like Squirrel.Mac, Windows can host updates on S3 or any other static file host. You can read the documents of Squirrel.Windows to get more details about how Squirrel.Windows works.

    Events

    The autoUpdater object emits the following events:

    Event: ‘error’

    Returns:

    • error Error

    Emitted when there is an error while updating.

    Event: ‘checking-for-update’

    Emitted when checking if an update has started.

    Event: ‘update-available’

    Emitted when there is an available update. The update is downloaded automatically.

    Event: ‘update-not-available’

    Emitted when there is no available update.

    Event: ‘update-downloaded’

    Returns:

    • event Event
    • releaseNotes string
    • releaseName string
    • releaseDate Date
    • updateURL string

    Emitted when an update has been downloaded.

    On Windows only releaseName is available.

    Note: It is not strictly necessary to handle this event. A successfully downloaded update will still be applied the next time the application starts.

    Event: ‘before-quit-for-update’

    This event is emitted after a user calls quitAndInstall().

    When this API is called, the before-quit event is not emitted before all windows are closed. As a result you should listen to this event if you wish to perform actions before the windows are closed while a process is quitting, as well as listening to before-quit.

    Methods

    The autoUpdater object has the following methods:

    autoUpdater.setFeedURL(options)

    • options Object
      • url string
      • headers Record<string, string> (optional) macOS – HTTP request headers.
      • serverType string (optional) macOS – Can be json or default, see the Squirrel.Mac README for more information.

    Sets the url and initialize the auto updater.

    autoUpdater.getFeedURL()

    Returns string – The current update feed URL.

    autoUpdater.checkForUpdates()

    Asks the server whether there is an update. You must call setFeedURL before using this API.

    Note: If an update is available it will be downloaded automatically. Calling autoUpdater.checkForUpdates() twice will download the update two times.

    autoUpdater.quitAndInstall()

    Restarts the app and installs the update after it has been downloaded. It should only be called after update-downloaded has been emitted.

    Under the hood calling autoUpdater.quitAndInstall() will close all application windows first, and automatically call app.quit() after all windows have been closed.

    Note: It is not strictly necessary to call this function to apply an update, as a successfully downloaded update will always be applied the next time the application starts.

  • App

    Control your application’s event lifecycle.

    Process: Main

    The following example shows how to quit the application when the last window is closed:

    const { app } = require('electron')
    app.on('window-all-closed', () => {
    app.quit()
    })

    Events

    The app object emits the following events:

    Event: ‘will-finish-launching’

    Emitted when the application has finished basic startup. On Windows and Linux, the will-finish-launching event is the same as the ready event; on macOS, this event represents the applicationWillFinishLaunching notification of NSApplication.

    In most cases, you should do everything in the ready event handler.

    Event: ‘ready’

    Returns:

    Emitted once, when Electron has finished initializing. On macOS, launchInfo holds the userInfo of the NSUserNotification or information from UNNotificationResponse that was used to open the application, if it was launched from Notification Center. You can also call app.isReady() to check if this event has already fired and app.whenReady() to get a Promise that is fulfilled when Electron is initialized.

    Note: The ready event is only fired after the main process has finished running the first tick of the event loop. If an Electron API needs to be called before the ready event, ensure that it is called synchronously in the top-level context of the main process.

    Event: ‘window-all-closed’

    Emitted when all windows have been closed.

    If you do not subscribe to this event and all windows are closed, the default behavior is to quit the app; however, if you subscribe, you control whether the app quits or not. If the user pressed Cmd + Q, or the developer called app.quit(), Electron will first try to close all the windows and then emit the will-quit event, and in this case the window-all-closed event would not be emitted.

    Event: ‘before-quit’

    Returns:

    • event Event

    Emitted before the application starts closing its windows. Calling event.preventDefault() will prevent the default behavior, which is terminating the application.

    Note: If application quit was initiated by autoUpdater.quitAndInstall(), then before-quit is emitted after emitting close event on all windows and closing them.

    Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.

    Event: ‘will-quit’

    Returns:

    • event Event

    Emitted when all windows have been closed and the application will quit. Calling event.preventDefault() will prevent the default behavior, which is terminating the application.

    See the description of the window-all-closed event for the differences between the will-quit and window-all-closed events.

    Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.

    Event: ‘quit’

    Returns:

    • event Event
    • exitCode Integer

    Emitted when the application is quitting.

    Note: On Windows, this event will not be emitted if the app is closed due to a shutdown/restart of the system or a user logout.

    Event: ‘open-file’ macOS

    Returns:

    • event Event
    • path string

    Emitted when the user wants to open a file with the application. The open-file event is usually emitted when the application is already open and the OS wants to reuse the application to open the file. open-file is also emitted when a file is dropped onto the dock and the application is not yet running. Make sure to listen for the open-file event very early in your application startup to handle this case (even before the ready event is emitted).

    You should call event.preventDefault() if you want to handle this event.

    On Windows, you have to parse process.argv (in the main process) to get the filepath.

    Event: ‘open-url’ macOS

    Returns:

    • event Event
    • url string

    Emitted when the user wants to open a URL with the application. Your application’s Info.plist file must define the URL scheme within the CFBundleURLTypes key, and set NSPrincipalClass to AtomApplication.

    As with the open-file event, be sure to register a listener for the open-url event early in your application startup to detect if the application is being opened to handle a URL. If you register the listener in response to a ready event, you’ll miss URLs that trigger the launch of your application.

    Event: ‘activate’ macOS

    Returns:

    • event Event
    • hasVisibleWindows boolean

    Emitted when the application is activated. Various actions can trigger this event, such as launching the application for the first time, attempting to re-launch the application when it’s already running, or clicking on the application’s dock or taskbar icon.

    Event: ‘did-become-active’ macOS

    Returns:

    • event Event

    Emitted when the application becomes active. This differs from the activate event in that did-become-active is emitted every time the app becomes active, not only when Dock icon is clicked or application is re-launched. It is also emitted when a user switches to the app via the macOS App Switcher.

    Event: ‘did-resign-active’ macOS

    Returns:

    • event Event

    Emitted when the app is no longer active and doesn’t have focus. This can be triggered, for example, by clicking on another application or by using the macOS App Switcher to switch to another application.

    Event: ‘continue-activity’ macOS

    Returns:

    • event Event
    • type string – A string identifying the activity. Maps to NSUserActivity.activityType.
    • userInfo unknown – Contains app-specific state stored by the activity on another device.
    • details Object
      • webpageURL string (optional) – A string identifying the URL of the webpage accessed by the activity on another device, if available.

    Emitted during Handoff when an activity from a different device wants to be resumed. You should call event.preventDefault() if you want to handle this event.

    A user activity can be continued only in an app that has the same developer Team ID as the activity’s source app and that supports the activity’s type. Supported activity types are specified in the app’s Info.plist under the NSUserActivityTypes key.

    Event: ‘will-continue-activity’ macOS

    Returns:

    Emitted during Handoff before an activity from a different device wants to be resumed. You should call event.preventDefault() if you want to handle this event.

    Event: ‘continue-activity-error’ macOS

    Returns:

    • event Event
    • type string – A string identifying the activity. Maps to NSUserActivity.activityType.
    • error string – A string with the error’s localized description.

    Emitted during Handoff when an activity from a different device fails to be resumed.

    Event: ‘activity-was-continued’ macOS

    Returns:

    • event Event
    • type string – A string identifying the activity. Maps to NSUserActivity.activityType.
    • userInfo unknown – Contains app-specific state stored by the activity.

    Emitted during Handoff after an activity from this device was successfully resumed on another one.

    Event: ‘update-activity-state’ macOS

    Returns:

    • event Event
    • type string – A string identifying the activity. Maps to NSUserActivity.activityType.
    • userInfo unknown – Contains app-specific state stored by the activity.

    Emitted when Handoff is about to be resumed on another device. If you need to update the state to be transferred, you should call event.preventDefault() immediately, construct a new userInfo dictionary and call app.updateCurrentActivity() in a timely manner. Otherwise, the operation will fail and continue-activity-error will be called.

    Event: ‘new-window-for-tab’ macOS

    Returns:

    • event Event

    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

    Event: ‘browser-window-blur’

    Returns:

    Emitted when a browserWindow gets blurred.

    Event: ‘browser-window-focus’

    Returns:

    Emitted when a browserWindow gets focused.

    Event: ‘browser-window-created’

    Returns:

    Emitted when a new browserWindow is created.

    Event: ‘web-contents-created’

    Returns:

    Emitted when a new webContents is created.

    Event: ‘certificate-error’

    Returns:

    • event Event
    • webContents WebContents
    • url string
    • error string – The error code
    • certificate Certificate
    • callback Function
      • isTrusted boolean – Whether to consider the certificate as trusted
    • isMainFrame boolean

    Emitted when failed to verify the certificate for url, to trust the certificate you should prevent the default behavior with event.preventDefault() and call callback(true).

    const { app } = require('electron')

    app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
    if (url === 'https://github.com') {
    // Verification logic.
    event.preventDefault()
    callback(true)
    } else {
    callback(false)
    }
    })

    Event: ‘select-client-certificate’

    Returns:

    Emitted when a client certificate is requested.

    The url corresponds to the navigation entry requesting the client certificate and callback can be called with an entry filtered from the list. Using event.preventDefault() prevents the application from using the first certificate from the store.

    const { app } = require('electron')

    app.on('select-client-certificate', (event, webContents, url, list, callback) => {
    event.preventDefault()
    callback(list[0])
    })

    Event: ‘login’

    Returns:

    • event Event
    • webContents WebContents
    • authenticationResponseDetails Object
      • url URL
    • authInfo Object
      • isProxy boolean
      • scheme string
      • host string
      • port Integer
      • realm string
    • callback Function
      • username string (optional)
      • password string (optional)

    Emitted when webContents wants to do basic auth.

    The default behavior is to cancel all authentications. To override this you should prevent the default behavior with event.preventDefault() and call callback(username, password) with the credentials.

    const { app } = require('electron')

    app.on('login', (event, webContents, details, authInfo, callback) => {
    event.preventDefault()
    callback('username', 'secret')
    })

    If callback is called without a username or password, the authentication request will be cancelled and the authentication error will be returned to the page.

    Event: ‘gpu-info-update’

    Emitted whenever there is a GPU info update.

    Event: ‘render-process-gone’

    Returns:

    Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed.

    Event: ‘child-process-gone’

    Returns:

    • event Event
    • details Object
      • type string – Process type. One of the following values:
        • Utility
        • Zygote
        • Sandbox helper
        • GPU
        • Pepper Plugin
        • Pepper Plugin Broker
        • Unknown
      • reason string – The reason the child process is gone. Possible values:
        • clean-exit – Process exited with an exit code of zero
        • abnormal-exit – Process exited with a non-zero exit code
        • killed – Process was sent a SIGTERM or otherwise killed externally
        • crashed – Process crashed
        • oom – Process ran out of memory
        • launch-failed – Process never successfully launched
        • integrity-failure – Windows code integrity checks failed
      • exitCode number – The exit code for the process (e.g. status from waitpid if on posix, from GetExitCodeProcess on Windows).
      • serviceName string (optional) – The non-localized name of the process.
      • name string (optional) – The name of the process. Examples for utility: Audio ServiceContent Decryption Module ServiceNetwork ServiceVideo Capture, etc.

    Emitted when the child process unexpectedly disappears. This is normally because it was crashed or killed. It does not include renderer processes.

    Event: ‘accessibility-support-changed’ macOS Windows

    Returns:

    • event Event
    • accessibilitySupportEnabled boolean – true when Chrome’s accessibility support is enabled, false otherwise.

    Emitted when Chrome’s accessibility support changes. This event fires when assistive technologies, such as screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details.

    Event: ‘session-created’

    Returns:

    Emitted when Electron has created a new session.

    const { app } = require('electron')

    app.on('session-created', (session) => {
    console.log(session)
    })

    Event: ‘second-instance’

    Returns:

    • event Event
    • argv string[] – An array of the second instance’s command line arguments
    • workingDirectory string – The second instance’s working directory
    • additionalData unknown – A JSON object of additional data passed from the second instance

    This event will be emitted inside the primary instance of your application when a second instance has been executed and calls app.requestSingleInstanceLock().

    argv is an Array of the second instance’s command line arguments, and workingDirectory is its current working directory. Usually applications respond to this by making their primary window focused and non-minimized.

    Note: argv will not be exactly the same list of arguments as those passed to the second instance. The order might change and additional arguments might be appended. If you need to maintain the exact same arguments, it’s advised to use additionalData instead.

    Note: If the second instance is started by a different user than the first, the argv array will not include the arguments.

    This event is guaranteed to be emitted after the ready event of app gets emitted.

    Note: Extra command line arguments might be added by Chromium, such as --original-process-start-time.

    Methods

    The app object has the following methods:

    Note: Some methods are only available on specific operating systems and are labeled as such.

    app.quit()

    Try to close all windows. The before-quit event will be emitted first. If all windows are successfully closed, the will-quit event will be emitted and by default the application will terminate.

    This method guarantees that all beforeunload and unload event handlers are correctly executed. It is possible that a window cancels the quitting by returning false in the beforeunload event handler.

    app.exit([exitCode])

    • exitCode Integer (optional)

    Exits immediately with exitCodeexitCode defaults to 0.

    All windows will be closed immediately without asking the user, and the before-quit and will-quit events will not be emitted.

    app.relaunch([options])

    • options Object (optional)
      • args string[] (optional)
      • execPath string (optional)

    Relaunches the app when current instance exits.

    By default, the new instance will use the same working directory and command line arguments with current instance. When args is specified, the args will be passed as command line arguments instead. When execPath is specified, the execPath will be executed for relaunch instead of current app.

    Note that this method does not quit the app when executed, you have to call app.quit or app.exit after calling app.relaunch to make the app restart.

    When app.relaunch is called for multiple times, multiple instances will be started after current instance exited.

    An example of restarting current instance immediately and adding a new command line argument to the new instance:

    const { app } = require('electron')

    app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
    app.exit(0)

    app.isReady()

    Returns boolean – true if Electron has finished initializing, false otherwise. See also app.whenReady().

    app.whenReady()

    Returns Promise<void> – fulfilled when Electron is initialized. May be used as a convenient alternative to checking app.isReady() and subscribing to the ready event if the app is not ready yet.

    app.focus([options])

    • options Object (optional)
      • steal boolean macOS – Make the receiver the active app even if another app is currently active.

    On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application’s first window.

    You should seek to use the steal option as sparingly as possible.

    app.hide() macOS

    Hides all application windows without minimizing them.

    app.isHidden() macOS

    Returns boolean – true if the application—including all of its windows—is hidden (e.g. with Command-H), false otherwise.

    app.show() macOS

    Shows application windows after they were hidden. Does not automatically focus them.

    app.setAppLogsPath([path])

    • path string (optional) – A custom path for your logs. Must be absolute.

    Sets or creates a directory your app’s logs which can then be manipulated with app.getPath() or app.setPath(pathName, newPath).

    Calling app.setAppLogsPath() without a path parameter will result in this directory being set to ~/Library/Logs/YourAppName on macOS, and inside the userData directory on Linux and Windows.

    app.getAppPath()

    Returns string – The current application directory.

    app.getPath(name)

    • name string – You can request the following paths by the name:
      • home User’s home directory.
      • appData Per-user application data directory, which by default points to:
        • %APPDATA% on Windows
        • $XDG_CONFIG_HOME or ~/.config on Linux
        • ~/Library/Application Support on macOS
      • userData The directory for storing your app’s configuration files, which by default is the appData directory appended with your app’s name. By convention files storing user data should be written to this directory, and it is not recommended to write large files here because some environments may backup this directory to cloud storage.
      • sessionData The directory for storing data generated by Session, such as localStorage, cookies, disk cache, downloaded dictionaries, network state, devtools files. By default this points to userData. Chromium may write very large disk cache here, so if your app does not rely on browser storage like localStorage or cookies to save user data, it is recommended to set this directory to other locations to avoid polluting the userData directory.
      • temp Temporary directory.
      • exe The current executable file.
      • module The libchromiumcontent library.
      • desktop The current user’s Desktop directory.
      • documents Directory for a user’s “My Documents”.
      • downloads Directory for a user’s downloads.
      • music Directory for a user’s music.
      • pictures Directory for a user’s pictures.
      • videos Directory for a user’s videos.
      • recent Directory for the user’s recent files (Windows only).
      • logs Directory for your app’s log folder.
      • crashDumps Directory where crash dumps are stored.

    Returns string – A path to a special directory or file associated with name. On failure, an Error is thrown.

    If app.getPath('logs') is called without called app.setAppLogsPath() being called first, a default log directory will be created equivalent to calling app.setAppLogsPath() without a path parameter.

    app.getFileIcon(path[, options])

    • path string
    • options Object (optional)
      • size string
        • small – 16×16
        • normal – 32×32
        • large – 48×48 on Linux, 32×32 on Windows, unsupported on macOS.

    Returns Promise<NativeImage> – fulfilled with the app’s icon, which is a NativeImage.

    Fetches a path’s associated icon.

    On Windows, there a 2 kinds of icons:

    • Icons associated with certain file extensions, like .mp3.png, etc.
    • Icons inside the file itself, like .exe.dll.ico.

    On Linux and macOS, icons depend on the application associated with file mime type.

    app.setPath(name, path)

    • name string
    • path string

    Overrides the path to a special directory or file associated with name. If the path specifies a directory that does not exist, an Error is thrown. In that case, the directory should be created with fs.mkdirSync or similar.

    You can only override paths of a name defined in app.getPath.

    By default, web pages’ cookies and caches will be stored under the sessionData directory. If you want to change this location, you have to override the sessionData path before the ready event of the app module is emitted.

    app.getVersion()

    Returns string – The version of the loaded application. If no version is found in the application’s package.json file, the version of the current bundle or executable is returned.

    app.getName()

    Returns string – The current application’s name, which is the name in the application’s package.json file.

    Usually the name field of package.json is a short lowercase name, according to the npm modules spec. You should usually also specify a productName field, which is your application’s full capitalized name, and which will be preferred over name by Electron.

    app.setName(name)

    • name string

    Overrides the current application’s name.

    Note: This function overrides the name used internally by Electron; it does not affect the name that the OS uses.

    app.getLocale()

    Returns string – The current application locale, fetched using Chromium’s l10n_util library. Possible return values are documented here.

    To set the locale, you’ll want to use a command line switch at app startup, which may be found here.

    Note: When distributing your packaged app, you have to also ship the locales folder.

    Note: This API must be called after the ready event is emitted.

    Note: To see example return values of this API compared to other locale and language APIs, see app.getPreferredSystemLanguages().

    app.getLocaleCountryCode()

    Returns string – User operating system’s locale two-letter ISO 3166 country code. The value is taken from native OS APIs.

    Note: When unable to detect locale country code, it returns empty string.

    app.getSystemLocale()

    Returns string – The current system locale. On Windows and Linux, it is fetched using Chromium’s i18n library. On macOS, [NSLocale currentLocale] is used instead. To get the user’s current system language, which is not always the same as the locale, it is better to use app.getPreferredSystemLanguages().

    Different operating systems also use the regional data differently:

    • Windows 11 uses the regional format for numbers, dates, and times.
    • macOS Monterey uses the region for formatting numbers, dates, times, and for selecting the currency symbol to use.

    Therefore, this API can be used for purposes such as choosing a format for rendering dates and times in a calendar app, especially when the developer wants the format to be consistent with the OS.

    Note: This API must be called after the ready event is emitted.

    Note: To see example return values of this API compared to other locale and language APIs, see app.getPreferredSystemLanguages().

    app.getPreferredSystemLanguages()

    Returns string[] – The user’s preferred system languages from most preferred to least preferred, including the country codes if applicable. A user can modify and add to this list on Windows or macOS through the Language and Region settings.

    The API uses GlobalizationPreferences (with a fallback to GetSystemPreferredUILanguages) on Windows, \[NSLocale preferredLanguages\] on macOS, and g_get_language_names on Linux.

    This API can be used for purposes such as deciding what language to present the application in.

    Here are some examples of return values of the various language and locale APIs with different configurations:

    On Windows, given application locale is German, the regional format is Finnish (Finland), and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese (China), Finnish, and Spanish (Latin America):

    app.getLocale() // 'de'
    app.getSystemLocale() // 'fi-FI'
    app.getPreferredSystemLanguages() // ['fr-CA', 'en-US', 'zh-Hans-CN', 'fi', 'es-419']

    On macOS, given the application locale is German, the region is Finland, and the preferred system languages from most to least preferred are French (Canada), English (US), Simplified Chinese, and Spanish (Latin America):

    app.getLocale() // 'de'
    app.getSystemLocale() // 'fr-FI'
    app.getPreferredSystemLanguages() // ['fr-CA', 'en-US', 'zh-Hans-FI', 'es-419']

    Both the available languages and regions and the possible return values differ between the two operating systems.

    As can be seen with the example above, on Windows, it is possible that a preferred system language has no country code, and that one of the preferred system languages corresponds with the language used for the regional format. On macOS, the region serves more as a default country code: the user doesn’t need to have Finnish as a preferred language to use Finland as the region,and the country code FI is used as the country code for preferred system languages that do not have associated countries in the language name.

    app.addRecentDocument(path) macOS Windows

    • path string

    Adds path to the recent documents list.

    This list is managed by the OS. On Windows, you can visit the list from the task bar, and on macOS, you can visit it from dock menu.

    app.clearRecentDocuments() macOS Windows

    Clears the recent documents list.

    app.setAsDefaultProtocolClient(protocol[, path, args])

    • protocol string – The name of your protocol, without ://. For example, if you want your app to handle electron:// links, call this method with electron as the parameter.
    • path string (optional) Windows – The path to the Electron executable. Defaults to process.execPath
    • args string[] (optional) Windows – Arguments passed to the executable. Defaults to an empty array

    Returns boolean – Whether the call succeeded.

    Sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to integrate your app deeper into the operating system. Once registered, all links with your-protocol:// will be opened with the current executable. The whole link, including protocol, will be passed to your application as a parameter.

    Note: On macOS, you can only register protocols that have been added to your app’s info.plist, which cannot be modified at runtime. However, you can change the file during build time via Electron ForgeElectron Packager, or by editing info.plist with a text editor. Please refer to Apple’s documentation for details.

    Note: In a Windows Store environment (when packaged as an appx) this API will return true for all calls but the registry key it sets won’t be accessible by other applications. In order to register your Windows Store application as a default protocol handler you must declare the protocol in your manifest.

    The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally.

    app.removeAsDefaultProtocolClient(protocol[, path, args]) macOS Windows

    • protocol string – The name of your protocol, without ://.
    • path string (optional) Windows – Defaults to process.execPath
    • args string[] (optional) Windows – Defaults to an empty array

    Returns boolean – Whether the call succeeded.

    This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler.

    app.isDefaultProtocolClient(protocol[, path, args])

    • protocol string – The name of your protocol, without ://.
    • path string (optional) Windows – Defaults to process.execPath
    • args string[] (optional) Windows – Defaults to an empty array

    Returns boolean – Whether the current executable is the default handler for a protocol (aka URI scheme).

    Note: On macOS, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking ~/Library/Preferences/com.apple.LaunchServices.plist on the macOS machine. Please refer to Apple’s documentation for details.

    The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.

    app.getApplicationNameForProtocol(url)

    • url string – a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including :// at a minimum (e.g. https://).

    Returns string – Name of the application handling the protocol, or an empty string if there is no handler. For instance, if Electron is the default handler of the URL, this could be Electron on Windows and Mac. However, don’t rely on the precise format which is not guaranteed to remain unchanged. Expect a different format on Linux, possibly with a .desktop suffix.

    This method returns the application name of the default handler for the protocol (aka URI scheme) of a URL.

    app.getApplicationInfoForProtocol(url) macOS Windows

    • url string – a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including :// at a minimum (e.g. https://).

    Returns Promise<Object> – Resolve with an object containing the following:

    • icon NativeImage – the display icon of the app handling the protocol.
    • path string – installation path of the app handling the protocol.
    • name string – display name of the app handling the protocol.

    This method returns a promise that contains the application name, icon and path of the default handler for the protocol (aka URI scheme) of a URL.

    app.setUserTasks(tasks) Windows

    • tasks Task[] – Array of Task objects

    Adds tasks to the Tasks category of the Jump List on Windows.

    tasks is an array of Task objects.

    Returns boolean – Whether the call succeeded.

    Note: If you’d like to customize the Jump List even more use app.setJumpList(categories) instead.

    app.getJumpListSettings() Windows

    Returns Object:

    • minItems Integer – The minimum number of items that will be shown in the Jump List (for a more detailed description of this value see the MSDN docs).
    • removedItems JumpListItem[] – Array of JumpListItem objects that correspond to items that the user has explicitly removed from custom categories in the Jump List. These items must not be re-added to the Jump List in the next call to app.setJumpList(), Windows will not display any custom category that contains any of the removed items.

    app.setJumpList(categories) Windows

    Returns string

    Sets or removes a custom Jump List for the application, and returns one of the following strings:

    • ok – Nothing went wrong.
    • error – One or more errors occurred, enable runtime logging to figure out the likely cause.
    • invalidSeparatorError – An attempt was made to add a separator to a custom category in the Jump List. Separators are only allowed in the standard Tasks category.
    • fileTypeRegistrationError – An attempt was made to add a file link to the Jump List for a file type the app isn’t registered to handle.
    • customCategoryAccessDeniedError – Custom categories can’t be added to the Jump List due to user privacy or group policy settings.

    If categories is null the previously set custom Jump List (if any) will be replaced by the standard Jump List for the app (managed by Windows).

    Note: If a JumpListCategory object has neither the type nor the name property set then its type is assumed to be tasks. If the name property is set but the type property is omitted then the type is assumed to be custom.

    Note: Users can remove items from custom categories, and Windows will not allow a removed item to be added back into a custom category until after the next successful call to app.setJumpList(categories). Any attempt to re-add a removed item to a custom category earlier than that will result in the entire custom category being omitted from the Jump List. The list of removed items can be obtained using app.getJumpListSettings().

    Note: The maximum length of a Jump List item’s description property is 260 characters. Beyond this limit, the item will not be added to the Jump List, nor will it be displayed.

    Here’s a very simple example of creating a custom Jump List:

    const { app } = require('electron')

    app.setJumpList([
    {
    type: 'custom',
    name: 'Recent Projects',
    items: [
    { type: 'file', path: 'C:\\Projects\\project1.proj' },
    { type: 'file', path: 'C:\\Projects\\project2.proj' }
    ]
    },
    { // has a name so type is assumed to be "custom"
    name: 'Tools',
    items: [
    {
    type: 'task',
    title: 'Tool A',
    program: process.execPath,
    args: '--run-tool-a',
    iconPath: process.execPath,
    iconIndex: 0,
    description: 'Runs Tool A'
    },
    {
    type: 'task',
    title: 'Tool B',
    program: process.execPath,
    args: '--run-tool-b',
    iconPath: process.execPath,
    iconIndex: 0,
    description: 'Runs Tool B'
    }
    ]
    },
    { type: 'frequent' },
    { // has no name and no type so type is assumed to be "tasks"
    items: [
    {
    type: 'task',
    title: 'New Project',
    program: process.execPath,
    args: '--new-project',
    description: 'Create a new project.'
    },
    { type: 'separator' },
    {
    type: 'task',
    title: 'Recover Project',
    program: process.execPath,
    args: '--recover-project',
    description: 'Recover Project'
    }
    ]
    }
    ])

    app.requestSingleInstanceLock([additionalData])

    • additionalData Record<any, any> (optional) – A JSON object containing additional data to send to the first instance.

    Returns boolean

    The return value of this method indicates whether or not this instance of your application successfully obtained the lock. If it failed to obtain the lock, you can assume that another instance of your application is already running with the lock and exit immediately.

    I.e. This method returns true if your process is the primary instance of your application and your app should continue loading. It returns false if your process should immediately quit as it has sent its parameters to another instance that has already acquired the lock.

    On macOS, the system enforces single instance automatically when users try to open a second instance of your app in Finder, and the open-file and open-url events will be emitted for that. However when users start your app in command line, the system’s single instance mechanism will be bypassed, and you have to use this method to ensure single instance.

    An example of activating the window of primary instance when a second instance starts:

    const { app, BrowserWindow } = require('electron')
    let myWindow = null

    const additionalData = { myKey: 'myValue' }
    const gotTheLock = app.requestSingleInstanceLock(additionalData)

    if (!gotTheLock) {
    app.quit()
    } else {
    app.on('second-instance', (event, commandLine, workingDirectory, additionalData) => {
    // Print out data received from the second instance.
    console.log(additionalData)

    // Someone tried to run a second instance, we should focus our window.
    if (myWindow) {
    if (myWindow.isMinimized()) myWindow.restore()
    myWindow.focus()
    }
    })

    app.whenReady().then(() => {
    myWindow = new BrowserWindow({})
    myWindow.loadURL('https://electronjs.org')
    })
    }

    app.hasSingleInstanceLock()

    Returns boolean

    This method returns whether or not this instance of your app is currently holding the single instance lock. You can request the lock with app.requestSingleInstanceLock() and release with app.releaseSingleInstanceLock()

    app.releaseSingleInstanceLock()

    Releases all locks that were created by requestSingleInstanceLock. This will allow multiple instances of the application to once again run side by side.

    app.setUserActivity(type, userInfo[, webpageURL]) macOS

    • type string – Uniquely identifies the activity. Maps to NSUserActivity.activityType.
    • userInfo any – App-specific state to store for use by another device.
    • webpageURL string (optional) – The webpage to load in a browser if no suitable app is installed on the resuming device. The scheme must be http or https.

    Creates an NSUserActivity and sets it as the current activity. The activity is eligible for Handoff to another device afterward.

    app.getCurrentActivityType() macOS

    Returns string – The type of the currently running activity.

    app.invalidateCurrentActivity() macOS

    Invalidates the current Handoff user activity.

    app.resignCurrentActivity() macOS

    Marks the current Handoff user activity as inactive without invalidating it.

    app.updateCurrentActivity(type, userInfo) macOS

    • type string – Uniquely identifies the activity. Maps to NSUserActivity.activityType.
    • userInfo any – App-specific state to store for use by another device.

    Updates the current activity if its type matches type, merging the entries from userInfo into its current userInfo dictionary.

    app.setAppUserModelId(id) Windows

    • id string

    Changes the Application User Model ID to id.

    app.setActivationPolicy(policy) macOS

    • policy string – Can be ‘regular’, ‘accessory’, or ‘prohibited’.

    Sets the activation policy for a given app.

    Activation policy types:

    • ‘regular’ – The application is an ordinary app that appears in the Dock and may have a user interface.
    • ‘accessory’ – The application doesn’t appear in the Dock and doesn’t have a menu bar, but it may be activated programmatically or by clicking on one of its windows.
    • ‘prohibited’ – The application doesn’t appear in the Dock and may not create windows or be activated.

    app.importCertificate(options, callback) Linux

    • options Object
      • certificate string – Path for the pkcs12 file.
      • password string – Passphrase for the certificate.
    • callback Function
      • result Integer – Result of import.

    Imports the certificate in pkcs12 format into the platform certificate store. callback is called with the result of import operation, a value of 0 indicates success while any other value indicates failure according to Chromium net_error_list.

    app.configureHostResolver(options)

    • options Object
      • enableBuiltInResolver boolean (optional) – Whether the built-in host resolver is used in preference to getaddrinfo. When enabled, the built-in resolver will attempt to use the system’s DNS settings to do DNS lookups itself. Enabled by default on macOS, disabled by default on Windows and Linux.
      • secureDnsMode string (optional) – Can be ‘off’, ‘automatic’ or ‘secure’. Configures the DNS-over-HTTP mode. When ‘off’, no DoH lookups will be performed. When ‘automatic’, DoH lookups will be performed first if DoH is available, and insecure DNS lookups will be performed as a fallback. When ‘secure’, only DoH lookups will be performed. Defaults to ‘automatic’.
      • secureDnsServers string[] (optional) – A list of DNS-over-HTTP server templates. See RFC8484 § 3 for details on the template format. Most servers support the POST method; the template for such servers is simply a URI. Note that for some DNS providers, the resolver will automatically upgrade to DoH unless DoH is explicitly disabled, even if there are no DoH servers provided in this list.
      • enableAdditionalDnsQueryTypes boolean (optional) – Controls whether additional DNS query types, e.g. HTTPS (DNS type 65) will be allowed besides the traditional A and AAAA queries when a request is being made via insecure DNS. Has no effect on Secure DNS which always allows additional types. Defaults to true.

    Configures host resolution (DNS and DNS-over-HTTPS). By default, the following resolvers will be used, in order:

    1. DNS-over-HTTPS, if the DNS provider supports it, then
    2. the built-in resolver (enabled on macOS only by default), then
    3. the system’s resolver (e.g. getaddrinfo).

    This can be configured to either restrict usage of non-encrypted DNS (secureDnsMode: "secure"), or disable DNS-over-HTTPS (secureDnsMode: "off"). It is also possible to enable or disable the built-in resolver.

    To disable insecure DNS, you can specify a secureDnsMode of "secure". If you do so, you should make sure to provide a list of DNS-over-HTTPS servers to use, in case the user’s DNS configuration does not include a provider that supports DoH.

    const { app } = require('electron')

    app.whenReady().then(() => {
    app.configureHostResolver({
    secureDnsMode: 'secure',
    secureDnsServers: [
    'https://cloudflare-dns.com/dns-query'
    ]
    })
    })

    This API must be called after the ready event is emitted.

    app.disableHardwareAcceleration()

    Disables hardware acceleration for current app.

    This method can only be called before app is ready.

    app.disableDomainBlockingFor3DAPIs()

    By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU processes crashes too frequently. This function disables that behavior.

    This method can only be called before app is ready.

    app.getAppMetrics()

    Returns ProcessMetric[]: Array of ProcessMetric objects that correspond to memory and CPU usage statistics of all the processes associated with the app.

    app.getGPUFeatureStatus()

    Returns GPUFeatureStatus – The Graphics Feature Status from chrome://gpu/.

    Note: This information is only usable after the gpu-info-update event is emitted.

    app.getGPUInfo(infoType)

    • infoType string – Can be basic or complete.

    Returns Promise<unknown>

    For infoType equal to complete: Promise is fulfilled with Object containing all the GPU Information as in chromium’s GPUInfo object. This includes the version and driver information that’s shown on chrome://gpu page.

    For infoType equal to basic: Promise is fulfilled with Object containing fewer attributes than when requested with complete. Here’s an example of basic response:

    {
    auxAttributes:
    {
    amdSwitchable: true,
    canSupportThreadedTextureMailbox: false,
    directComposition: false,
    directRendering: true,
    glResetNotificationStrategy: 0,
    inProcessGpu: true,
    initializationTime: 0,
    jpegDecodeAcceleratorSupported: false,
    optimus: false,
    passthroughCmdDecoder: false,
    sandboxed: false,
    softwareRendering: false,
    supportsOverlays: false,
    videoDecodeAcceleratorFlags: 0
    },
    gpuDevice:
    [{ active: true, deviceId: 26657, vendorId: 4098 },
    { active: false, deviceId: 3366, vendorId: 32902 }],
    machineModelName: 'MacBookPro',
    machineModelVersion: '11.5'
    }

    Using basic should be preferred if only basic information like vendorId or deviceId is needed.

    app.setBadgeCount([count]) Linux macOS

    • count Integer (optional) – If a value is provided, set the badge to the provided value otherwise, on macOS, display a plain white dot (e.g. unknown number of notifications). On Linux, if a value is not provided the badge will not display.

    Returns boolean – Whether the call succeeded.

    Sets the counter badge for current app. Setting the count to 0 will hide the badge.

    On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher.

    Note: Unity launcher requires a .desktop file to work. For more information, please read the Unity integration documentation.

    Note: On macOS, you need to ensure that your application has the permission to display notifications for this method to work.

    app.getBadgeCount() Linux macOS

    Returns Integer – The current value displayed in the counter badge.

    app.isUnityRunning() Linux

    Returns boolean – Whether the current desktop environment is Unity launcher.

    app.getLoginItemSettings([options]) macOS Windows

    • options Object (optional)
      • type string (optional) macOS – Can be one of mainAppServiceagentServicedaemonService, or loginItemService. Defaults to mainAppService. Only available on macOS 13 and up. See app.setLoginItemSettings for more information about each type.
      • serviceName string (optional) macOS – The name of the service. Required if type is non-default. Only available on macOS 13 and up.
      • path string (optional) Windows – The executable path to compare against. Defaults to process.execPath.
      • args string[] (optional) Windows – The command-line arguments to compare against. Defaults to an empty array.

    If you provided path and args options to app.setLoginItemSettings, then you need to pass the same arguments here for openAtLogin to be set correctly.

    Returns Object:

    • openAtLogin boolean – true if the app is set to open at login.
    • openAsHidden boolean macOS Deprecated – true if the app is set to open as hidden at login. This does not work on macOS 13 and up.
    • wasOpenedAtLogin boolean macOS – true if the app was opened at login automatically.
    • wasOpenedAsHidden boolean macOS Deprecated – true if the app was opened as a hidden login item. This indicates that the app should not open any windows at startup. This setting is not available on MAS builds or on macOS 13 and up.
    • restoreState boolean macOS Deprecated – true if the app was opened as a login item that should restore the state from the previous session. This indicates that the app should restore the windows that were open the last time the app was closed. This setting is not available on MAS builds or on macOS 13 and up.
    • status string macOS – can be one of not-registeredenabledrequires-approval, or not-found.
    • executableWillLaunchAtLogin boolean Windows – true if app is set to open at login and its run key is not deactivated. This differs from openAtLogin as it ignores the args option, this property will be true if the given executable would be launched at login with any arguments.
    • launchItems Object[] Windows
      • name string Windows – name value of a registry entry.
      • path string Windows – The executable to an app that corresponds to a registry entry.
      • args string[] Windows – the command-line arguments to pass to the executable.
      • scope string Windows – one of user or machine. Indicates whether the registry entry is under HKEY_CURRENT USER or HKEY_LOCAL_MACHINE.
      • enabled boolean Windows – true if the app registry key is startup approved and therefore shows as enabled in Task Manager and Windows settings.

    app.setLoginItemSettings(settings) macOS Windows

    • settings Object
      • openAtLogin boolean (optional) – true to open the app at login, false to remove the app as a login item. Defaults to false.
      • openAsHidden boolean (optional) macOS Deprecated – true to open the app as hidden. Defaults to false. The user can edit this setting from the System Preferences so app.getLoginItemSettings().wasOpenedAsHidden should be checked when the app is opened to know the current value. This setting is not available on MAS builds or on macOS 13 and up.
      • type string (optional) macOS – The type of service to add as a login item. Defaults to mainAppService. Only available on macOS 13 and up.
        • mainAppService – The primary application.
        • agentService – The property list name for a launch agent. The property list name must correspond to a property list in the app’s Contents/Library/LaunchAgents directory.
        • daemonService string (optional) macOS – The property list name for a launch agent. The property list name must correspond to a property list in the app’s Contents/Library/LaunchDaemons directory.
        • loginItemService string (optional) macOS – The property list name for a login item service. The property list name must correspond to a property list in the app’s Contents/Library/LoginItems directory.
      • serviceName string (optional) macOS – The name of the service. Required if type is non-default. Only available on macOS 13 and up.
      • path string (optional) Windows – The executable to launch at login. Defaults to process.execPath.
      • args string[] (optional) Windows – The command-line arguments to pass to the executable. Defaults to an empty array. Take care to wrap paths in quotes.
      • enabled boolean (optional) Windows – true will change the startup approved registry key and enable / disable the App in Task Manager and Windows Settings. Defaults to true.
      • name string (optional) Windows – value name to write into registry. Defaults to the app’s AppUserModelId().

    Set the app’s login item settings.

    To work with Electron’s autoUpdater on Windows, which uses Squirrel, you’ll want to set the launch path to Update.exe, and pass arguments that specify your application name. For example:

    const { app } = require('electron')
    const path = require('node:path')

    const appFolder = path.dirname(process.execPath)
    const updateExe = path.resolve(appFolder, '..', 'Update.exe')
    const exeName = path.basename(process.execPath)

    app.setLoginItemSettings({
    openAtLogin: true,
    path: updateExe,
    args: [
    '--processStart', "${exeName}",
    '--process-start-args', '"--hidden"'
    ]
    })

    For more information about setting different services as login items on macOS 13 and up, see SMAppService.

    app.isAccessibilitySupportEnabled() macOS Windows

    Returns boolean – true if Chrome’s accessibility support is enabled, false otherwise. This API will return true if the use of assistive technologies, such as screen readers, has been detected. See https://www.chromium.org/developers/design-documents/accessibility for more details.

    app.setAccessibilitySupportEnabled(enabled) macOS Windows

    Manually enables Chrome’s accessibility support, allowing to expose accessibility switch to users in application settings. See Chromium’s accessibility docs for more details. Disabled by default.

    This API must be called after the ready event is emitted.

    Note: Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.

    app.showAboutPanel()

    Show the app’s about panel options. These options can be overridden with app.setAboutPanelOptions(options). This function runs asynchronously.

    app.setAboutPanelOptions(options)

    • options Object
      • applicationName string (optional) – The app’s name.
      • applicationVersion string (optional) – The app’s version.
      • copyright string (optional) – Copyright information.
      • version string (optional) macOS – The app’s build version number.
      • credits string (optional) macOS Windows – Credit information.
      • authors string[] (optional) Linux – List of app authors.
      • website string (optional) Linux – The app’s website.
      • iconPath string (optional) Linux Windows – Path to the app’s icon in a JPEG or PNG file format. On Linux, will be shown as 64×64 pixels while retaining aspect ratio. On Windows, a 48×48 PNG will result in the best visual quality.

    Set the about panel options. This will override the values defined in the app’s .plist file on macOS. See the Apple docs for more details. On Linux, values must be set in order to be shown; there are no defaults.

    If you do not set credits but still wish to surface them in your app, AppKit will look for a file named “Credits.html”, “Credits.rtf”, and “Credits.rtfd”, in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple documentation for more information.

    app.isEmojiPanelSupported()

    Returns boolean – whether or not the current OS version allows for native emoji pickers.

    app.showEmojiPanel() macOS Windows

    Show the platform’s native emoji picker.

    app.startAccessingSecurityScopedResource(bookmarkData) MAS

    • bookmarkData string – The base64 encoded security scoped bookmark data returned by the dialog.showOpenDialog or dialog.showSaveDialog methods.

    Returns Function – This function must be called once you have finished accessing the security scoped file. If you do not remember to stop accessing the bookmark, kernel resources will be leaked and your app will lose its ability to reach outside the sandbox completely, until your app is restarted.

    const { app, dialog } = require('electron')
    const fs = require('node:fs')

    let filepath
    let bookmark

    dialog.showOpenDialog(null, { securityScopedBookmarks: true }).then(({ filePaths, bookmarks }) => {
    filepath = filePaths[0]
    bookmark = bookmarks[0]
    fs.readFileSync(filepath)
    })

    // ... restart app ...

    const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(bookmark)
    fs.readFileSync(filepath)
    stopAccessingSecurityScopedResource()

    Start accessing a security scoped resource. With this method Electron applications that are packaged for the Mac App Store may reach outside their sandbox to access files chosen by the user. See Apple’s documentation for a description of how this system works.

    app.enableSandbox()

    Enables full sandbox mode on the app. This means that all renderers will be launched sandboxed, regardless of the value of the sandbox flag in WebPreferences.

    This method can only be called before app is ready.

    app.isInApplicationsFolder() macOS

    Returns boolean – Whether the application is currently running from the systems Application folder. Use in combination with app.moveToApplicationsFolder()

    app.moveToApplicationsFolder([options]) macOS

    • options Object (optional)
      • conflictHandler Function (optional) – A handler for potential conflict in move failure.
        • conflictType string – The type of move conflict encountered by the handler; can be exists or existsAndRunning, where exists means that an app of the same name is present in the Applications directory and existsAndRunning means both that it exists and that it’s presently running.

    Returns boolean – Whether the move was successful. Please note that if the move is successful, your application will quit and relaunch.

    No confirmation dialog will be presented by default. If you wish to allow the user to confirm the operation, you may do so using the dialog API.

    NOTE: This method throws errors if anything other than the user causes the move to fail. For instance if the user cancels the authorization dialog, this method returns false. If we fail to perform the copy, then this method will throw an error. The message in the error should be informative and tell you exactly what went wrong.

    By default, if an app of the same name as the one being moved exists in the Applications directory and is not running, the existing app will be trashed and the active app moved into its place. If it is running, the preexisting running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning false will ensure no further action is taken, returning true will result in the default behavior and the method continuing.

    For example:

    const { app, dialog } = require('electron')

    app.moveToApplicationsFolder({
    conflictHandler: (conflictType) => {
    if (conflictType === 'exists') {
    return dialog.showMessageBoxSync({
    type: 'question',
    buttons: ['Halt Move', 'Continue Move'],
    defaultId: 0,
    message: 'An app of this name already exists'
    }) === 1
    }
    }
    })

    Would mean that if an app already exists in the user directory, if the user chooses to ‘Continue Move’ then the function would continue with its default behavior and the existing app will be trashed and the active app moved into its place.

    app.isSecureKeyboardEntryEnabled() macOS

    Returns boolean – whether Secure Keyboard Entry is enabled.

    By default this API will return false.

    app.setSecureKeyboardEntryEnabled(enabled) macOS

    • enabled boolean – Enable or disable Secure Keyboard Entry

    Set the Secure Keyboard Entry is enabled in your application.

    By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes.

    See Apple’s documentation for more details.

    Note: Enable Secure Keyboard Entry only when it is needed and disable it when it is no longer needed.

    app.setProxy(config)

    Returns Promise<void> – Resolves when the proxy setting process is complete.

    Sets the proxy settings for networks requests made without an associated Session. Currently this will affect requests made with Net in the utility process and internal requests made by the runtime (ex: geolocation queries).

    This method can only be called after app is ready.

    app.resolveProxy(url)

    • url URL

    Returns Promise<string> – Resolves with the proxy information for url that will be used when attempting to make requests using Net in the utility process.

    Properties

    app.accessibilitySupportEnabled macOS Windows

    boolean property that’s true if Chrome’s accessibility support is enabled, false otherwise. This property will be true if the use of assistive technologies, such as screen readers, has been detected. Setting this property to true manually enables Chrome’s accessibility support, allowing developers to expose accessibility switch to users in application settings.

    See Chromium’s accessibility docs for more details. Disabled by default.

    This API must be called after the ready event is emitted.

    Note: Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default.

    app.applicationMenu

    Menu | null property that returns Menu if one has been set and null otherwise. Users can pass a Menu to set this property.

    app.badgeCount Linux macOS

    An Integer property that returns the badge count for current app. Setting the count to 0 will hide the badge.

    On macOS, setting this with any nonzero integer shows on the dock icon. On Linux, this property only works for Unity launcher.

    Note: Unity launcher requires a .desktop file to work. For more information, please read the Unity integration documentation.

    Note: On macOS, you need to ensure that your application has the permission to display notifications for this property to take effect.

    app.commandLine Readonly

    CommandLine object that allows you to read and manipulate the command line arguments that Chromium uses.

    app.dock macOS Readonly

    Dock | undefined object that allows you to perform actions on your app icon in the user’s dock on macOS.

    app.isPackaged Readonly

    boolean property that returns true if the app is packaged, false otherwise. For many apps, this property can be used to distinguish development and production environments.

    app.name

    string property that indicates the current application’s name, which is the name in the application’s package.json file.

    Usually the name field of package.json is a short lowercase name, according to the npm modules spec. You should usually also specify a productName field, which is your application’s full capitalized name, and which will be preferred over name by Electron.

    app.userAgentFallback

    string which is the user agent string Electron will use as a global fallback.

    This is the user agent that will be used when no user agent is set at the webContents or session level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app’s initialization to ensure that your overridden value is used.

    app.runningUnderARM64Translation Readonly macOS Windows

    boolean which when true indicates that the app is currently running under an ARM64 translator (like the macOS Rosetta Translator Environment or Windows WOW).

    You can use this property to prompt users to download the arm64 version of your application when they are mistakenly running the x64 version under Rosetta or WOW

  •  Resources

    We have used the following resources to learn more about Electron. We have referred to these while creating this tutorial.

    The most important resource is the Electron documentation. The Documentation has extensive coverage of almost all features and quirks of the framework. They are alone enough to make your way through building an app.

    There are also some very good Electron examples presented in the electron-sample-apps respository.

    Video Resources

    Desktop apps with web languages

    Rapid cross platform desktop app development using JavaScript and Electron

    Blog Posts

    Building a desktop application with Electron

    Build a Music Player with React & Electron

    Creating Your First Desktop App With HTML, JS and Electron

    Create Cross-Platform Desktop Node Apps with Electron

  • Packaging Apps

    Packaging and distributing apps is an integral part of the development process of a desktop application. Since Electron is a cross-platform desktop application development framework, packaging and distribution of apps for all the platforms should also be a seamless experience.

    The electron community has created a project, electron-packager that takes care of the same for us. It allows us to package and distribute our Electron app with OS-specific bundles (.app, .exe etc) via JS or CLI.

    Supported Platforms

    Electron Packager runs on the following host platforms −

    • Windows (32/64 bit)
    • OS X
    • Linux (x86/x86_64)

    It generates executables/bundles for the following target platforms −

    • Windows (also known as win32, for both 32/64 bit)
    • OS X (also known as darwin) / Mac App Store (also known as mas)
    • Linux (for x86, x86_64, and armv7l architectures)

    Installation

    Install the electron packager using −

    # for use in npm scripts
    $ npm install electron-packager --save-dev
    
    # for use from cli
    $ npm install electron-packager -g
    

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Packaging Apps

    In this section, we will see how to run the packager from the command line. The basic form of the command is −

    electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch> [optional flags...]
    

    This will −

    • Find or download the correct release of Electron.
    • Use that version of Electron to create a app in <output-folder>/<appname>-<platform>-<arch>.

    –platform and –arch can be omitted, in two cases. If you specify –all instead, bundles for all valid combinations of target platforms/architectures will be created. Otherwise, a single bundle for the host platform/architecture will be created.

  • Debugging

    We have two processes that run our application – the main process and the renderer process.

    Since the renderer process is the one being executed in our browser window, we can use the Chrome Devtools to debug it. To open DevTools, use the shortcut “Ctrl+Shift+I” or the <F12> key. You can check out how to use devtools here.

    When you open the DevTools, your app will look like as shown in the following screenshot −

    DevTools

    Debugging the Main Process

    The DevTools in an Electron browser window can only debug JavaScript that is executed in that window (i.e., the web pages). To debug JavaScript that is executed in the main process you will need to use an external debugger and launch Electron with the –debug or the –debug-brk switch.

    Electron will listen for the V8 debugger protocol messages on the specified port; an external debugger will need to connect on this port. The default port is 5858.

    Run your app using the following −

    $ electron --debug = 5858 ./main.js
    

    Now you will need a debugger that supports the V8 debugger protocol. You can use VSCode or node-inspector for this purpose. For example, let us follow these steps and set up VSCode for this purpose. Follow these steps to set it up −

    Download and install VSCode. Open your Electron project in VSCode.

    Add a file .vscode/launch.json with the following configuration −

    {
       "version": "1.0.0",
       "configurations": [
    
      {
         "name": "Debug Main Process",
         "type": "node",
         "request": "launch",
         "cwd": "${workspaceRoot}",
         "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
         "program": "${workspaceRoot}/main.js"
      }
    ] }

    Note − For Windows, use “${workspaceRoot}/node_modules/.bin/electron.cmd” for runtimeExecutable.

    Set some breakpoints in main.js, and start debugging in the Debug View. When you hit the breakpoints, the screen will look something like this −

    Debugger

    The VSCode debugger is very powerful and will help you rectify errors quickly. You also have other options like node-inspector for debugging electron apps.

  • Environment Variables

    Environment Variables control application configuration and behavior without changing code. Certain Electron behaviors are controlled by environment variables because they are initialized earlier than the command line flags and the app’s code.

    There are two kinds of environment variables encoded in electron – Production variables and Development variables.

    Production Variables

    The following environment variables are intended for use at runtime in packaged Electron applications.

    Sr.NoVariable & Description
    1GOOGLE_API_KEYElectron includes a hardcoded API key for making requests to Google’s geocoding webservice. Because this API key is included in every version of Electron, it often exceeds its usage quota.To work around this, you can supply your own Google API key in the environment. Place the following code in your main process file, before opening any browser windows that will make geocoding requests −process.env.GOOGLE_API_KEY = ‘YOUR_KEY_HERE’
    2ELECTRON_RUN_AS_NODEStarts the process as a normal Node.js process.
    3ELECTRON_FORCE_WINDOW_MENU_BAR (Linux Only)Do not use the global menu bar on Linux.

    Development Variables

    The following environment variables are intended primarily for development and debugging purposes.

    Sr.NoVariable & Description
    1ELECTRON_ENABLE_LOGGINGPrints Chrome’s internal logging to the console.
    2ELECTRON_ENABLE_STACK_DUMPINGPrints the stack trace to the console when Electron crashes.
    3ELECTRON_DEFAULT_ERROR_MODEShows the Windows’s crash dialog when Electron crashes.

    To set any of these environment variables as true, set it in your console. For example, if you want to enable logging, then use the following commands −

    For Windows

    > set ELECTRON_ENABLE_LOGGING=true
    

    For Linux

    $ export ELECTRON_ENABLE_LOGGING=true
    

    Note that you will need to set these environment variables every time you restart your computer. If you want to avoid doing so, add these lines to your .bashrc files.

  • Defining Shortcuts

    We typically have memorized certain shortcuts for all the apps that we use on our PC daily. To make your applications feel intuitive and easily accessible to the user, you must allow the user to use shortcuts.

    We will use the globalShortcut module to define shortcuts in our app. Note that Accelerators are Strings that can contain multiple modifiers and key codes, combined by the + character. These accelerators are used to define keyboard shortcuts throughout our application.

    Let us consider an example and create a shortcut. For this, we will follow the dialog boxes example where we used the open dialog box for opening files. We will register a CommandOrControl+O shortcut to bring up the dialog box.

    Our main.js code will remain the same as before. So create a new main.js file and enter the following code in it −

    const {app, BrowserWindow} = require('electron')
    const url = require('url')
    const path = require('path')
    const {ipcMain} = require('electron')
    
    let win
    
    function createWindow() {
       win = new BrowserWindow({width: 800, height: 600})
       win.loadURL(url.format ({
    
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes: true
    })) } ipcMain.on('openFile', (event, path) => { const {dialog} = require('electron') const fs = require('fs') dialog.showOpenDialog(function (fileNames) {
         
      // fileNames is an array that contains all the selected
      if(fileNames === undefined)
         console.log("No file selected")
      else
         readFile(fileNames&#91;0])
    }) function readFile(filepath){
      fs.readFile(filepath, 'utf-8', (err, data) =&gt; {
         if(err){
            alert("An error ocurred reading the file :" + err.message)
            return
         }
         
         // handle the file content
         event.sender.send('fileData', data)
      })
    } }) app.on('ready', createWindow)

    This code will pop open the open dialog box whenever our main process receives a ‘openFile’ message from a renderer process. Earlier this dialog box popped up whenever the app was run. Let us now limit it to open only when we press CommandOrControl+O.

    Now create a new index.html file with the following content −

    <!DOCTYPE html>
    <html>
       <head>
    
      &lt;meta charset = "UTF-8"&gt;
      &lt;title&gt;File read using system dialogs&lt;/title&gt;
    </head> <body>
      &lt;p&gt;Press CTRL/CMD + O to open a file. &lt;/p&gt;
      &lt;script type = "text/javascript"&gt;
         const {ipcRenderer, remote} = require('electron')
         const {globalShortcut} = remote
         globalShortcut.register('CommandOrControl+O', () =&gt; {
            ipcRenderer.send('openFile', () =&gt; {
               console.log("Event sent.");
            })
            
            ipcRenderer.on('fileData', (event, data) =&gt; {
               document.write(data)
            })
         })
      &lt;/script&gt;
    </body> </html>

    We registered a new shortcut and passed a callback that will be executed whenever we press this shortcut. We can deregister shortcuts as and when we do not require them.

    Now once the app is opened, we will get the message to open the file using the shortcut we just defined.

    Open dialog

    These shortcuts can be made customizable by allowing the user to choose his own shortcuts for defined actions.

  • Audio and Video Capturing

    Audio and video capturing are important characteristics if you are building apps for screen sharing, voice memos, etc. They are also useful if you require an application to capture the profile picture.

    We will be using the getUserMedia HTML5 API for capturing audio and video streams with Electron. Let us first set up our main process in the main.js file as follows −

    const {app, BrowserWindow} = require('electron')
    const url = require('url')
    const path = require('path')
    
    let win
    
    // Set the path where recordings will be saved
    app.setPath("userData", __dirname + "/saved_recordings")
    
    function createWindow() {
       win = new BrowserWindow({width: 800, height: 600})
       win.loadURL(url.format({
    
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes: true
    })) } app.on('ready', createWindow)

    Now that we have set up our main process, let us create the HTML file that will be capturing this content. Create a file called index.html with the following content −

    <!DOCTYPE html>
    <html>
       <head>
    
      &lt;meta charset = "UTF-8"&gt;
      &lt;title&gt;Audio and Video&lt;/title&gt;
    </head> <body>
      &lt;video autoplay&gt;&lt;/video&gt;
      &lt;script type = "text/javascript"&gt;
         function errorCallback(e) {
            console.log('Error', e)
         }
         navigator.getUserMedia({video: true, audio: true}, (localMediaStream) =&gt; {
            var video = document.querySelector('video')
            video.src = window.URL.createObjectURL(localMediaStream)
            video.onloadedmetadata = (e) =&gt; {
               // Ready to go. Do some stuff.
            };
         }, errorCallback)
      &lt;/script&gt;
    </body> </html>

    The above program will generate the following output −

    Audio and Video Stream

    You now have the stream from both your webcam and your microphone. You can send this stream over the network or save this in a format you like.

    Have a look at the MDN Documentation for capturing images to get the images from your webcam and store them. This was done using the HTML5 getUserMedia API. You can also capture the user desktop using the desktopCapturer module that comes with Electron. Let us now see an example of how to get the screen stream.

    Use the same main.js file as above and edit the index.html file to have the following content −

    desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
       if (error) throw error
       for (let i = 0; i < sources.length; ++i) {
    
      if (sources&#91;i].name === 'Your Window Name here!') {
         navigator.webkitGetUserMedia({
            audio: false,
            video: {
               mandatory: {
                  chromeMediaSource: 'desktop',
                  chromeMediaSourceId: sources&#91;i].id,
                  minWidth: 1280,
                  maxWidth: 1280,
                  minHeight: 720,
                  maxHeight: 720
               }
            }
         }, handleStream, handleError)
         return
      }
    } }) function handleStream (stream) { document.querySelector('video').src = URL.createObjectURL(stream) } function handleError (e) { console.log(e) }

    We have used the desktopCapturer module to get the information about each open window. Now you can capture the events of a specific application or of the entire screen depending on the name you pass to the above if statement. This will stream only that which is happening on that screen to your app.

    Desktop capturer

    You can refer to this StackOverflow question to understand the usage in detail.