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 · all subjects

native apis & system integration

52 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Platform-specific pattern for loading native addons on Linux

To load a native addon only on Linux platforms, use `process.platform !== 'linux'` to check the platform and throw an error on non-Linux systems. Use `require('bindings')('addon_name')` to load the compiled addon. Export an empty object on non-Linux platforms to prevent errors in cross-platform code.

Native addon methods for calling C++ code from JavaScript

A native addon wrapper provides methods that call corresponding C++ functions. For example, `helloWorld(input)` calls the C++ `helloWorld()` function and returns its result, and `helloGui()` launches a native GUI window.

GTK3 native addon example: Todo application with GUI

A complete example of a native Linux addon using GTK3 provides: a text entry field for todo items, a calendar widget for selecting dates, an "Add" button to create new todos, a scrollable list showing all todos, and right-click context menus for editing and deleting todos. The addon emits events (`todoAdded`, `todoUpdated`, `todoDeleted`) that are forwarded to JavaScript, allowing the Electron application to respond to native GUI interactions in real-time.

Building native addon with npm run build

After all files are in place for a native addon, build it using `npm run build` to compile the C++ code into a loadable native module.

GTK3 compatibility with Electron's Chromium runtime

GTK3 is compatible with Electron's Chromium runtime and can be used to create native GUIs that integrate with Electron applications on Linux.

Native addon wrapper extends EventEmitter for event forwarding

A native addon wrapper should extend EventEmitter to forward events from C++ to JavaScript. Set up event forwarding by attaching listeners to the native addon (e.g., `this.addon.on('eventName', (payload) => this.emit('eventName', payload))`) and then emit those events from the wrapper class to JavaScript code.

Native addon JSON parsing and type conversion in JavaScript wrapper

When receiving JSON data from a native addon, parse it in the JavaScript wrapper and convert string dates to JavaScript Date objects. For example, parse JSON payloads and use `new Date(parsed.date)` to convert date strings to proper JavaScript Date objects before returning to calling code.

Display native dialog from renderer - use contextBridge

To display a native dialog from a renderer process, you cannot directly call dialog methods since the dialog module only runs in the main process. Instead, use contextBridge to expose a preload function that invokes dialog methods in the main process via IPC.

Dock API class and main process

The Dock class controls the application in the macOS dock. It is only available in the main process and is not exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.

What is the Dock API in Electron?

The Dock API is a class available in the main process on macOS that allows you to control the application's dock icon and behavior. It provides methods to bounce the icon, set and get badges, show and hide the icon, manage dock menus, and set the dock icon image. The Dock class is only available as a return value from other Electron API methods and is not directly exported from the 'electron' module.

chrome.management supported methods and events

Supported methods: chrome.management.getAll, chrome.management.get, chrome.management.getSelf, chrome.management.getPermissionWarningsById, chrome.management.getPermissionWarningsByManifest. Supported events: chrome.management.onEnabled, chrome.management.onDisabled.

chrome.runtime supported properties, methods and events

Supported properties: chrome.runtime.lastError, chrome.runtime.id. Supported methods: chrome.runtime.getBackgroundPage, chrome.runtime.getManifest, chrome.runtime.getPlatformInfo, chrome.runtime.getURL, chrome.runtime.connect, chrome.runtime.sendMessage, chrome.runtime.reload. Supported events: chrome.runtime.onStartup, chrome.runtime.onInstalled, chrome.runtime.onSuspend, chrome.runtime.onSuspendCanceled, chrome.runtime.onConnect, chrome.runtime.onMessage.

chrome.scripting support

All features of the chrome.scripting API are supported in Electron.

Tab ID -1 not supported in Electron extensions

In Chrome, passing -1 as a tab ID signifies the currently active tab. Since Electron has no such concept, passing -1 as a tab ID is not supported and will raise an error.

chrome.webRequest support

All features of the chrome.webRequest API are supported in Electron. Electron's webRequest module takes precedence over chrome.webRequest if there are conflicting handlers.

chrome.storage supported methods

The method chrome.storage.local is supported. chrome.storage.sync and chrome.storage.managed are not supported.

chrome.tabs supported methods

Supported methods: chrome.tabs.sendMessage, chrome.tabs.reload, chrome.tabs.executeScript. chrome.tabs.query has partial support with supported properties: url, title, audible, active, muted. chrome.tabs.update has partial support with supported properties: url, muted.

Loading unpacked extensions in Electron

Electron only supports loading unpacked extensions; .crx files do not work. Extensions are installed per-session. To load an extension, call ses.extensions.loadExtension(path, options). The example code shows: const { session } = require('electron'); session.defaultSession.loadExtension('path/to/unpacked/extension').then(({ id }) => { ... })

