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

dialog.showOpenDialog options

dialog.showOpenDialog accepts an options object with: title (string, optional), defaultPath (string, optional - Absolute directory path, absolute file path, or file name to use by default. If not provided, defaults to user's Downloads folder, or home directory if Downloads doesn't exist.), buttonLabel (string, optional - Custom label for confirmation button, default used if empty), filters (FileFilter[], optional), properties (string[], optional - openFile, openDirectory, multiSelections, showHiddenFiles (macOS Windows), createDirectory (macOS), promptToCreate (Windows), noResolveAliases (macOS), treatPackageAsDirectory (macOS), dontAddToRecent (Windows)), message (string, optional, macOS only - Message to display above input boxes), securityScopedBookmarks (boolean, optional, macOS mas only - Create security scoped bookmarks when packaged for Mac App Store).

globalShortcut.setSuspended(suspended)

Suspends or resumes global shortcut handling. When suspended, all registered global shortcuts stop listening for key presses. When resumed, all previously registered shortcuts begin listening again. New shortcut registrations fail while handling is suspended. This is useful when temporarily allowing users to press key combinations without the application intercepting them, for example while displaying a UI to rebind shortcuts. Parameters: suspended (boolean) - Whether global shortcut handling should be suspended.

globalShortcut.isSuspended()

Returns boolean indicating whether global shortcut handling is currently suspended.

globalShortcut registration example

Example showing how to register, check, and unregister global shortcuts: const { app, globalShortcut } = require('electron') // Enable usage of Portal's globalShortcuts. This is essential for cases when // the app runs in a Wayland session. app.commandLine.appendSwitch('enable-features', 'GlobalShortcutsPortal') app.whenReady().then(() => { // Register a 'CommandOrControl+X' shortcut listener. const ret = globalShortcut.register('CommandOrControl+X', () => { console.log('CommandOrControl+X is pressed') }) if (!ret) { console.log('registration failed') } // Check whether a shortcut is registered. console.log(globalShortcut.isRegistered('CommandOrControl+X')) }) app.on('will-quit', () => { // Unregister a shortcut. globalShortcut.unregister('CommandOrControl+X') // Unregister all shortcuts. globalShortcut.unregisterAll() })

globalShortcut.unregisterAll()

Unregisters all of the registered global shortcuts.

globalShortcut.unregister(accelerator)

Unregisters the global shortcut of the specified accelerator. Parameters: accelerator (string) - An accelerator shortcut.

globalShortcut.isRegistered(accelerator)

Checks whether the application has registered the specified accelerator. Returns boolean indicating whether this application has registered the accelerator. When the accelerator is already taken by other applications, this call returns false. Parameters: accelerator (string) - An accelerator shortcut.

globalShortcut.registerAll media accelerators on macOS 10.14

The following accelerators will not be registered successfully on macOS 10.14 Mojave unless the app has been authorized as a trusted accessibility client: 'Media Play/Pause', 'Media Next Track', 'Media Previous Track', 'Media Stop'.

globalShortcut.registerAll(accelerators, callback)

Registers a global shortcut for all accelerators in the accelerators array. The callback is called when any of the registered shortcuts are pressed by the user. When a given accelerator is already taken by other applications, the call silently fails. Parameters: accelerators (string[]) - An array of accelerator shortcuts; callback (Function) - Function called when any shortcut is pressed.

inAppPurchase.purchaseProduct method

inAppPurchase.purchaseProduct(productID[, opts]) purchases a product. Parameters: productID (string), opts (Integer | Object, optional). When opts is an integer, it defines the quantity. When opts is an object, it accepts: quantity (Integer, optional) for the number of items to purchase, and username (string, optional) to associate the transaction with a user account on your service (applicationUsername). Returns Promise<boolean> which resolves to true if the product is valid and added to the payment queue. You should listen for the transactions-updated event as soon as possible and certainly before calling purchaseProduct.

inAppPurchase.finishTransactionByDate method

inAppPurchase.finishTransactionByDate(date) completes pending transactions corresponding to a specific date. Parameter: date (string) - the ISO formatted date of the transaction to finish.

inAppPurchase.finishAllTransactions method

inAppPurchase.finishAllTransactions() completes all pending transactions.

inAppPurchase.getProducts method

