new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Electron · API · all subjects

app/overview

128 notes in this subject, read out of this brain and free to use. This is page 2 of 3.

Creating a basic tray menu example

const { app, Menu, Tray } = require('electron') let tray = null app.whenReady().then(() => { tray = new Tray('/path/to/my/icon') const contextMenu = Menu.buildFromTemplate([ { label: 'Item1', type: 'radio' }, { label: 'Item2', type: 'radio' }, { label: 'Item3', type: 'radio', checked: true }, { label: 'Item4', type: 'radio' } ]) tray.setToolTip('This is my application.') tray.setContextMenu(contextMenu) }) This example shows how to create a basic tray icon with a context menu.

Linux context menu update example

const { app, Menu, Tray } = require('electron') let appIcon = null app.whenReady().then(() => { appIcon = new Tray('/path/to/my/icon') const contextMenu = Menu.buildFromTemplate([ { label: 'Item1', type: 'radio' }, { label: 'Item2', type: 'radio' } ]) // Make a change to the context menu contextMenu.items[1].checked = false // Call this again for Linux because we modified the context menu appIcon.setContextMenu(contextMenu) }) This example shows that on Linux, tray.setContextMenu() must be called again after modifying individual MenuItems for changes to take effect.

utilityProcess module overview

utilityProcess creates a child process with Node.js and Message ports enabled. It provides equivalent functionality to Node.js child_process.fork API but uses Chromium's Services API to launch the child process. Available in the main process only.

WebContentsView class overview

WebContentsView is a View that displays a WebContents. It runs in the main process and extends the View class. It is an EventEmitter. WebContentsView cannot be subclassed in user code.

WebContentsView usage example

Example showing how to create a BaseWindow with two WebContentsViews side by side: const { BaseWindow, WebContentsView } = require('electron') const win = new BaseWindow({ width: 800, height: 400 }) const view1 = new WebContentsView() win.contentView.addChildView(view1) view1.webContents.loadURL('https://electronjs.org') view1.setBounds({ x: 0, y: 0, width: 400, height: 400 }) const view2 = new WebContentsView() win.contentView.addChildView(view2) view2.webContents.loadURL('https://github.com/electron/electron') view2.setBounds({ x: 400, y: 0, width: 400, height: 400 })

View module overview

The View module is used to create and layout native views. It is available only in the main process and cannot be used until the 'ready' event of the app module is emitted.

webFrameMain module overview

The webFrameMain module is used to control web pages and iframes. It is available in the main process and can be used to lookup frames across existing WebContents instances. Navigation events are a common use case.

WebFrameMain class availability

The WebFrameMain class is not exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.

webFrame module overview

webFrame is an instance of the WebFrame class that represents the current frame in the renderer process. It is used to customize the rendering of the current web page. If context isolation is enabled, the API call must be placed in the preload script and exposed using the contextBridge API.

webFrame module process

webFrame is available only in the Renderer process.

webUtils module overview

The webUtils module is a utility layer to interact with Web API objects such as Files and Blobs. It is available in the renderer process only.

webview httpreferrer attribute

The httpreferrer attribute is a string that sets the referrer URL for the guest page.

webview tag deprecated - not recommended

Electron's webview tag is based on Chromium's webview, which is undergoing dramatic architectural changes. This impacts the stability of webviews, including rendering, navigation, and event routing. Electron currently recommends not using the webview tag and considering alternatives like iframe, WebContentsView, or an architecture that avoids embedded content altogether.

webview tag requires webviewTag webPreferences option

By default the webview tag is disabled in Electron >= 5. You must enable the tag by setting the webviewTag webPreferences option when constructing your BrowserWindow.

webview tag runs in separate process with different permissions

The webview tag embeds guest content in an isolated frame and process separate from the host app. Unlike an iframe, the webview runs in a separate process than the app, does not have the same permissions as the web page, and all interactions between the app and embedded content are asynchronous. This keeps the app safe from the embedded content.

webview most methods require synchronous main process call

Most methods called on the webview from the host page require a synchronous call to the main process.

webview implemented with Out-of-Process iframes (OOPIFs)

Under the hood webview is implemented with Out-of-Process iframes (OOPIFs). The webview tag is a custom element using shadow DOM to wrap an iframe element inside it. The behavior of webview is very similar to a cross-domain iframe: when clicking into a webview, the page focus will move from the embedder frame to webview; you cannot add keyboard, mouse, and scroll event listeners to webview; and all reactions between the embedder frame and webview are asynchronous.

webview src attribute

The src attribute is a string representing the visible URL. Writing to this attribute initiates top-level navigation. Assigning src its own value will reload the current page. The src attribute can also accept data URLs, such as data:text/plain,Hello, world!.

webview nodeintegration attribute

The nodeintegration attribute is a boolean. When this attribute is present, the guest page in webview will have node integration and can use node APIs like require and process to access low level system resources. Node integration is disabled by default in the guest page.

webview nodeintegrationinsubframes attribute

The nodeintegrationinsubframes attribute is a boolean for the experimental option for enabling NodeJS support in sub-frames such as iframes inside the webview. All preloads will load for every iframe, and you can use process.isMainFrame to determine if you are in the main frame or not. This option is disabled by default in the guest page.

webview plugins attribute

The plugins attribute is a boolean. When this attribute is present, the guest page in webview will be able to use browser plugins. Plugins are disabled by default.

webview preload attribute

The preload attribute is a string that specifies a script that will be loaded before other scripts run in the guest page. The protocol of the script's URL must be file: (even when using asar: archives) because it will be loaded by Node's require under the hood, which treats asar: archives as virtual directories. When the guest page doesn't have node integration, this script will still have access to all Node APIs, but global objects injected by Node will be deleted after this script has finished executing.

webview useragent attribute

The useragent attribute is a string that sets the user agent for the guest page before the page is navigated to. Once the page is loaded, use the setUserAgent method to change the user agent.

webview partition attribute

The partition attribute is a string that sets the session used by the page. 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. If the partition is unset, the default session of the app will be used. This value can only be modified before the first navigation, since the session of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception.

webview allowpopups attribute

The allowpopups attribute is a boolean. When this attribute is present, the guest page will be allowed to open new windows. Popups are disabled by default.

webview webpreferences attribute

The webpreferences attribute is a string which is a comma separated list of strings which specifies the web preferences to be set on the webview. The full list of supported preference strings can be found in the BrowserWindow documentation. The string follows the same format as the features string in window.open. A name by itself is given a true boolean value. A preference can be set to another value by including an =, followed by the value. Special values yes and 1 are interpreted as true, while no and 0 are interpreted as false.

webview disableblinkfeatures attribute

The disableblinkfeatures attribute is a string which is a list of strings which specifies the blink features to be disabled separated by comma. The full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.

webview must be loaded before using methods

The webview element must be loaded before using the methods. Example: listen for the dom-ready event before calling methods like openDevTools().

webview example basic HTML with event listeners

Example showing how to listen for webview events. The code creates a webview element, listens for did-start-loading and did-stop-loading events, and displays a loading indicator: const webview = document.querySelector('webview'); const indicator = document.querySelector('.indicator'); const loadstart = () => { indicator.innerText = 'loading...' }; const loadstop = () => { indicator.innerText = '' }; webview.addEventListener('did-start-loading', loadstart); webview.addEventListener('did-stop-loading', loadstop);

BaseWindow vs BrowserWindow design purpose

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.

BaseWindow cannot be subclassed

Electron's built-in classes, including BaseWindow, cannot be subclassed in user code.

WebContentsView resource management in BaseWindow

When you add a WebContentsView to a BaseWindow and the BaseWindow is closed, the webContents of the WebContentsView are not destroyed automatically. It is your responsibility to close the webContents when you no longer need them, otherwise you will encounter memory leaks.

BaseWindow class is main-process only

The BaseWindow class creates and controls windows in the main process. This module cannot be used until the 'ready' event of the app module is emitted.

Renderer process creation with web embeds

A renderer process is also created for web embeds such as the BrowserView module. The webContents object is also accessible for embedded web content.

Electron multi-process architecture overview

Electron inherits its multi-process architecture from Chromium, making it architecturally similar to a modern web browser. Each Electron app has two types of processes: a main process and renderer processes, analogous to Chrome's browser and renderer processes.

Single main process per app

Each Electron app has a single main process, which acts as the application's entry point. The main process runs in a Node.js environment, meaning it has the ability to require modules and use all of Node.js APIs.

Why multi-process architecture

Single-process browsers meant less overhead for each tab, but one website crashing or hanging would affect the entire browser. Chrome solved this by having each tab render in its own process, limiting the harm that buggy or malicious code on a web page could cause to the app as a whole. A single browser process then controls these processes and the application lifecycle.

Renderer process web standards

Each Electron app spawns a separate renderer process for each open BrowserWindow (and each web embed). A renderer is responsible for rendering web content. Code run in renderer processes should behave according to web standards. All user interfaces and app functionality within a single browser window should be written with the same tools and paradigms that you use on the web.

Renderer process entry point

An HTML file is your entry point for the renderer process. UI styling is added through Cascading Style Sheets (CSS). Executable JavaScript code can be added through <script> elements.

Utility process for child processes

Each Electron app can spawn multiple child processes from the main process using the UtilityProcess API. The utility process runs in a Node.js environment, meaning it has the ability to require modules and use all of Node.js APIs. The utility process can be used to host untrusted services, CPU intensive tasks or crash prone components which would have previously been hosted in the main process or process spawned with Node.js child_process.fork API.

UtilityProcess preferred over child_process.fork

An Electron app can always prefer the UtilityProcess API over Node.js child_process.fork API when there is need to fork a child process from the main process.

Process-specific module type aliases (TypeScript)

Electron's npm package exports subpaths that contain a subset of Electron's TypeScript type definitions: - electron/main includes types for all main process modules. - electron/renderer includes types for all renderer process modules. - electron/common includes types for modules that can run in main and renderer processes. These aliases have no impact on runtime, but can be used for typechecking and autocomplete.

Process-specific module aliases usage example

const { shell } = require('electron/common') const { app } = require('electron/main')

Filename too long error with Node.js on Windows

Node.js has extremely long pathnames and git on Windows doesn't handle long pathnames correctly by default. Enable git long path support with: git config --system core.longpaths true

Build scripts hang on Windows command prompt

Build scripts may hang on Windows command prompt when QuickEdit is enabled, because clicking in the window pauses the build. Disable QuickEdit in command prompt properties to prevent accidental pauses.

Fatal internal compiler error C1001

If encountering 'Fatal internal compiler error: C1001' when building Electron on Windows, ensure you have the latest Visual Studio update installed.

Windows Security exclusion needed for Chromium source

Windows Security must be configured to exclude the Electron source tree from monitoring because it will delete a file in the Chromium source code, causing gclient sync issues.

Building Electron on Windows uses command-line scripts

Building Electron on Windows is done entirely with command-line scripts and cannot be done with Visual Studio IDE. Developers can use any editor for development.

32-bit Electron build on Windows

To build Electron for 32-bit target on Windows, pass target_cpu = "x86" as a GN argument. The 32-bit target can be built alongside the 64-bit target by using a different output directory for GN, such as out/Release-x86.

Generate Visual Studio project for Electron build

To generate a Visual Studio project from Electron build files, pass the --ide=vs2017 parameter to gn gen. Example: gn gen out/Testing --ide=vs2017

LNK1181 linker error on 32-bit build

If encountering 'LNK1181: cannot open input file kernel32.lib' error when building Electron on Windows, try reinstalling 32-bit Node.js.

Cannot open npm directory error on Windows

The error 'Error: ENOENT, stat C:\Users\USERNAME\AppData\Roaming\npm' can be fixed by creating the directory with: mkdir ~\AppData\Roaming\npm

node-gyp not recognized in Git Bash

If node-gyp is not recognized when building Electron on Windows, you may be using Git Bash. Use PowerShell or VS2015 Command Prompt instead.

DefaultDelegateCheckMode undeclared identifier error

If encountering 'error: use of undeclared identifier DefaultDelegateCheckMode' during build, this can happen when Debugging Tools for Windows has been installed with Windows Driver Kit. Uninstall Windows Driver Kit and install Debugging Tools separately.

Windows SDK Debugging Tools for full distribution

Debugging Tools for Windows of Windows SDK 10.0.15063.468 is required if planning to create a full distribution, since symstore.exe is used for creating a symbol store from .pdb files.

Git requirement for Windows Electron build

Git is required to build Electron on Windows.

Node.js version for Windows Electron build

Node.js version 22.12.0 or higher is required to build Electron on Windows.

Visual Studio requirement for Windows Electron build

Visual Studio 2019 (version 16.0.0 or higher) is required to build Electron, but Visual Studio 2022 (version 17.0.0 or higher) is preferred. Visual Studio is required for the build toolchains it provides, even though the actual building is done with command-line scripts, not the Visual Studio IDE.

Windows minimum version for Electron build

Windows 10 or Server 2012 R2 or higher is required to build Electron on Windows.

Visual Studio installation environment variables

If Visual Studio is installed in a non-default directory, set the vs2022_install environment variable to DRIVE:\path\to\Microsoft Visual Studio\2022\Community (replacing 2022 and Community with your installed versions and DRIVE: with the drive letter) and set WINDOWSSDKDIR to DRIVE:\path\to\Windows Kits\10 (replacing DRIVE: with the drive letter).

Give your agent this brain