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 2 of 9.

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

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

BrowserView constructor and options

BrowserView is created with the constructor new BrowserView([options]). It accepts an optional options object with a webPreferences property of type WebPreferences, which defines settings for the web page's features.

BrowserView.setBackgroundColor() method and supported color formats

The setBackgroundColor(color) method sets the background color of the BrowserView. Supported color formats are: Hex (#fff, #ffff, #ffffff, #ffffffff), RGB (rgb(255, 255, 255)), RGBA (rgba(255, 255, 255, 1.0)), HSL (hsl(200, 20%, 50%)), HSLA (hsla(200, 20%, 50%, 0.5)), and named CSS colors (e.g., blueviolet, red). Hex format with alpha takes AARRGGBB or ARGB, not RRGGBBAA or RGB. Color names are case-sensitive and similar to CSS Color Module Level 3 keywords.

BrowserView.setBounds() method

The setBounds(bounds) method resizes and moves the view to the supplied bounds relative to the window. It takes a Rectangle parameter.

BrowserView.setAutoResize() method

The setAutoResize(options) method configures how a BrowserView resizes with its window. Options: width (boolean, default false) - if true, the view's width grows and shrinks with the window; height (boolean, default false) - if true, the view's height grows and shrinks with the window; horizontal (boolean, default false) - if true, the view's x position and width grow and shrink proportionally with the window; vertical (boolean, default false) - if true, the view's y position and height grow and shrink proportionally with the window.

BrowserView.getBounds() method

The getBounds() method returns a Rectangle object representing the bounds of the BrowserView instance.

Reading bookmark from clipboard example

const { clipboard } = require('electron') async function dumpClipboard () { const bookmarkType = 'electron application/bookmark' const items = await clipboard.read() for (const item of items) { if (item.types.includes(bookmarkType)) { const bookmark = await item.getType(bookmarkType) console.log('Bookmark found: ', bookmark) } else { console.log('There is no bookmark present') } } } This example shows checking for and reading a bookmark from clipboard items.

Reading clipboard items example

const { clipboard, ClipboardItem } = require('electron') async function readFiles () { const [item] = await clipboard.read() if (item.types.includes('text/uri-list')) { const blob = await item.getType('text/uri-list') if (blob instanceof Blob) { const uriList = await blob.text() return uriList.split(/\r?\n/).filter(Boolean) } } return [] } This example shows reading files from the clipboard and parsing the URI list.

Dumping all clipboard item payloads example

const { clipboard } = require('electron') async function dumpClipboard () { const items = await clipboard.read() for (const item of items) { for (const type of item.types) { const payload = await item.getType(type) console.log(type, payload) } } } This example shows iterating through all clipboard items and their MIME types, retrieving and logging each payload.

ClipboardItem.types property

clipboardItem.types is a read-only string array property containing the MIME types of the data carried by the clipboard entry. For a constructed ClipboardItem, these are the keys passed to the constructor. For an item returned by clipboard.read(), these are the MIME types the platform clipboard currently makes available.

Writing files to clipboard example

const { clipboard, ClipboardItem } = require('electron') const { pathToFileURL } = require('node:url') // Write two files to the clipboard so they can be pasted into the OS file manager. clipboard.write([ new ClipboardItem({ 'text/uri-list': [ pathToFileURL('/path/to/first.txt').href, pathToFileURL('/path/to/second.txt').href ].join('\r\n') }) ]) This example shows writing multiple files to the clipboard using the text/uri-list MIME type so they can be pasted into native file managers.

ClipboardItem constructor example

const { clipboard, ClipboardItem, nativeImage } = require('electron') const png = nativeImage.createFromPath('/path/to/icon.png').toPNG() clipboard.write([ new ClipboardItem({ 'text/plain': 'hello', 'text/html': '<b>hello</b>', 'image/png': new Blob([png], { type: 'image/png' }), 'electron application/bookmark': { title: 'Electron', url: 'https://electronjs.org' } }) ]) This example shows creating a ClipboardItem with multiple MIME-typed representations including text, HTML, image, and bookmark formats.

ClipboardItem.getType(type) method

clipboardItem.getType(type) takes a string parameter representing a MIME type to retrieve. It returns Promise<Blob> | Promise<ClipboardBookmark>. The promise resolves with the payload for the given MIME type. For most MIME types it resolves to a Blob; the exception is getType('electron application/bookmark') which resolves to a ClipboardBookmark object. The method rejects when the type is not present in clipboardItem.types.

ClipboardItem constructor parameters

The ClipboardItem constructor takes an `items` parameter of type Record<string, string | ClipboardBookmark | Blob | Promise<Blob | string>>. The keys are MIME types and the values are the payload for that type. String values are UTF-8 encoded into payload bytes. Blob objects supply raw payload bytes. The custom format 'electron application/bookmark' accepts a ClipboardBookmark object. Non-bookmark values may also be Promises that resolve to a Blob or string, which are awaited when clipboard.write() is called.

app.commandLine.appendSwitch usage pattern

Command-line switches can be appended to an Electron app using app.commandLine.appendSwitch() before the ready event of the app module is emitted. Example: app.commandLine.appendSwitch('remote-debugging-port', '8315') and app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'). This must be called in the app's main script before app.whenReady() resolves.

getSwitchValue example retrieving port value

const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') const portValue = app.commandLine.getSwitchValue('remote-debugging-port') console.log(portValue) // '8315'

CommandLine appendArgument does not affect process.argv

When using commandLine.appendArgument(), the changes only affect Chromium's command line and do not modify process.argv.

removeSwitch example

const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') console.log(app.commandLine.hasSwitch('remote-debugging-port')) // true app.commandLine.removeSwitch('remote-debugging-port') console.log(app.commandLine.hasSwitch('remote-debugging-port')) // false

CommandLine removeSwitch does not affect process.argv

When using commandLine.removeSwitch(), the changes only affect Chromium's command line and do not modify process.argv.

CommandLine appendSwitch does not affect process.argv

When using commandLine.appendSwitch(), the changes only affect Chromium's command line and do not modify process.argv.

hasSwitch example checking for disable-gpu flag

const { app } = require('electron') app.commandLine.hasSwitch('disable-gpu')

commandLine.removeSwitch() method

commandLine.removeSwitch(switch) removes the specified switch from Chromium's command line. Parameters: switch (string, required) - a command-line switch. This will not affect process.argv and is intended to control Chromium's behavior.

hasSwitch example checking for remote debugging port

const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') const hasPort = app.commandLine.hasSwitch('remote-debugging-port') console.log(hasPort) // true

appendArgument example with experimental feature

const { app } = require('electron') app.commandLine.appendArgument('--enable-experimental-web-platform-features')

appendSwitch example with remote debugging port

const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315')

commandLine.getSwitchValue() method

commandLine.getSwitchValue(switch) obtains a Chromium command line switch value. Parameters: switch (string, required) - a command-line switch. Returns string - the command-line switch value. This function is meant to obtain Chromium command line switches, not application-specific command line arguments; use process.argv for the latter. When the switch is not present or has no value, it returns an empty string.

commandLine.hasSwitch() method

commandLine.hasSwitch(switch) checks whether a command-line switch is present. Parameters: switch (string, required) - a command-line switch. Returns boolean - whether the command-line switch is present.

commandLine.appendArgument() method

commandLine.appendArgument(value) appends an argument to Chromium's command line. Parameters: value (string, required) - the argument to append to the command line. The argument will be quoted correctly. Switches will precede arguments regardless of appending order. This will not affect process.argv and is intended to control Chromium's behavior. When appending an argument like '--switch=value', consider using appendSwitch('switch', 'value') instead.

commandLine.appendSwitch() method

commandLine.appendSwitch(switch[, value]) appends a switch (with optional value) to Chromium's command line. Parameters: switch (string, required) - a command-line switch without the leading '--', value (string, optional) - a value for the given switch. This will not affect process.argv and is intended to control Chromium's behavior.

contentTracing.getTraceBufferUsage() method

contentTracing.getTraceBufferUsage() returns Promise<Object> that resolves with an object containing value (number) and percentage (number) properties. It gets the maximum usage across processes of trace buffer as a percentage of the full state.

contentTracing basic usage example

const { app, contentTracing } = require('electron') app.whenReady().then(() => { (async () => { await contentTracing.startRecording({ included_categories: ['*'] }) console.log('Tracing started') await new Promise(resolve => setTimeout(resolve, 5000)) const path = await contentTracing.stopRecording() console.log('Tracing data recorded to ' + path) })() }) This example starts recording with all categories, waits 5 seconds, then stops recording and logs the output file path.

contentTracing.enableHeapProfiling() method (experimental)

contentTracing.enableHeapProfiling([options]) accepts optional EnableHeapProfilingOptions and returns Promise<void> that resolves once heap profiling has been enabled. It enables heap profiling for MemoryInfra traces, equivalent to the --memlog switch in Chrome. Only takes effect if the disabled-by-default-memory-infra category is included. Must be called before contentTracing.startRecording().

contentTracing.stopRecording() method

contentTracing.stopRecording([resultFilePath]) accepts an optional resultFilePath string parameter and returns Promise<string> that resolves with a path to a file containing the traced data once all child processes have acknowledged the stopRecording request. Child processes cache trace data and asynchronously flush and send trace data back to the main process. If resultFilePath is empty or not provided, trace data will be written to a temporary file and the path will be returned in the promise.

contentTracing.startRecording() method

contentTracing.startRecording(options) accepts options as either TraceConfig or TraceCategoriesAndOptions and returns Promise<void> that resolves once all child processes have acknowledged the startRecording request. Recording begins immediately locally and asynchronously on child processes as soon as they receive the EnableRecording request. If a recording is already running, the promise will be immediately resolved, as only one trace operation can be in progress at a time.

contentTracing.getCategories() method

contentTracing.getCategories() returns Promise<string[]> that resolves with an array of category groups once all child processes have acknowledged the request. The category groups can change as new code paths are reached. Electron adds a non-default tracing category called 'electron' that can be used to capture Electron-specific tracing events.

contentTracing heap profiling usage example

const { contentTracing } = require('electron') async function recordTrace () { await contentTracing.enableHeapProfiling() await contentTracing.startRecording({ included_categories: ['disabled-by-default-memory-infra'], excluded_categories: ['*'], memory_dump_config: { triggers: [ { mode: 'detailed', periodic_interval_ms: 1000 } ] } }) await new Promise(resolve => setTimeout(resolve, 5000)) const filePath = await contentTracing.stopRecording() } This example enables heap profiling, starts recording memory infra traces with detailed periodic triggers every 1000ms, waits 5 seconds, then stops recording.

Cookies.get example

Example code showing how to query all cookies and cookies for a specific URL: const { session } = require('electron') // Query all cookies. session.defaultSession.cookies.get({}) .then((cookies) => { console.log(cookies) }).catch((error) => { console.log(error) }) // Query all cookies associated with a specific url. session.defaultSession.cookies.get({ url: 'https://www.github.com' }) .then((cookies) => { console.log(cookies) }).catch((error) => { console.log(error) })

Cookies.remove method

The remove method removes cookies matching a URL and name. It accepts a url parameter (the URL associated with the cookie) and a name parameter (the name of the cookie to remove). Returns a Promise that resolves when the cookie has been removed.

Cookies.set method

The set method sets a cookie with provided details. The details object requires a url property (the URL to associate with the cookie; promise rejects if invalid). Optional properties are: name (cookie name, defaults to empty string), value (cookie value, defaults to empty string), domain (cookie domain, normalized with preceding dot for subdomain validity, defaults to empty string), path (cookie path, defaults to empty string), secure (whether marked as Secure, defaults to false unless SameSite=None is used), httpOnly (whether marked as HTTP only, defaults to false), expirationDate (expiration as seconds since UNIX epoch; if omitted becomes a session cookie not retained between sessions), and sameSite (Same Site policy: 'unspecified', 'no_restriction', 'lax', or 'strict', defaults to 'lax'). Returns a Promise that resolves when the cookie has been set.

Cookies.get method

The get method queries cookies matching a filter. It accepts a filter object with optional properties: url (retrieves cookies associated with the URL, empty implies all URLs), name (filters by cookie name), domain (retrieves cookies whose domains match or are subdomains), path (retrieves cookies matching the path), secure (filters by Secure property), session (filters session or persistent cookies), and httpOnly (filters by httpOnly property). Returns a Promise that resolves with an array of cookie objects.

Cookies.flushStore method

The flushStore method writes any unwritten cookies data to disk immediately. Cookies written by methods are not written to disk immediately but are written every 30 seconds or after 512 operations. Calling this method causes the cookie to be written to disk immediately. Returns a Promise that resolves when the cookie store has been flushed.

Cookies.set example

Example code showing how to set a cookie: const { session } = require('electron') const cookie = { url: 'https://www.github.com', name: 'dummy_name', value: 'dummy' } session.defaultSession.cookies.set(cookie) .then(() => { // success }, (error) => { console.error(error) })

Debugger isAttached method

The isAttached() method returns a boolean indicating whether a debugger is attached to the webContents.

Debugger detach method

The detach() method detaches the debugger from the webContents.

Debugger attach method

The attach([protocolVersion]) method attaches the debugger to the webContents. The protocolVersion parameter is optional and specifies the requested debugging protocol version.

Debugger sendCommand method

The sendCommand(method[, commandParams, sessionId]) method sends a command to the debugging target. The method parameter is a string specifying the method name as defined by the remote debugging protocol. The commandParams parameter is optional and is a JSON object with request parameters. The sessionId parameter is optional and specifies the target debugging session id to send the command to. The method returns a Promise that resolves with the response defined by the 'returns' attribute of the command description in the remote debugging protocol, or is rejected if the command fails.

crashReporter in Node child processes

In Node child processes where require('electron') is not available, the following crashReporter APIs are available on the process object: process.crashReporter.start(options), process.crashReporter.getParameters(), process.crashReporter.addExtraParameter(key, value), and process.crashReporter.removeExtraParameter(key). These methods have the same functionality as their crashReporter counterparts. If the crash reporter is started in the main process, it will automatically monitor child processes, so it should not be started in the child process. Only use process.crashReporter.start() if the main process does not initialize the crash reporter.

crashReporter.getUploadedReports() method

crashReporter.getUploadedReports() returns CrashReport[]. It returns all uploaded crash reports. Each report contains the date and uploaded ID. This method is only available in the main process.

crashReporter.getLastCrashReport() method

crashReporter.getLastCrashReport() returns CrashReport | null. It returns the date and ID of the last crash report. Only crash reports that have been uploaded will be returned; even if a crash report is present on disk it will not be returned until it is uploaded. If no uploaded reports exist, null is returned. This method is only available in the main process.

crashReporter.setUploadToServer() method

crashReporter.setUploadToServer(uploadToServer) accepts a boolean parameter indicating whether reports should be submitted to the server. This would normally be controlled by user preferences. This method has no effect if called before start is called. This method is only available in the main process.

crashReporter.start() requirements and timing

crashReporter.start() must be called before using any other crashReporter APIs. Once initialized, the crashpad handler collects crashes from all subsequently created processes. The crash reporter cannot be disabled once started. This method should be called as early as possible in app startup, preferably before app.on('ready'). If not initialized before a renderer process is created, that renderer process will not be monitored. This method is only available in the main process.

crashReporter extra parameter limits

Parameters passed in extra, globalExtra, or set with addExtraParameter have length limits: key names must be at most 39 bytes long, and values must be no longer than 127 bytes. For addExtraParameter specifically, values must be no longer than 20320 bytes. Keys with names longer than the maximum will be silently ignored. Key values longer than the maximum length will be truncated.

crashReporter.addExtraParameter() method

crashReporter.addExtraParameter(key, value) accepts key (string, must be no longer than 39 bytes) and value (string, must be no longer than 20320 bytes). This method sets an extra parameter to be sent with the crash report. Values are sent in addition to values set via the extra option when start was called. Parameters added are specific to the calling process: adding in main process does not cause them to be sent with renderer or child process crashes, and vice versa. Keys longer than maximum will be silently ignored, and values longer than maximum will be truncated.

crashReporter.start() options

crashReporter.start(options) accepts an Object with the following properties: submitURL (string, optional) - URL that crash reports will be sent to as POST, required unless uploadToServer is false; productName (string, optional) - defaults to app.name; companyName (string, optional, deprecated) - use globalExtra with _companyName instead; uploadToServer (boolean, optional) - whether to send reports to server, default true; ignoreSystemCrashHandler (boolean, optional) - if true, crashes in main process will not be forwarded to system crash handler, default false; rateLimit (boolean, optional, macOS Windows only) - if true, limit crashes uploaded to 1/hour, default false; compress (boolean, optional) - if true, reports compressed with Content-Encoding: gzip, default true; extra (Record<string, string>, optional) - extra string key/value annotations sent with main process crashes only, child processes must use addExtraParameter; globalExtra (Record<string, string>, optional) - extra string key/value annotations sent with all crash reports from any process, cannot be changed after start, global takes precedence over process-specific, includes productName, app version, and Electron version by default.

crashReporter.removeExtraParameter() method

crashReporter.removeExtraParameter(key) accepts a key parameter (string, must be no longer than 39 bytes). This method removes an extra parameter from the current set of parameters. Future crashes will not include this parameter.

crashReporter.getParameters() method

crashReporter.getParameters() returns Record<string, string> containing the current 'extra' parameters of the crash reporter.

Crash report payload fields

The crash reporter sends the following data to the submitURL as multipart/form-data POST: ver (string) - version of Electron; platform (string) - e.g. 'win32'; process_type (string) - e.g. 'renderer'; guid (string) - e.g. '5e1286fc-da97-479e-918b-6bfb0c3d1c72'; _version (string) - version in package.json; _productName (string) - product name from crashReporter options; prod (string) - name of underlying product (Electron); _companyName (string) - company name from crashReporter options; upload_file_minidump (File) - crash report in minidump format; all level one properties of the extra object from crashReporter options.

Give your agent this brain