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/methods

526 notes in this subject, read out of this brain and free to use. This is page 1 of 9.

Method: app.isHardwareAccelerationEnabled()

Returns boolean - whether hardware acceleration is currently enabled. This information is only usable after the gpu-info-update event is emitted.

Method: app.disableDomainBlockingFor3DAPIs()

By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU process crashes too frequently. This function disables that behavior. This method can only be called before app is ready.

Method: app.configureHostResolver example

Example of configuring secure DNS: const { app } = require('electron') app.whenReady().then(() => { app.configureHostResolver({ secureDnsMode: 'secure', secureDnsServers: [ 'https://cloudflare-dns.com/dns-query' ] }) })

Method: app.disableHardwareAcceleration()

Disables hardware acceleration for current app. This method can only be called before app is ready.

Method: app.configureWebAuthn example

Example of configuring Web Authentication: const { app } = require('electron') app.configureWebAuthn({ touchID: { keychainAccessGroup: 'A1B2C3D4E5.com.example.app.webauthn', promptReason: 'sign in to $1' }, platformPasskeys: true }) With matching entitlements in app's entitlements.plist: <key>keychain-access-groups</key> <array> <string>A1B2C3D4E5.com.example.app.webauthn</string> </array> For platform passkeys, app needs Associated Domains entitlement plus application identifier: <key>com.apple.developer.associated-domains</key> <array> <string>webcredentials:example.com</string> </array> <key>com.apple.application-identifier</key> <string>A1B2C3D4E5.com.example.app</string>

Method: app.configureWebAuthn(options) (macOS only)

Takes options Object with: touchID Object (optional, enables Touch ID / Secure Enclave platform authenticator for Web Authentication requests, with keychainAccessGroup string required value for keychain access group that WebAuthn credentials stored under - must be present in app's keychain-access-groups code-signing entitlement, typically form <TEAM_ID>.<BUNDLE_ID>.webauthn, and optional promptReason string customizing reason text shown in macOS Touch ID prompt), platformPasskeys boolean (optional, enables passkeys via Apple's ASAuthorizationController, when enabled passkey operations present system credential provider sheet). Configures platform authenticators for Web Authentication API (navigator.credentials.create() / navigator.credentials.get()). Until this is called, PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() resolves to false and platform-authenticator requests are not serviced. When touchID is provided, WebAuthn credentials are stored in macOS keychain and bound to device's Secure Enclave. When platformPasskeys is true, passkey operations use Apple's ASAuthorizationController. This API must be called before app ready.

Method: app.configureHostResolver(options)

Takes options Object with: enableBuiltInResolver boolean (optional, whether built-in host resolver is used in preference to getaddrinfo, enabled by default on macOS, disabled by default on Windows and Linux), enableHappyEyeballs boolean (optional, whether Happy Eyeballs V3 algorithm should be used in creating network connections), secureDnsMode string (optional, can be 'off', 'automatic' or 'secure', configures DNS-over-HTTP mode, defaults to 'automatic'), secureDnsServers string[] (optional, list of DNS-over-HTTP server templates following RFC8484 template format), enableAdditionalDnsQueryTypes boolean (optional, controls whether additional DNS query types like HTTPS will be allowed besides traditional A and AAAA queries when request is made via insecure DNS, defaults to true). Configures host resolution (DNS and DNS-over-HTTPS). By default, resolvers are used in order: 1) DNS-over-HTTPS (if DNS provider supports it), 2) built-in resolver (enabled on macOS only by default), 3) system resolver. This can be configured to restrict usage of non-encrypted DNS or disable DNS-over-HTTPS. This API must be called after the ready event is emitted.

Method: app.getAppMetrics()

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

Method: app.getGPUFeatureStatus()

Returns GPUFeatureStatus - The Graphics Feature Status from chrome://gpu/. This information is only usable after the gpu-info-update event is emitted.

Method: 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.

Method: app.exit([exitCode])

Exits immediately with exitCode. exitCode Integer (optional), 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.

Method: app.relaunch([options])

Relaunches the app when the current instance exits. Takes optional options Object with args string[] (optional, command line arguments for new instance) and execPath string (optional, executable path for relaunch). By default, the new instance will use the same working directory and command line arguments as the current instance. When args is specified, the args will be passed as the command line arguments instead. When execPath is specified, the execPath will be executed for the relaunch instead of the 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 multiple times, multiple instances will be started after the current instance exits.

Method: app.relaunch example

Example of restarting the 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)

Method: app.isReady()

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

Method: 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.

Method: app.focus([options])

Takes optional options Object with steal boolean (macOS only, make the receiver the active app even if another app is currently active). On macOS, makes the application the active app. On Windows, focuses on the application's first window. On Linux, either focuses on the first visible window (X11) or requests focus but may instead show a notification or flash the app icon (Wayland). You should seek to use the steal option as sparingly as possible.

Method: app.isActive() (macOS only)

Returns boolean - true if the application is active (i.e. focused).

Method: app.hide() (macOS only)

Hides all application windows without minimizing them.

Method: app.isHidden() (macOS only)

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