inAppPurchase.getProducts(productIDs) retrieves product descriptions. Parameter: productIDs (string[]) - the identifiers of the products to get. Returns Promise<Product[]> which resolves with an array of Product objects.

inAppPurchase.getReceiptURL method

inAppPurchase.getReceiptURL() returns a string representing the path to the receipt.

inAppPurchase.restoreCompletedTransactions method

inAppPurchase.restoreCompletedTransactions() restores finished transactions. This method can be called to install purchases on additional devices, or to restore purchases for an application that the user deleted and reinstalled. The payment queue delivers a new transaction for each previously completed transaction that can be restored, with each transaction including a copy of the original transaction.

inAppPurchase.canMakePayments method

inAppPurchase.canMakePayments() returns a boolean indicating whether a user can make a payment.

LanguageModelUtility constructor

The constructor takes an initialState object with two required properties: contextUsage (number) and contextWindow (number). Do not use this constructor directly outside of the class itself, as it will not be properly connected to the localAIHandler.

languageModelUtility.destroy() method

languageModelUtility.destroy() is an experimental instance method that destroys the model and aborts any ongoing executions.

languageModelUtility.clone() method

languageModelUtility.clone(options) is an experimental instance method that clones the LanguageModelUtility such that the context and initial prompt are preserved. It takes options as LanguageModelCloneOptions and returns Promise<LanguageModelUtility>.

languageModelUtility.append() method

languageModelUtility.append(input, options) is an experimental instance method that appends a message without prompting for a response. It takes input as LanguageModelMessage[] and options as LanguageModelAppendOptions. It returns Promise<undefined>.

languageModelUtility.prompt() method

languageModelUtility.prompt(input, options) is an experimental instance method that prompts the model for a response. It takes input as LanguageModelMessage[] and options as LanguageModelPromptOptions. It returns Promise<string> | Promise<import('stream/web').ReadableStream<string>>.

LanguageModelUtility.availability() static method

LanguageModelUtility.availability([options]) is an experimental static method that determines the availability of the language model. It takes an optional LanguageModelCreateCoreOptions object and returns Promise<string>. The method returns one of four strings: 'available', 'downloadable', 'downloading', or 'unavailable'.

LanguageModelUtility.create() static method

LanguageModelUtility.create(options) is an experimental static method that creates a new LanguageModelUtility with the provided options. It takes a LanguageModelCreateOptions object and returns Promise<LanguageModelUtility>.

languageModelUtility.measureContextUsage() method

languageModelUtility.measureContextUsage(input, options) is an experimental instance method that measures how many tokens the input would use. It takes input as LanguageModelMessage[] and options as LanguageModelPromptOptions. It returns Promise<number>.

netLog startLogging example