Extensions not remembered across application exits

Loaded extensions will not be automatically remembered across exits. If you do not call loadExtension when the app runs, the extension will not be loaded.

Loading extensions only in persistent sessions

Loading extensions is only supported in persistent sessions. Attempting to load an extension into an in-memory session will throw an error.

Supported manifest keys for extensions

Supported manifest keys are: name, version, author, permissions, content_scripts, default_locale, devtools_page, short_name, host_permissions (Manifest V3), manifest_version, background (Manifest V2), and minimum_chrome_version.

chrome.devtools.inspectedWindow support

All features of the chrome.devtools.inspectedWindow API are supported in Electron.

chrome.devtools.panels support

All features of the chrome.devtools.panels API are supported in Electron.

chrome.extension supported properties and methods

Supported properties: chrome.extension.lastError. Supported methods: chrome.extension.getURL, chrome.extension.getBackgroundPage.

EXIF metadata not supported in nativeImage

EXIF metadata is currently not supported and will not be taken into account during image encoding and decoding.

nativeImage creates tray, dock, and application icons

The nativeImage module provides a unified interface for manipulating system images to create tray, dock, and application icons. Electron APIs that take image files accept either file paths or NativeImage instances. An empty and transparent image will be used when null is passed.

Supported image formats for nativeImage

PNG and JPEG image formats are supported across all platforms. PNG is recommended because of its support for transparency and lossless compression. On Windows, you can also load ICO icons from file paths.

Windows icon sizes for visual quality

For best visual quality on Windows, include at least the following sizes: Small icon: 16x16 (100% DPI), 20x20 (125% DPI), 24x24 (150% DPI), 32x32 (200% DPI). Large icon: 32x32 (100% DPI), 40x40 (125% DPI), 48x48 (150% DPI), 64x64 (200% DPI), 256x256.

High resolution image DPI suffixes

Append DPI suffixes after the base filename to mark images as high resolution. Supported suffixes are: @1x, @1.25x, @1.33x, @1.4x, @1.5x, @1.8x, @2x, @2.5x, @3x, @4x, @5x. For example, icon@2x.png will be treated as a 2x scale high resolution image.

macOS template images

On macOS, template images consist of black and an alpha channel and are not intended to be used as standalone images. They are usually mixed with other content to create the desired final appearance. To mark an image as a template image, its base filename should end with the word Template (e.g. xxxTemplate.png). Template images can be specified at different DPI densities (e.g. xxxTemplate@2x.png). The most common case is using template images for a menu bar (Tray) icon so it can adapt to both light and dark menu bars.

How to use the nativeImage module

The nativeImage module can be used to create tray, dock, and application icons. You can pass either file paths or NativeImage instances to Electron APIs that take image files. Use nativeImage.createFromPath() to create a NativeImage instance from a file path, or use other create methods like createFromBuffer(), createFromDataURL(), etc.

nativeImage example creating icons from paths

const { BrowserWindow, nativeImage, Tray } = require('electron') const trayIcon = nativeImage.createFromPath('/Users/somebody/images/icon.png') const appIcon = nativeImage.createFromPath('/Users/somebody/images/window.png') const tray = new Tray(trayIcon) const win = new BrowserWindow({ icon: appIcon })

nativeImage example creating menu symbol

const { nativeImage, MenuItem } = require('electron') const item = new MenuItem({ icon: nativeImage.createMenuSymbol('folder.badge.plus'), label: 'Create Folder' })

Main process native APIs

To extend Electron's features beyond being a Chromium wrapper for web contents, the main process adds custom APIs to interact with the user's operating system. Electron exposes various modules that control native desktop functionality, such as menus, dialogs, and tray icons.

LanguageModelCreateCoreOptions object structure

LanguageModelCreateCoreOptions is an object with two optional properties: expectedInputs which is an array of LanguageModelExpected objects, and expectedOutputs which is an array of LanguageModelExpected objects.

Example: Use bypassCustomProtocolHandlers with ses.fetch()

protocol.handle('https', (req) => { if (req.url === 'https://my-app.com') { return new Response('<body>my app</body>') } else { return net.fetch(req, { bypassCustomProtocolHandlers: true }) } })

Session instance events: preconnect

The 'preconnect' event is emitted when a render process requests preconnection to a URL, generally due to a resource hint. Event returns: event (Event), preconnectUrl (string - the URL being requested for preconnection), allowCredentials (boolean - true if the renderer is requesting that the connection include credentials).