Method: app.show() (macOS only)

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

Method: app.setAppLogsPath([path])

Sets or creates a directory your app's logs which can then be manipulated with app.getPath() or app.setPath(pathName, newPath). Takes optional path string (custom path for logs, must be absolute). 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.

Method: app.getAppPath()

Returns string - The current application directory.

Method: app.setUserTasks(tasks) (Windows only)

Takes tasks Task[] (array of Task objects). Adds tasks to the Tasks category of the Jump List on Windows. Returns boolean - whether the call succeeded. If you'd like to customize the Jump List even more use app.setJumpList(categories) instead.

Method: app.getPath(name)

Takes name string requesting one of the following paths: home (user's home directory), appData (per-user application data directory: %APPDATA% on Windows, $XDG_CONFIG_HOME or ~/.config on Linux, ~/Library/Application Support on macOS), assets (directory where app assets such as resources.pak are stored, Windows and Linux only), userData (directory for storing app's configuration files, default is appData directory appended with app's name), sessionData (directory for storing data generated by Session such as localStorage, cookies, disk cache, downloaded dictionaries, network state, DevTools files, default is userData), temp (temporary directory), exe (current executable file), module (location of Chromium module, default is exe), desktop (current user's Desktop directory), documents (directory for user's My Documents), downloads (directory for user's downloads), music (directory for user's music), pictures (directory for user's pictures), videos (directory for user's videos), recent (directory for user's recent files, Windows only), logs (directory for app's log folder), crashDumps (directory where crash dumps are stored). Returns string - path to special directory or file associated with name. On failure, an Error is thrown. If app.getPath('logs') is called without app.setAppLogsPath() being called first, a default log directory will be created equivalent to calling app.setAppLogsPath() without a path parameter.

Method: app.getFileIcon(path[, options])

Fetches a path's associated icon. Takes path string and optional options Object with size string (small: 16x16, normal: 32x32, large: 48x48 on Linux, 32x32 on Windows, unsupported on macOS). Returns Promise<NativeImage> - fulfilled with the app's icon. On Windows, there are 2 kinds of icons: icons associated with certain file extensions like .mp3, .png, etc., and icons inside the file itself like .exe, .dll, .ico. On Linux and macOS, icons depend on the application associated with file mime type.

Method: app.setPath(name, path)

Overrides the path to a special directory or file associated with name. Takes name string and path string. 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.

Method: 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.

Method: 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.

Method: app.setName(name)

Takes name string. Overrides the current application's name. This function overrides the name used internally by Electron; it does not affect the name that the OS uses.

Method: app.setDesktopName(name) (Linux only)

Takes name string (the .desktop filename, e.g. 'my-app.desktop'). Sets the .desktop filename on Linux. This should match the base filename of the app's installed .desktop file. The .desktop suffix is optional. This value is used to determine the default XDG application ID on Wayland and WM_CLASS on X11. If it is not set, Electron will attempt to infer a name, but it may not match the packaged app's actual .desktop file. This could result in the app showing a generic icon or failing to respond to global keyboard shortcuts. This API must be called before the ready event. The value can also be set using desktopName in package.json.

Method: app.getLocale()

Returns string - The current application locale, fetched using Chromium's l10n_util library. Possible return values are documented at https://source.chromium.org/chromium/chromium/src/+/main:ui/base/l10n/l10n_util.cc. To set the locale, use a command line switch at app startup. When distributing your packaged app, you have to also ship the locales folder. This API must be called after the ready event is emitted. To see example return values of this API compared to other locale and language APIs, see app.getPreferredSystemLanguages().

Method: app.getLocaleCountryCode()

Returns string - User operating system's locale two-letter ISO 3166 country code. The value is taken from native OS APIs. When unable to detect locale country code, it returns empty string.

Method: 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 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. This API must be called after the ready event is emitted. To see example return values of this API compared to other locale and language APIs, see app.getPreferredSystemLanguages().

Method: 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.

Method: app.getPreferredSystemLanguages example

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. 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.

Method: app.addRecentDocument(path) (macOS Windows only)

Takes 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.

Method: app.clearRecentDocuments() (macOS Windows only)

Clears the recent documents list.

Method: app.getRecentDocuments() (macOS Windows only)

Returns string[] - An array containing documents in the most recent documents list.

Method: app.getRecentDocuments example

Example showing how to add and retrieve recent documents: const { app } = require('electron') const path = require('node:path') const file = path.join(app.getPath('desktop'), 'foo.txt') app.addRecentDocument(file) const recents = app.getRecentDocuments() console.log(recents) // ['/path/to/desktop/foo.txt'}

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

Takes protocol string (name of your protocol without ://, e.g. electron for electron:// links), optional path string (Windows only, path to Electron executable, defaults to process.execPath), and optional args string[] (Windows only, arguments passed to executable, defaults to 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. 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 Forge, Electron Packager, or by editing info.plist with a text editor. 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.

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

Takes protocol string (name of your protocol without ://), optional path string (Windows only, defaults to process.execPath), and optional args string[] (Windows only, defaults to empty array). Returns boolean - whether the current executable is the default handler for a protocol (aka URI scheme). 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. The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.

Method: app.getApplicationNameForProtocol(url)

Takes url string (a URL with the protocol name to check, unlike other methods in this family, this accepts an entire URL including :// at 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.

Method: app.getApplicationInfoForProtocol(url)

Takes url string (a URL with the protocol name to check, unlike other methods in this family, this accepts an entire URL including :// at minimum, e.g. https://). Returns Promise<Object> - Resolve with an object containing icon NativeImage (display icon of app handling protocol), path string (installation path of app handling protocol), and name string (display name of app handling 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.

Method: app.getJumpListSettings() (Windows only)

Returns Object containing: minItems Integer (minimum number of items that will be shown in Jump List) and removedItems JumpListItem[] (array of JumpListItem objects that correspond to items that the user has explicitly removed from custom categories in Jump List. These items must not be re-added in next call to app.setJumpList(), Windows will not display any custom category containing any removed items).

Method: app.setJumpList(categories) (Windows only)

Takes categories JumpListCategory[] | null (array of JumpListCategory objects). Sets or removes a custom Jump List for the application. Returns string - one of: 'ok' (nothing went wrong), 'error' (one or more errors occurred, enable runtime logging to figure out the likely cause), 'invalidSeparatorError' (attempt was made to add separator to custom category in Jump List, separators only allowed in Tasks category), 'fileTypeRegistrationError' (attempt was made to add file link to Jump List for file type app isn't registered to handle), 'customCategoryAccessDeniedError' (custom categories can't be added 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). If a JumpListCategory object has neither type nor name property set then type is assumed to be tasks. If name property is set but type property is omitted then type is assumed to be custom. Users can remove items from custom categories, and Windows will not allow a removed item to be re-added into custom category until after the next successful call to app.setJumpList(categories). The maximum length of a Jump List item's description property is 260 characters. Beyond this limit, the item will not be added to Jump List.

Method: app.setJumpList example

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

Method: app.requestSingleInstanceLock([additionalData])

Takes optional additionalData Record<any, any> (JSON object containing additional data to send to first instance). Returns boolean. The return value 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. 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.

Method: app.requestSingleInstanceLock example

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

Method: 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().

Method: 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.

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

Takes type string (uniquely identifies the activity, maps to NSUserActivity.activityType), userInfo any (app-specific state to store for use by another device), and optional webpageURL string (webpage to load in browser if no suitable app is installed on resuming device, 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.

Method: app.getCurrentActivityType() (macOS only)

Returns string - The type of the currently running activity.

Method: app.invalidateCurrentActivity() (macOS only)

Invalidates the current Handoff user activity.

Method: app.resignCurrentActivity() (macOS only)

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

Method: app.updateCurrentActivity(type, userInfo) (macOS only)

Takes type string (uniquely identifies the activity, maps to NSUserActivity.activityType) and 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.

Method: app.setAppUserModelId(id) (Windows only)

Takes id string. Changes the Application User Model ID to id.

Method: app.setToastActivatorCLSID(id) (Windows only)

Takes id string. Changes the Toast Activator CLSID to id. If one is not set via this method, it will be randomly generated for the app. The value must be a valid GUID/CLSID in one of the following forms: Canonical brace-wrapped: {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} (preferred) or Canonical without braces: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX (braces will be added automatically). Hex digits are case-insensitive. This method should be called early (before showing notifications) so the value is baked into the registration/shortcut. Supplying an empty string or an unparsable value throws and leaves the existing (or generated) CLSID unchanged. If this method is never called, a random CLSID is generated once per run and exposed via app.toastActivatorCLSID.

Method: app.setActivationPolicy(policy) (macOS only)

Takes policy string (can be 'regular', 'accessory', or 'prohibited'). Sets the activation policy for a given app. Activation policy types: 'regular' - application is an ordinary app that appears in Dock and may have user interface, 'accessory' - application doesn't appear in Dock and doesn't have menu bar but it may be activated programmatically or by clicking on one of its windows, 'prohibited' - application doesn't appear in Dock and may not create windows or be activated.

Method: app.importCertificate(options, callback) (Linux only)

Takes options Object with certificate string (path for pkcs12 file) and password string (passphrase for certificate), and callback Function with result Integer (result of import operation, 0 indicates success, any other value indicates failure according to Chromium net_error_list). Imports the certificate in pkcs12 format into the platform certificate store. Callback is called with the result of import operation.

Method: app.getGPUInfo(infoType)

Takes infoType string (can be 'basic' or 'complete'). Returns Promise<unknown>. For infoType equal to 'complete': Promise is fulfilled with Object containing all GPU Information as in chromium's GPUInfo object. This includes version and driver information shown on chrome://gpu page. For infoType equal to 'basic': Promise is fulfilled with Object containing fewer attributes than when requested with 'complete'. Using 'basic' should be preferred if only basic information like vendorId or deviceId is needed. Promise is rejected if GPU is completely disabled (no hardware and software implementations available).

Give your agent this brain