const { app, netLog } = require('electron') app.whenReady().then(async () => { await netLog.startLogging('/path/to/net-log') // After some network events const path = await netLog.stopLogging() console.log('Net-logs written to', path) })

netLog.stopLogging() method

netLog.stopLogging() stops recording network events. If not called, net logging will automatically end when the app quits. The method returns Promise<void> that resolves when the net log has been flushed to disk.

netLog.startLogging() method

netLog.startLogging(path[, options]) starts recording network events to the specified file path. The path parameter is a string specifying the file path to record network logs. The options object is optional and can include: captureMode (string, optional) which determines what kinds of data should be captured—can be 'default' (only metadata, the default), 'includeSensitive' (includes cookies and authentication data), or 'everything' (includes all bytes transferred on sockets); maxFileSize (number, optional) which sets an automatic logging stop point when the log grows beyond this size, defaulting to unlimited. The method returns Promise<void> that resolves when the net log has begun recording.

net.request() example

const { app } = require('electron') app.whenReady().then(() => { const { net } = require('electron') const request = net.request('https://github.com') request.on('response', (response) => { console.log(`STATUS: ${response.statusCode}`) console.log(`HEADERS: ${JSON.stringify(response.headers)}`) response.on('data', (chunk) => { console.log(`BODY: ${chunk}`) }) response.on('end', () => { console.log('No more data in response.') }) }) request.end() }) This example shows how to use net.request() to make an HTTP request, listen for the response event, and handle response data.

net.fetch() example

async function example () { const response = await net.fetch('https://my.app') if (response.ok) { const body = await response.json() // ... use the result. } } This example shows how to use net.fetch() to make an HTTP request and parse the JSON response.

net.fetch() custom protocol handling

By default, requests made with net.fetch can be made to custom protocols as well as file:, and will trigger webRequest handlers if present. When the non-standard bypassCustomProtocolHandlers option is set in RequestInit, custom protocol handlers will not be called for this request, allowing forwarding an intercepted request to the built-in handler. webRequest handlers will still be triggered when bypassing custom protocols. In the utility process, custom protocols are not supported.

net.resolveHost() method

net.resolveHost(host, [options]) resolves a hostname and returns Promise<ResolvedHost> with the resolved IP addresses. The host parameter is a string hostname to resolve. The options object is optional and contains: queryType (string, optional) for requested DNS query type (A or AAAA); source (string, optional) for the source to use for resolved addresses with values 'any' (default), 'system', 'dns', 'mdns', or 'localOnly'; cacheUsage (string, optional) indicating what DNS cache entries can be used with values 'allowed' (default), 'staleAllowed', or 'disallowed'; and secureDnsPolicy (string, optional) controlling the resolver's Secure DNS behavior with values 'allow' (default) or 'disable'. This method resolves hosts from the default session.

net.isOnline() method

net.isOnline() returns a boolean indicating whether there is currently internet connection. A return value of false is a strong indicator that the user won't be able to connect to remote sites. However, a return value of true is inconclusive; even if some link is up, it is uncertain whether a particular connection attempt to a particular remote site will be successful.

net.fetch() method

net.fetch(input[, init]) sends a request similarly to how fetch() works in the renderer, using Chromium's network stack. The input parameter is either a string or GlobalRequest. The init parameter is optional and is RequestInit with an optional bypassCustomProtocolHandlers boolean property. It returns a Promise resolving to GlobalResponse. This method issues requests from the default session and differs from Node's fetch() which uses Node.js's HTTP stack.

net.fetch() limitations

net.fetch() does not support the data: or blob: schemes. The value of the integrity option is ignored. The .type and .url values of the returned Response object are incorrect.

net.request() method

net.request(options) creates a ClientRequest instance using the provided options which are directly forwarded to the ClientRequest constructor. The options parameter is either ClientRequestConstructorOptions or a string. It returns a ClientRequest instance and is used to issue both secure and insecure HTTP requests according to the specified protocol scheme.

net.fetch() bypassCustomProtocolHandlers example

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 }) } }) This example shows how to use the bypassCustomProtocolHandlers option to forward an intercepted request to the built-in handler.

net module ready event requirement

The net API can be used only after the application emits the ready event. Trying to use the module before the ready event will throw an error.

powerMonitor.getSystemIdleTime() method

powerMonitor.getSystemIdleTime() calculates the system idle time in seconds and returns an integer representing idle time.

powerMonitor.isOnBatteryPower() method

powerMonitor.isOnBatteryPower() returns a boolean indicating whether the system is on battery power. To monitor for changes in this property, use the 'on-battery' and 'on-ac' events.

powerMonitor.getCurrentThermalState() method

powerMonitor.getCurrentThermalState() returns the system's current thermal state as a string. Available on macOS only. The return value can be 'unknown', 'nominal', 'fair', 'serious', or 'critical'.

powerMonitor.getSystemIdleState() method

powerMonitor.getSystemIdleState(idleThreshold) calculates the system idle state. It takes an idleThreshold parameter which is an integer representing the amount of time in seconds before the system is considered idle. It returns a string that can be 'active', 'idle', 'locked', or 'unknown'. The 'locked' state is only available on supported systems.

powerSaveBlocker usage example

const { powerSaveBlocker } = require('electron') const id = powerSaveBlocker.start('prevent-display-sleep') console.log(powerSaveBlocker.isStarted(id)) powerSaveBlocker.stop(id)

powerSaveBlocker.isStarted method

powerSaveBlocker.isStarted(id) returns a boolean indicating whether the corresponding powerSaveBlocker with the given Integer id has started. The id parameter is the power save blocker id returned by powerSaveBlocker.start.

powerSaveBlocker.stop method

powerSaveBlocker.stop(id) stops the specified power save blocker, where id is the Integer returned by powerSaveBlocker.start. The method returns a boolean indicating whether the specified powerSaveBlocker has been stopped.