ses.setProxy() method

ses.setProxy(config) sets proxy settings where config is a ProxyConfig object. Returns Promise<void> - resolves when the proxy setting process is complete. May need to call ses.closeAllConnections() to close currently in-flight connections to prevent pooled sockets using previous proxy from being reused by future requests.

ses.resolveHost() method signature and parameters

ses.resolveHost(host, [options]) resolves a hostname and returns Promise<ResolvedHost>. Parameters: host (string, required) - hostname to resolve; options (Object, optional) with properties: queryType (string) - DNS query type 'A', 'AAAA', or unspecified to let resolver pick; source (string) - 'any' (default), 'system', 'dns', 'mdns', or 'localOnly'; cacheUsage (string) - 'allowed' (default), 'staleAllowed', or 'disallowed'; secureDnsPolicy (string) - 'allow' (default) or 'disable'.

ses.resolveProxy() method

ses.resolveProxy(url) returns Promise<string> - resolves with the proxy information for the given URL.

ses.forceReloadProxyConfig() method

ses.forceReloadProxyConfig() returns Promise<void> - resolves when all internal states of proxy service are reset and the latest proxy configuration is reapplied if already available. The pac script will be fetched from pacScript again if proxy mode is pac_script.

ses.enableNetworkEmulation() method signature and options

ses.enableNetworkEmulation(options) emulates network with the given configuration for the session. Options parameter is an Object with: offline (boolean, optional) - whether to emulate network outage, defaults to false; latency (Double, optional) - RTT in ms, defaults to 0 which disables latency throttling; downloadThroughput (Double, optional) - download rate in Bps, defaults to 0 which disables download throttling; uploadThroughput (Double, optional) - upload rate in Bps, defaults to 0 which disables upload throttling.

ses.preconnect() method

ses.preconnect(options) preconnects the given number of sockets to an origin. Options parameter is an Object with: url (string, required) - URL for preconnect, only the origin is relevant for opening the socket; numSockets (number, optional) - number of sockets to preconnect, must be between 1 and 6, defaults to 1.

ses.closeAllConnections() method

ses.closeAllConnections() returns Promise<void> - resolves when all connections are closed. Note: it will terminate or fail all requests currently in flight.

ses.fetch() method and limitations

ses.fetch(input[, init]) sends a request similarly to how fetch() works in the renderer, using Chromium's network stack. Parameters: input (string or GlobalRequest), init (RequestInit with optional bypassCustomProtocolHandlers boolean). Returns Promise<GlobalResponse>. By default, requests can be made to custom protocols and file:, and trigger webRequest handlers. When bypassCustomProtocolHandlers is set in RequestInit, custom protocol handlers will not be called for this request, allowing forwarding to the built-in handler, but webRequest handlers will still trigger. Limitations: does not support data: or blob: schemes; integrity option value is ignored; .type and .url values of returned Response object are incorrect.

ses.disableNetworkEmulation() method

ses.disableNetworkEmulation() disables any network emulation already active for the session and resets to the original network configuration.

ses.clearHostResolverCache() method

ses.clearHostResolverCache() returns Promise<void> - resolves when the operation is complete. Clears the host resolver cache.

ses.allowNTLMCredentialsForDomains() method

ses.allowNTLMCredentialsForDomains(domains) dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. domains parameter is a string containing a comma-separated list of servers for which integrated authentication is enabled. Use '*' to consider all URLs for integrated authentication, or patterns like '*example.com' to match domain suffixes.

Example: Enable network emulation

const win = new BrowserWindow() // To emulate a GPRS connection with 50kbps throughput and 500 ms latency. win.webContents.session.enableNetworkEmulation({ latency: 500, downloadThroughput: 6400, uploadThroughput: 6400 }) // To emulate a network outage. win.webContents.session.enableNetworkEmulation({ offline: true })

Example: Use ses.fetch()

async function example () { const response = await net.fetch('https://my.app') if (response.ok) { const body = await response.json() // ... use the result. } }

Example: Allow NTLM credentials for domains

const { session } = require('electron') // consider any url ending with `example.com`, `foobar.com`, `baz` // for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') // consider all urls for integrated authentication. session.defaultSession.allowNTLMCredentialsForDomains('*')

ses.registerLocalAIHandler() registers local AI utility process

The ses.registerLocalAIHandler(handler) method is experimental and accepts a UtilityProcess | null parameter. It registers a local AI handler UtilityProcess. To clear the handler, call registerLocalAIHandler(null), which will disconnect any existing Prompt API sessions and destroy any LanguageModelUtility instances.

Give your agent this brain