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

api/main-process

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

Main process modules in Electron API

Main process modules include: app, autoUpdater, BaseWindow, BrowserWindow, contentTracing, desktopCapturer, dialog, globalShortcut, inAppPurchase, ImageView, ipcMain, Menu, MenuItem, MessageChannelMain, MessagePortMain, nativeTheme, net, netLog, Notification, powerMonitor, powerSaveBlocker, protocol, pushNotifications, safeStorage, screen, ServiceWorkerMain, session, ShareMenu, systemPreferences, TouchBar, Tray, utilityProcess, View, webContents, webFrameMain, and WebContentsView.

Keep Tray object from garbage collection

To prevent a Tray object from being garbage collected, store it in a persistent variable: const { app, Tray } = require('electron'); let tray = null; app.whenReady().then(() => { tray = new Tray('/path/to/icon.png'); tray.setTitle('hello world'); });

Set BrowserWindow background color to fix font rendering

To fix blurry font rendering, use the backgroundColor option when creating a BrowserWindow: const { BrowserWindow } = require('electron'); const win = new BrowserWindow({ backgroundColor: '#fff' });

Turn off Node.js integration in BrowserWindow

To disable Node.js integration in a BrowserWindow, set nodeIntegration: false in the webPreferences option when creating the window. This prevents Node.js symbols from being inserted into the DOM.

Tray object gets garbage collected

If a tray icon disappears after a few minutes, it is because the variable storing the tray object was garbage collected. To prevent this, store the tray in a module-level or persistent variable rather than a local scope variable, ensuring the object remains in memory for the lifetime of the application.

Blurry font rendering on LCD screens

If sub-pixel anti-aliasing is deactivated, fonts on LCD screens can look blurry. Sub-pixel anti-aliasing needs a non-transparent background of the layer containing the font glyphs. To fix this, set the backgroundColor option in the BrowserWindow constructor, for example backgroundColor: '#fff'. Setting the background only in CSS does not have the desired effect. The effect is visible primarily on LCD screens, and it is best to always set the background this way.

Utility process definition

The utility process is a child of the main process that allows running any untrusted services that cannot be run in the main process. Chromium uses this process to perform network I/O, audio/video processing, and device inputs. In Electron, you can create this process using the UtilityProcess API.

Main process definition and role

The main process, commonly a file named main.js, is the entry point to every Electron app. It controls the life of the app from open to close. It also manages native elements such as the Menu, Menu Bar, Dock, and Tray. The main process is responsible for creating each new renderer process in the app. The full Node API is built in.

Main process entry point configuration

Every app's main process file is specified in the main property in package.json. This is how electron . knows what file to execute at startup.

showMessageBox parameters and options

dialog.showMessageBox([window, ]options) accepts: window (BaseWindow, optional), options object with: message (string, required), type (string, optional - values: none, info, error, question, warning; on Windows question displays same icon as info unless icon option set; on macOS warning and error display same icon), buttons (string[] array, optional - on Windows empty array results in one OK button), defaultId (Integer, optional), signal (AbortSignal, optional), title (string, optional), detail (string, optional), checkboxLabel (string, optional), checkboxChecked (boolean, optional, defaults to false), icon (NativeImage or string, optional), textWidth (Integer, optional, macOS only), cancelId (Integer, optional - defaults to first cancel/no button or 0), noLink (boolean, optional - on Windows, prevents modern style command links), normalizeAccessKeys (boolean, optional, defaults to false - converts & for keyboard shortcuts across platforms). Returns Promise<Object> with: response (number - index of clicked button), checkboxChecked (boolean - state of checkbox if checkboxLabel set, else false).

showCertificateTrustDialog parameters

dialog.showCertificateTrustDialog([window, ]options) accepts: window (BaseWindow, optional), options object with: certificate (Certificate, required - the certificate to trust/import), message (string, required). Returns Promise<void> that resolves when the certificate trust dialog is shown.

showMessageBoxSync parameters and options