powerSaveBlocker.start method

powerSaveBlocker.start(type) starts preventing the system from entering lower-power mode and returns an Integer blocker ID. The type parameter is a string with two valid values: 'prevent-app-suspension' (prevents application suspension, keeps system active but allows screen off, used for downloading files or playing audio) or 'prevent-display-sleep' (prevents display sleep, keeps system and screen active, used for playing video). The prevent-display-sleep type has higher precedence over prevent-app-suspension, and only the highest precedence type takes effect.

process.setFdLimit(maxDescriptors) method - macOS Linux

process.setFdLimit(maxDescriptors) sets the file descriptor soft limit to maxDescriptors or the OS hard limit, whichever is lower, for the current process. Parameter: maxDescriptors (Integer). Only available on macOS and Linux.

process.getSystemVersion() method

process.getSystemVersion() returns a string representing the version of the host operating system. Returns actual operating system version instead of kernel version on macOS unlike os.release(). Examples: '10.13.6' on macOS, '10.0.17763' on Windows, '4.15.0-45-generic' on Linux.

process.getSystemMemoryInfo() method

process.getSystemMemoryInfo() returns an object with system memory statistics. Fields: total (Integer - total physical memory in Kilobytes available to system), free (Integer - memory not being used by applications or disk cache), available (Integer, Linux only - kernel's estimate of memory available for allocation without swapping from /proc/meminfo MemAvailable), fileBacked (Integer, macOS only - memory paged out to storage including file caches, network buffers, and system services), purgeable (Integer, macOS only - memory marked as purgeable that system can reclaim if memory pressure increases), swapTotal (Integer, Windows and Linux - total swap memory in Kilobytes), swapFree (Integer, Windows and Linux - free swap memory in Kilobytes). All statistics are reported in Kilobytes.

process.getProcessMemoryInfo() method

process.getProcessMemoryInfo() returns a Promise that resolves with a ProcessMemoryInfo structure. It returns an object giving memory usage statistics about the current process. All statistics are reported in Kilobytes. This API should be called after app is ready. On macOS, Chromium does not provide the residentSet value because macOS performs in-memory compression of pages that haven't been recently used. The private memory value is more representative of actual pre-compression memory usage on macOS.

process.getBlinkMemoryInfo() method

process.getBlinkMemoryInfo() returns an object with Blink memory information with fields: allocated (Integer - size of all allocated objects in Kilobytes) and total (Integer - total allocated space in Kilobytes). It can be useful for debugging rendering or DOM related memory issues.

process.getHeapStatistics() method

process.getHeapStatistics() returns an object with V8 heap statistics with fields: totalHeapSize (Integer), totalHeapSizeExecutable (Integer), totalPhysicalSize (Integer), totalAvailableSize (Integer), usedHeapSize (Integer), heapSizeLimit (Integer), mallocedMemory (Integer), peakMallocedMemory (Integer), and doesZapGarbage (boolean). All statistics are reported in Kilobytes.

process.getCPUUsage() method

process.getCPUUsage() returns a CPUUsage structure.

process.getCreationTime() method

process.getCreationTime() returns number | null. It indicates the creation time of the application as the number of milliseconds since epoch, or null if the information is unavailable.

process.crash() method

process.crash() causes the main thread of the current process to crash.

process.hang() method

process.hang() causes the main thread of the current process to hang.

serviceWorker.startTask() method

Initiates a task to keep the service worker alive until ended. Returns an Object with an 'end' Function property. The 'end' method must be called when the task has ended; if never called, the service won't terminate while otherwise idle. This method is experimental.

serviceWorker.isDestroyed() method

Returns a boolean indicating whether the service worker has been destroyed. This method is experimental.

serviceWorker.send() method

Sends an asynchronous message to the service worker process via a channel with optional arguments. Parameters: channel (string), ...args (any[]). Arguments are serialized using the Structured Clone Algorithm, so prototype chains are not included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. The service worker can handle the message using the ipcRenderer module. This method is experimental.

screen.getAllDisplays()

Returns Display[]. Returns an array of displays that are currently available.

screen.getDisplayNearestPoint()

Takes point Point as parameter. Returns Display. Returns the display nearest the specified point.

Give your agent this brain