dialog.showMessageBoxSync([window, ]options) accepts: window (BaseWindow, optional), options object with: message (string, required), type (string, optional - values: none, info, error, question, warning; on Windows question displays same icon as info unless icon option set; on macOS warning and error display same icon), buttons (string[] array, optional - on Windows empty array results in one OK button), defaultId (Integer, optional), title (string, optional), detail (string, optional), icon (NativeImage or string, optional), textWidth (Integer, optional, macOS only), cancelId (Integer, optional - defaults to first cancel/no button or 0), noLink (boolean, optional - on Windows, prevents modern style command links), normalizeAccessKeys (boolean, optional, defaults to false - converts & for keyboard shortcuts across platforms). Returns Integer (index of clicked button).

File extension format in filters array

In the filters array for file dialogs, the extensions array should contain extensions without wildcards or dots. For example, use 'png' not '.png' or '*.png'. Use the '*' wildcard to show all files; no other wildcard is supported.

showErrorBox parameters

dialog.showErrorBox(title, content) accepts: title (string), content (string). Displays a modal dialog showing an error message. This API can be safely called before the app 'ready' event and is typically used for early-stage startup errors. On Linux, if called before the ready event, the message is emitted to stderr and no GUI dialog appears.

showCertificateTrustDialog macOS and Windows only

dialog.showCertificateTrustDialog([window, ]options) is available on macOS and Windows only. On macOS, displays a modal dialog with certificate information and trust/import option. On Windows, the message argument is not used as the OS provides its own confirmation dialog, and the window argument is ignored as the dialog cannot be made modal.

securityScopedBookmarks creates blank file if enabled

When using showSaveDialog with securityScopedBookmarks enabled on macOS/mas, if the file doesn't already exist, a blank file will be created at the chosen path.

showSaveDialog parameters and options

dialog.showSaveDialog([window, ]options) accepts: window (BaseWindow, optional), options object with: title (string, optional), defaultPath (string, optional - defaults to Downloads or home directory), buttonLabel (string, optional), filters (FileFilter[] array, optional), message (string, optional, macOS only), nameFieldLabel (string, optional, macOS only), showsTagField (boolean, optional, macOS only, defaults to true), properties (string[] array, optional - values: showHiddenFiles [macOS/Windows], createDirectory [macOS], treatPackageAsDirectory [macOS], showOverwriteConfirmation [Linux], dontAddToRecent [Windows]), securityScopedBookmarks (boolean, optional, macOS/mas only - if enabled and file doesn't exist, a blank file will be created at chosen path). Returns Promise<Object> with: canceled (boolean), filePath (string, empty if cancelled), bookmark (string, optional, macOS/mas only).

Dialog sheets on macOS

On macOS, dialogs are presented as sheets attached to a window if a BaseWindow reference is provided in the window parameter, or as modals if no window is provided. Call BaseWindow.getCurrentWindow().setSheetOffset(offset) to change the offset from the window frame where sheets are attached.

Example file filters

{ filters: [ { name: 'Images', extensions: ['jpg', 'png', 'gif'] }, { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] }, { name: 'Custom File Type', extensions: ['as'] }, { name: 'All Files', extensions: ['*'] } ] }

Example showing multiple file selections

const { dialog } = require('electron') console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))

Example open dialog with then/catch

dialog.showOpenDialog(mainWindow, { properties: ['openFile', 'openDirectory'] }).then(result => { console.log(result.canceled) console.log(result.filePaths) }).catch(err => { console.log(err) })

showOpenDialog parameters and options

dialog.showOpenDialog([window, ]options) accepts: window (BaseWindow, optional), options object with: title (string, optional), defaultPath (string, optional - defaults to Downloads or home directory), buttonLabel (string, optional), filters (FileFilter[] array, optional), properties (string[] array, optional - values: openFile, openDirectory, multiSelections, showHiddenFiles [macOS/Windows], createDirectory [macOS], promptToCreate [Windows], noResolveAliases [macOS], treatPackageAsDirectory [macOS], dontAddToRecent [Windows]), message (string, optional, macOS only), securityScopedBookmarks (boolean, optional, macOS/mas only). Returns Promise<Object> with: canceled (boolean), filePaths (string[] array), bookmarks (string[] array, optional, macOS/mas only).

Bookmarks array return values for security scoped bookmarks

The bookmarks field returned from showOpenDialog and showSaveDialog is an array of Base64 encoded strings containing security scoped bookmark data. Return values depend on build type and securityScopedBookmarks option: macOS mas with securityScopedBookmarks=true on success returns array like ['LONGBOOKMARKSTRING'], on error returns [''] (array of empty string); macOS mas with securityScopedBookmarks=false returns [] (empty array); non-mas builds always return [] (empty array) regardless of securityScopedBookmarks setting.

Async showSaveDialog recommended on macOS

On macOS, using the asynchronous version of showSaveDialog is recommended to avoid issues when expanding and collapsing the dialog.

defaultPath not supported with portal file chooser on Linux

On Linux, defaultPath is not supported when using portal file chooser dialogs unless the portal backend is version 4 or higher. Use the --xdg-portal-required-version command-line switch to force gtk or kde dialogs.

openFile and openDirectory properties mutually exclusive on Windows and Linux

On Windows and Linux, an open dialog cannot be both a file selector and a directory selector. If you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown instead.

dock.setMenu() method

The dock.setMenu() method takes a Menu parameter and sets the application's dock menu on macOS.

dock.show() method

The dock.show() method shows the dock icon on macOS and returns a Promise that resolves when the dock icon is shown.

dock.getMenu() method

The dock.getMenu() method returns the application's dock menu on macOS. It returns a Menu object or null if no dock menu is set.

dock.hide() method

The dock.hide() method hides the dock icon on macOS. There is a known issue where calling dock.hide() within one second of a previous call will have no effect. As a workaround, ensure at least one second has elapsed between calls, for example by deferring with a setTimeout of 1100ms or more after a previous call.

dock.isVisible() method

The dock.isVisible() method returns a boolean indicating whether the dock icon is visible on macOS.

dock.getBadge() method

The dock.getBadge() method returns a string containing the badge string of the dock on macOS.

dock.setBadge() method

The dock.setBadge() method takes a text string parameter and sets the string to be displayed in the dock's badging area on macOS. The application must have permission to display notifications for this method to work.

dock.downloadFinished() method

The dock.downloadFinished() method takes a filePath string parameter and bounces the Downloads stack if the file path is inside the Downloads folder on macOS.

dock.cancelBounce() method

The dock.cancelBounce() method takes an id Integer parameter and cancels the bounce identified by that ID on macOS.

dock.bounce() method

The dock.bounce() method makes the dock icon bounce on macOS. The type parameter can be 'critical' or 'informational', with 'informational' as the default. When 'critical' is passed, the dock icon bounces until the application becomes active or the request is canceled. When 'informational' is passed, the dock icon bounces for one second but the request remains active until the application becomes active or the request is canceled. The method returns an Integer ID representing the request. This method can only be used while the app is not focused; when the app is focused it returns -1.

dock.setIcon() method

The dock.setIcon() method takes an image parameter that can be either a NativeImage or a string, and sets the image associated with the dock icon on macOS.

extensions.getAllExtensions requires app ready event

The extensions.getAllExtensions API cannot be called before the ready event of the app module is emitted.

What does extensions module provide

The extensions module provides the Extensions class which allows loading and interacting with Chrome extensions. It is accessed via the extensions property of a Session object. The Extensions class provides methods to load extensions (loadExtension), remove extensions (removeExtension), query loaded extensions (getExtension, getAllExtensions), and emit events when extensions are loaded, unloaded, or ready. Extensions run only in the main process.

extension-ready event fires when extension background page is initialized

The 'extension-ready' event is emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page. The event returns the event object and an Extension object.

extension-unloaded event fires when extension is removed

The 'extension-unloaded' event is emitted after an extension is unloaded. This occurs when Session.removeExtension is called. The event returns the event object and an Extension object.

extension-loaded event fires when extension is added to enabled set

The 'extension-loaded' event is emitted after an extension is loaded and added to the enabled set of extensions. This occurs when extensions are loaded from extensions.loadExtension, or when extensions are reloaded from a crash, or when the extension requests a reload via chrome.runtime.reload(). The event returns the event object and an Extension object.

extensions.getAllExtensions method signature

The extensions.getAllExtensions method takes no parameters and returns Extension[], a list of all loaded extensions.

extensions.getExtension method signature

The extensions.getExtension method takes an extensionId string parameter and returns Extension | null. It returns the loaded extension with the given ID, or null if not found.

extensions.removeExtension requires app ready event

The extensions.removeExtension API cannot be called before the ready event of the app module is emitted.

extensions.removeExtension method signature

The extensions.removeExtension method takes an extensionId string parameter and unloads the corresponding extension.

extensions.loadExtension requires persistent sessions

Loading extensions into in-memory (non-persistent) sessions is not supported and will throw an error.

extensions.loadExtension does not persist extensions

In previous versions of Electron, loaded extensions would be remembered for future runs of the application. This is no longer the case: loadExtension must be called on every boot of the app if you want the extension to be loaded.

extensions.loadExtension does not support packed extensions

The loadExtension API does not support loading packed (.crx) extensions. Only unpacked extensions can be loaded.

extensions.loadExtension method signature and parameters

The extensions.loadExtension method takes a path string (path to a directory containing an unpacked Chrome extension) and optional options object. The options object has a single property: allowFileAccess (boolean, defaults to false), which determines whether the extension can read local files over file:// protocol and inject content scripts into file:// pages. The method returns Promise<Extension> and resolves when the extension is loaded.

globalShortcut example with register and isRegistered

const { app, globalShortcut } = require('electron') app.commandLine.appendSwitch('enable-features', 'GlobalShortcutsPortal') app.whenReady().then(() => { const ret = globalShortcut.register('CommandOrControl+X', () => { console.log('CommandOrControl+X is pressed') }) if (!ret) { console.log('registration failed') } console.log(globalShortcut.isRegistered('CommandOrControl+X')) }) app.on('will-quit', () => { globalShortcut.unregister('CommandOrControl+X') globalShortcut.unregisterAll() }) This example shows how to register a global shortcut, check if it is registered, and unregister it.

globalShortcut.setSuspended method

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 you want to temporarily allow the user to press key combinations without the application intercepting them, for example while displaying a UI to rebind shortcuts.

globalShortcut.isRegistered method

globalShortcut.isRegistered(accelerator) returns a boolean indicating whether the application has registered the specified accelerator. If the accelerator is already taken by other applications, this call will still return false.

globalShortcut.registerAll macOS 10.14 accessibility requirement

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

globalShortcut.registerAll method

globalShortcut.registerAll(accelerators, callback) registers a global shortcut of all accelerator items 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, this call will silently fail.

globalShortcut Wayland support with GlobalShortcutsPortal

It is possible to use Chromium's GlobalShortcutsPortal implementation, which allows apps to bind global shortcuts when running within a Wayland session. Enable this with app.commandLine.appendSwitch('enable-features', 'GlobalShortcutsPortal').

globalShortcut module overview

The globalShortcut module can register and unregister global keyboard shortcuts with the operating system to customize operations for various shortcuts. The shortcut is global and works even if the app does not have keyboard focus. This module cannot be used before the ready event of the app module is emitted.

globalShortcut.isSuspended method

globalShortcut.isSuspended() returns a boolean indicating whether global shortcut handling is currently suspended.

globalShortcut.unregisterAll method

globalShortcut.unregisterAll() unregisters all global shortcuts.

globalShortcut.unregister method

globalShortcut.unregister(accelerator) unregisters the global shortcut of the specified accelerator.

Give your agent this brain