# Electron > Control your application's event lifecycle. --- # app > Control your application's event lifecycle. Process: [Main](../glossary.md#main-process) The following example shows how to quit the application when the last window is closed: ```js const { app } = require('electron') app.on('window-all-closed', () => { app.quit() }) ``` ## Events The `app` object emits the following events: ### Event: 'will-finish-launching' Emitted when the application has finished basic startup. On Windows and Linux, the `will-finish-launching` event is the same as the `ready` event; on macOS, this event represents the `applicationWillFinishLaunching` notification of `NSApplication`. In most cases, you should do everything in the `ready` event handler. ### Event: 'ready' Returns: * `event` Event * `launchInfo` Record\ | [NotificationResponse](structures/notification-response.md) _macOS_ Emitted once, when Electron has finished initializing. On macOS, `launchInfo` holds the `userInfo` of the [`NSUserNotification`](https://developer.apple.com/documentation/foundation/nsusernotification) or information from [`UNNotificationResponse`](https://developer.apple.com/documentation/usernotifications/unnotificationresponse) that was used to open the application, if it was launched from Notification Center. You can also call `app.isReady()` to check if this event has already fired and `app.whenReady()` to get a Promise that is fulfilled when Electron is initialized. > [!NOTE] > The `ready` event is only fired after the main process has finished running the first > tick of the event loop. If an Electron API needs to be called before the `ready` event, ensure > that it is called synchronously in the top-level context of the main process. ### Event: 'window-all-closed' Emitted when all windows have been closed. If you do not subscribe to this event and all windows are closed, the default behavior is to quit the app; however, if you subscribe, you control whether the app quits or not. If the user pressed `Cmd + Q`, or the developer called `app.quit()`, Electron will first try to close all the windows and then emit the `will-quit` event, and in this case the `window-all-closed` event would not be emitted. ### Event: 'before-quit' Returns: * `event` Event Emitted before the application starts closing its windows. Calling `event.preventDefault()` will prevent the default behavior, which is terminating the application. > [!NOTE] > If application quit was initiated by `autoUpdater.quitAndInstall()`, > then `before-quit` is emitted _after_ emitting `close` event on all windows and > closing them. > [!NOTE] > On Windows, this event will not be emitted if the app is closed due > to a shutdown/restart of the system or a user logout. ### Event: 'will-quit' Returns: * `event` Event Emitted when all windows have been closed and the application will quit. Calling `event.preventDefault()` will prevent the default behavior, which is terminating the application. See the description of the `window-all-closed` event for the differences between the `will-quit` and `window-all-closed` events. > [!NOTE] > On Windows, this event will not be emitted if the app is closed due > to a shutdown/restart of the system or a user logout. ### Event: 'quit' Returns: * `event` Event * `exitCode` Integer Emitted when the application is quitting. > [!NOTE] > On Windows, this event will not be emitted if the app is closed due > to a shutdown/restart of the system or a user logout. ### Event: 'open-file' _macOS_ Returns: * `event` Event * `path` string Emitted when the user wants to open a file with the application. The `open-file` event is usually emitted when the application is already open and the OS wants to reuse the application to open the file. `open-file` is also emitted when a file is dropped onto the dock and the application is not yet running. Make sure to listen for the `open-file` event very early in your application startup to handle this case (even before the `ready` event is emitted). You should call `event.preventDefault()` if you want to handle this event. On Windows, you have to parse `process.argv` (in the main process) to get the filepath. ### Event: 'open-url' _macOS_ Returns: * `event` Event * `url` string Emitted when the user wants to open a URL with the application. Your application's `Info.plist` file must define the URL scheme within the `CFBundleURLTypes` key, and set `NSPrincipalClass` to `AtomApplication`. As with the `open-file` event, be sure to register a listener for the `open-url` event early in your application startup to detect if the application is being opened to handle a URL. If you register the listener in response to a `ready` event, you'll miss URLs that trigger the launch of your application. ### Event: 'activate' _macOS_ Returns: * `event` Event * `hasVisibleWindows` boolean Emitted when the application is activated. Various actions can trigger this event, such as launching the application for the first time, attempting to re-launch the application when it's already running, or clicking on the application's dock or taskbar icon. ### Event: 'did-become-active' _macOS_ Returns: * `event` Event Emitted when the application becomes active. This differs from the `activate` event in that `did-become-active` is emitted every time the app becomes active, not only when Dock icon is clicked or application is re-launched. It is also emitted when a user switches to the app via the macOS App Switcher. ### Event: 'did-resign-active' _macOS_ Returns: * `event` Event Emitted when the app is no longer active and doesn’t have focus. This can be triggered, for example, by clicking on another application or by using the macOS App Switcher to switch to another application. ### Event: 'continue-activity' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity on another device. * `details` Object * `webpageURL` string (optional) - A string identifying the URL of the webpage accessed by the activity on another device, if available. Emitted during [Handoff][handoff] when an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this event. A user activity can be continued only in an app that has the same developer Team ID as the activity's source app and that supports the activity's type. Supported activity types are specified in the app's `Info.plist` under the `NSUserActivityTypes` key. ### Event: 'will-continue-activity' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. Emitted during [Handoff][handoff] before an activity from a different device wants to be resumed. You should call `event.preventDefault()` if you want to handle this event. ### Event: 'continue-activity-error' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `error` string - A string with the error's localized description. Emitted during [Handoff][handoff] when an activity from a different device fails to be resumed. ### Event: 'activity-was-continued' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity. Emitted during [Handoff][handoff] after an activity from this device was successfully resumed on another one. ### Event: 'update-activity-state' _macOS_ Returns: * `event` Event * `type` string - A string identifying the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` unknown - Contains app-specific state stored by the activity. Emitted when [Handoff][handoff] is about to be resumed on another device. If you need to update the state to be transferred, you should call `event.preventDefault()` immediately, construct a new `userInfo` dictionary and call `app.updateCurrentActivity()` in a timely manner. Otherwise, the operation will fail and `continue-activity-error` will be called. ### Event: 'new-window-for-tab' _macOS_ Returns: * `event` Event Emitted when the user clicks the native macOS new tab button. The new tab button is only visible if the current `BrowserWindow` has a `tabbingIdentifier` ### Event: 'browser-window-blur' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a [browserWindow](browser-window.md) gets blurred. ### Event: 'browser-window-focus' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a [browserWindow](browser-window.md) gets focused. ### Event: 'browser-window-created' Returns: * `event` Event * `window` [BrowserWindow](browser-window.md) Emitted when a new [browserWindow](browser-window.md) is created. ### Event: 'web-contents-created' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) Emitted when a new [webContents](web-contents.md) is created. ### Event: 'certificate-error' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `url` string * `error` string - The error code * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Whether to consider the certificate as trusted * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`, to trust the certificate you should prevent the default behavior with `event.preventDefault()` and call `callback(true)`. ```js const { app } = require('electron') app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { if (url === 'https://github.com') { // Verification logic. event.preventDefault() callback(true) } else { callback(false) } }) ``` ### Event: 'select-client-certificate' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) (optional) Emitted when a client certificate is requested. The `url` corresponds to the navigation entry requesting the client certificate and `callback` can be called with an entry filtered from the list. Using `event.preventDefault()` prevents the application from using the first certificate from the store. ```js const { app } = require('electron') app.on('select-client-certificate', (event, webContents, url, list, callback) => { event.preventDefault() callback(list[0]) }) ``` ### Event: 'login' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) (optional) * `authenticationResponseDetails` Object * `url` URL * `pid` number * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` or [Utility process](../glossary.md#utility-process) wants to do basic auth. The default behavior is to cancel all authentications. To override this you should prevent the default behavior with `event.preventDefault()` and call `callback(username, password)` with the credentials. ```js const { app } = require('electron') app.on('login', (event, webContents, details, authInfo, callback) => { event.preventDefault() callback('username', 'secret') }) ``` If `callback` is called without a username or password, the authentication request will be cancelled and the authentication error will be returned to the page. ### Event: 'gpu-info-update' Emitted whenever there is a GPU info update. ### Event: 'render-process-gone' Returns: * `event` Event * `webContents` [WebContents](web-contents.md) * `details` [RenderProcessGoneDetails](structures/render-process-gone-details.md) Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. ### Event: 'child-process-gone' Returns: * `event` Event * `details` Object * `type` string - Process type. One of the following values: * `Utility` * `Zygote` * `Sandbox helper` * `GPU` * `Pepper Plugin` * `Pepper Plugin Broker` * `Unknown` * `reason` string - The reason the child process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `memory-eviction` - Process proactively terminated to prevent a future out-of-memory (OOM) situation * `exitCode` number - The exit code for the process (e.g. status from waitpid if on POSIX, from GetExitCodeProcess on Windows). * `serviceName` string (optional) - The non-localized name of the process. * `name` string (optional) - The name of the process. Examples for utility: `Audio Service`, `Content Decryption Module Service`, `Network Service`, `Video Capture`, etc. Emitted when the child process unexpectedly disappears. This is normally because it was crashed or killed. It does not include renderer processes. ### Event: 'accessibility-support-changed' _macOS_ _Windows_ Returns: * `event` Event * `accessibilitySupportEnabled` boolean - `true` when Chrome's accessibility support is enabled, `false` otherwise. Emitted when Chrome's accessibility support changes. This event fires when assistive technologies, such as screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details. ### Event: 'session-created' Returns: * `session` [Session](session.md) Emitted when Electron has created a new `session`. ```js const { app } = require('electron') app.on('session-created', (session) => { console.log(session) }) ``` ### Event: 'second-instance' Returns: * `event` Event * `argv` string[] - An array of the second instance's command line arguments * `workingDirectory` string - The second instance's working directory * `additionalData` unknown - A JSON object of additional data passed from the second instance This event will be emitted inside the primary instance of your application when a second instance has been executed and calls `app.requestSingleInstanceLock()`. `argv` is an Array of the second instance's command line arguments, and `workingDirectory` is its current working directory. Usually applications respond to this by making their primary window focused and non-minimized. > [!NOTE] > `argv` will not be exactly the same list of arguments as those passed > to the second instance. The order might change and additional arguments might be appended. > If you need to maintain the exact same arguments, it's advised to use `additionalData` instead. > [!NOTE] > If the second instance is started by a different user than the first, the `argv` array will not include the arguments. This event is guaranteed to be emitted after the `ready` event of `app` gets emitted. > [!NOTE] > Extra command line arguments might be added by Chromium, > such as `--original-process-start-time`. ## Methods The `app` object has the following methods: > [!NOTE] > Some methods are only available on specific operating systems and are > labeled as such. ### `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. ### `app.exit([exitCode])` * `exitCode` Integer (optional) Exits immediately with `exitCode`. `exitCode` 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. ### `app.relaunch([options])` * `options` Object (optional) * `args` string[] (optional) * `execPath` string (optional) Relaunches the app when the current instance exits. 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. An example of restarting the current instance immediately and adding a new command line argument to the new instance: ```js const { app } = require('electron') app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) }) app.exit(0) ``` ### `app.isReady()` Returns `boolean` - `true` if Electron has finished initializing, `false` otherwise. See also `app.whenReady()`. ### `app.whenReady()` Returns `Promise` - 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. ### `app.focus([options])` * `options` Object (optional) * `steal` boolean _macOS_ - 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. ### `app.hide()` _macOS_ Hides all application windows without minimizing them. ### `app.isHidden()` _macOS_ Returns `boolean` - `true` if the application—including all of its windows—is hidden (e.g. with `Command-H`), `false` otherwise. ### `app.show()` _macOS_ Shows application windows after they were hidden. Does not automatically focus them. ### `app.setAppLogsPath([path])` * `path` string (optional) - A custom path for your logs. Must be absolute. Sets or creates a directory your app's logs which can then be manipulated with `app.getPath()` or `app.setPath(pathName, newPath)`. 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_. ### `app.getAppPath()` Returns `string` - The current application directory. ### `app.getPath(name)` * `name` string - You can request the following paths by the name: * `home` User's home directory. * `appData` Per-user application data directory, which by default points to: * `%APPDATA%` on Windows * `$XDG_CONFIG_HOME` or `~/.config` on Linux * `~/Library/Application Support` on macOS * `assets` The directory where app assets such as `resources.pak` are stored. By default this is the same as the folder containing the `exe` path. Available on Windows and Linux only. * `userData` The directory for storing your app's configuration files, which by default is the `appData` directory appended with your app's name. By convention files storing user data should be written to this directory, and it is not recommended to write large files here because some environments may backup this directory to cloud storage. * `sessionData` The directory for storing data generated by `Session`, such as localStorage, cookies, disk cache, downloaded dictionaries, network state, devtools files. By default this points to `userData`. Chromium may write very large disk cache here, so if your app does not rely on browser storage like localStorage or cookies to save user data, it is recommended to set this directory to other locations to avoid polluting the `userData` directory. * `temp` Temporary directory. * `exe` The current executable file. * `module` The location of the Chromium module. By default this is synonymous with `exe`. * `desktop` The current user's Desktop directory. * `documents` Directory for a user's "My Documents". * `downloads` Directory for a user's downloads. * `music` Directory for a user's music. * `pictures` Directory for a user's pictures. * `videos` Directory for a user's videos. * `recent` Directory for the user's recent files (Windows only). * `logs` Directory for your app's log folder. * `crashDumps` Directory where crash dumps are stored. Returns `string` - A path to a special directory or file associated with `name`. On failure, an `Error` is thrown. If `app.getPath('logs')` is called without called `app.setAppLogsPath()` being called first, a default log directory will be created equivalent to calling `app.setAppLogsPath()` without a `path` parameter. ### `app.getFileIcon(path[, options])` * `path` string * `options` Object (optional) * `size` string * `small` - 16x16 * `normal` - 32x32 * `large` - 48x48 on _Linux_, 32x32 on _Windows_, unsupported on _macOS_. Returns `Promise` - fulfilled with the app's icon, which is a [NativeImage](native-image.md). Fetches a path's associated icon. On _Windows_, there a 2 kinds of icons: * Icons associated with certain file extensions, like `.mp3`, `.png`, etc. * Icons inside the file itself, like `.exe`, `.dll`, `.ico`. On _Linux_ and _macOS_, icons depend on the application associated with file mime type. ### `app.setPath(name, path)` * `name` string * `path` string Overrides the `path` to a special directory or file associated with `name`. 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. ### `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. ### `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. ### `app.setName(name)` * `name` string Overrides the current application's name. > [!NOTE] > This function overrides the name used internally by Electron; it does not affect the name that the OS uses. ### `app.getLocale()` Returns `string` - The current application locale, fetched using Chromium's `l10n_util` library. Possible return values are documented [here](https://source.chromium.org/chromium/chromium/src/+/main:ui/base/l10n/l10n_util.cc). To set the locale, you'll want to use a command line switch at app startup, which may be found [here](command-line-switches.md). > [!NOTE] > When distributing your packaged app, you have to also ship the > `locales` folder. > [!NOTE] > This API must be called after the `ready` event is emitted. > [!NOTE] > To see example return values of this API compared to other locale and language APIs, see [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages). ### `app.getLocaleCountryCode()` Returns `string` - User operating system's locale two-letter [ISO 3166](https://www.iso.org/iso-3166-country-codes.html) country code. The value is taken from native OS APIs. > [!NOTE] > When unable to detect locale country code, it returns empty string. ### `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()`](#appgetpreferredsystemlanguages). Different operating systems also 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. > [!NOTE] > This API must be called after the `ready` event is emitted. > [!NOTE] > To see example return values of this API compared to other locale and language APIs, see [`app.getPreferredSystemLanguages()`](#appgetpreferredsystemlanguages). ### `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. Here are some examples of return values of the various language and locale APIs with different configurations: 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): ```js 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): ```js 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. As can be seen with the example above, 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: the user doesn't need to have Finnish as a preferred language to use Finland as the region,and the country code `FI` is used as the country code for preferred system languages that do not have associated countries in the language name. ### `app.addRecentDocument(path)` _macOS_ _Windows_ * `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. ### `app.clearRecentDocuments()` _macOS_ _Windows_ Clears the recent documents list. ### `app.getRecentDocuments()` _macOS_ _Windows_ Returns `string[]` - An array containing documents in the most recent documents list. ```js 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'} ``` ### `app.setAsDefaultProtocolClient(protocol[, path, args])` * `protocol` string - The name of your protocol, without `://`. For example, if you want your app to handle `electron://` links, call this method with `electron` as the parameter. * `path` string (optional) _Windows_ - The path to the Electron executable. Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Arguments passed to the executable. Defaults to an 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. > [!NOTE] > 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-forge], > [Electron Packager][electron-packager], or by editing `info.plist` with a text > editor. Please refer to [Apple's documentation][CFBundleURLTypes] for details. > [!NOTE] > 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](https://learn.microsoft.com/en-us/uwp/schemas/appxpackage/uapmanifestschema/element-uap-protocol). The API uses the Windows Registry and `LSSetDefaultHandlerForURLScheme` internally. ### `app.removeAsDefaultProtocolClient(protocol[, path, args])` _macOS_ _Windows_ * `protocol` string - The name of your protocol, without `://`. * `path` string (optional) _Windows_ - Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Defaults to an empty array Returns `boolean` - Whether the call succeeded. This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler. ### `app.isDefaultProtocolClient(protocol[, path, args])` * `protocol` string - The name of your protocol, without `://`. * `path` string (optional) _Windows_ - Defaults to `process.execPath` * `args` string[] (optional) _Windows_ - Defaults to an empty array Returns `boolean` - Whether the current executable is the default handler for a protocol (aka URI scheme). > [!NOTE] > 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. Please refer to > [Apple's documentation][LSCopyDefaultHandlerForURLScheme] for details. The API uses the Windows Registry and `LSCopyDefaultHandlerForURLScheme` internally. ### `app.getApplicationNameForProtocol(url)` * `url` string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including `://` at a 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. ### `app.getApplicationInfoForProtocol(url)` _macOS_ _Windows_ * `url` string - a URL with the protocol name to check. Unlike the other methods in this family, this accepts an entire URL, including `://` at a minimum (e.g. `https://`). Returns `Promise` - Resolve with an object containing the following: * `icon` NativeImage - the display icon of the app handling the protocol. * `path` string - installation path of the app handling the protocol. * `name` string - display name of the app handling the 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. ### `app.setUserTasks(tasks)` _Windows_ * `tasks` [Task[]](structures/task.md) - Array of `Task` objects Adds `tasks` to the [Tasks][tasks] category of the Jump List on Windows. `tasks` is an array of [`Task`](structures/task.md) objects. Returns `boolean` - Whether the call succeeded. > [!NOTE] > If you'd like to customize the Jump List even more use > `app.setJumpList(categories)` instead. ### `app.getJumpListSettings()` _Windows_ Returns `Object`: * `minItems` Integer - The minimum number of items that will be shown in the Jump List (for a more detailed description of this value see the [MSDN docs][JumpListBeginListMSDN]). * `removedItems` [JumpListItem[]](structures/jump-list-item.md) - Array of `JumpListItem` objects that correspond to items that the user has explicitly removed from custom categories in the Jump List. These items must not be re-added to the Jump List in the **next** call to `app.setJumpList()`, Windows will not display any custom category that contains any of the removed items. ### `app.setJumpList(categories)` _Windows_ * `categories` [JumpListCategory[]](structures/jump-list-category.md) | `null` - Array of `JumpListCategory` objects. Returns `string` Sets or removes a custom Jump List for the application, and returns one of the following strings: * `ok` - Nothing went wrong. * `error` - One or more errors occurred, enable runtime logging to figure out the likely cause. * `invalidSeparatorError` - An attempt was made to add a separator to a custom category in the Jump List. Separators are only allowed in the standard `Tasks` category. * `fileTypeRegistrationError` - An attempt was made to add a file link to the Jump List for a file type the app isn't registered to handle. * `customCategoryAccessDeniedError` - Custom categories can't be added to the Jump List 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). > [!NOTE] > If a `JumpListCategory` object has neither the `type` nor the `name` > property set then its `type` is assumed to be `tasks`. If the `name` property is set but the `type` property is omitted then the `type` is assumed to be `custom`. > [!NOTE] > Users can remove items from custom categories, and Windows will not > allow a removed item to be added back into a custom category until **after** > the next successful call to `app.setJumpList(categories)`. Any attempt to > re-add a removed item to a custom category earlier than that will result in the > entire custom category being omitted from the Jump List. The list of removed > items can be obtained using `app.getJumpListSettings()`. > [!NOTE] > The maximum length of a Jump List item's `description` property is > 260 characters. Beyond this limit, the item will not be added to the Jump > List, nor will it be displayed. Here's a very simple example of creating a custom Jump List: ```js 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' } ] } ]) ``` ### `app.requestSingleInstanceLock([additionalData])` * `additionalData` Record\ (optional) - A JSON object containing additional data to send to the first instance. Returns `boolean` The return value of this method 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. I.e. 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. An example of activating the window of primary instance when a second instance starts: ```js 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') }) } ``` ### `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()` ### `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. ### `app.setUserActivity(type, userInfo[, webpageURL])` _macOS_ * `type` string - Uniquely identifies the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `userInfo` any - App-specific state to store for use by another device. * `webpageURL` string (optional) - The webpage to load in a browser if no suitable app is installed on the resuming device. The scheme must be `http` or `https`. Creates an `NSUserActivity` and sets it as the current activity. The activity is eligible for [Handoff][handoff] to another device afterward. ### `app.getCurrentActivityType()` _macOS_ Returns `string` - The type of the currently running activity. ### `app.invalidateCurrentActivity()` _macOS_ Invalidates the current [Handoff][handoff] user activity. ### `app.resignCurrentActivity()` _macOS_ Marks the current [Handoff][handoff] user activity as inactive without invalidating it. ### `app.updateCurrentActivity(type, userInfo)` _macOS_ * `type` string - Uniquely identifies the activity. Maps to [`NSUserActivity.activityType`][activity-type]. * `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. ### `app.setAppUserModelId(id)` _Windows_ * `id` string Changes the [Application User Model ID][app-user-model-id] to `id`. ### `app.setActivationPolicy(policy)` _macOS_ * `policy` string - Can be 'regular', 'accessory', or 'prohibited'. Sets the activation policy for a given app. Activation policy types: * 'regular' - The application is an ordinary app that appears in the Dock and may have a user interface. * 'accessory' - The application doesn’t appear in the Dock and doesn’t have a menu bar, but it may be activated programmatically or by clicking on one of its windows. * 'prohibited' - The application doesn’t appear in the Dock and may not create windows or be activated. ### `app.importCertificate(options, callback)` _Linux_ * `options` Object * `certificate` string - Path for the pkcs12 file. * `password` string - Passphrase for the certificate. * `callback` Function * `result` Integer - Result of import. Imports the certificate in pkcs12 format into the platform certificate store. `callback` is called with the `result` of import operation, a value of `0` indicates success while any other value indicates failure according to Chromium [net_error_list](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h). ### `app.configureHostResolver(options)` * `options` Object * `enableBuiltInResolver` boolean (optional) - Whether the built-in host resolver is used in preference to getaddrinfo. When enabled, the built-in resolver will attempt to use the system's DNS settings to do DNS lookups itself. Enabled by default on macOS, disabled by default on Windows and Linux. * `enableHappyEyeballs` boolean (optional) - Whether the [Happy Eyeballs V3][happy-eyeballs-v3] algorithm should be used in creating network connections. When enabled, hostnames resolving to multiple IP addresses will be attempted in parallel to have a chance at establishing a connection more quickly. * `secureDnsMode` string (optional) - Can be 'off', 'automatic' or 'secure'. Configures the DNS-over-HTTP mode. When 'off', no DoH lookups will be performed. When 'automatic', DoH lookups will be performed first if DoH is available, and insecure DNS lookups will be performed as a fallback. When 'secure', only DoH lookups will be performed. Defaults to 'automatic'. * `secureDnsServers` string[] (optional) - A list of DNS-over-HTTP server templates. See [RFC8484 § 3][] for details on the template format. Most servers support the POST method; the template for such servers is simply a URI. Note that for [some DNS providers][doh-providers], the resolver will automatically upgrade to DoH unless DoH is explicitly disabled, even if there are no DoH servers provided in this list. * `enableAdditionalDnsQueryTypes` boolean (optional) - Controls whether additional DNS query types, e.g. HTTPS (DNS type 65) will be allowed besides the traditional A and AAAA queries when a request is being made via insecure DNS. Has no effect on Secure DNS which always allows additional types. Defaults to true. Configures host resolution (DNS and DNS-over-HTTPS). By default, the following resolvers will be used, in order: 1. DNS-over-HTTPS, if the [DNS provider supports it][doh-providers], then 2. the built-in resolver (enabled on macOS only by default), then 3. the system's resolver (e.g. `getaddrinfo`). This can be configured to either restrict usage of non-encrypted DNS (`secureDnsMode: "secure"`), or disable DNS-over-HTTPS (`secureDnsMode: "off"`). It is also possible to enable or disable the built-in resolver. To disable insecure DNS, you can specify a `secureDnsMode` of `"secure"`. If you do so, you should make sure to provide a list of DNS-over-HTTPS servers to use, in case the user's DNS configuration does not include a provider that supports DoH. ```js const { app } = require('electron') app.whenReady().then(() => { app.configureHostResolver({ secureDnsMode: 'secure', secureDnsServers: [ 'https://cloudflare-dns.com/dns-query' ] }) }) ``` This API must be called after the `ready` event is emitted. [doh-providers]: https://source.chromium.org/chromium/chromium/src/+/main:net/dns/public/doh_provider_entry.cc;l=31?q=%22DohProviderEntry::GetList()%22&ss=chromium%2Fchromium%2Fsrc [RFC8484 § 3]: https://datatracker.ietf.org/doc/html/rfc8484#section-3 ### `app.disableHardwareAcceleration()` Disables hardware acceleration for current app. This method can only be called before app is ready. ### `app.isHardwareAccelerationEnabled()` Returns `boolean` - whether hardware acceleration is currently enabled. > [!NOTE] > This information is only usable after the `gpu-info-update` event is emitted. ### `app.disableDomainBlockingFor3DAPIs()` By default, Chromium disables 3D APIs (e.g. WebGL) until restart on a per domain basis if the GPU processes crashes too frequently. This function disables that behavior. This method can only be called before app is ready. ### `app.getAppMetrics()` Returns [`ProcessMetric[]`](structures/process-metric.md): Array of `ProcessMetric` objects that correspond to memory and CPU usage statistics of all the processes associated with the app. ### `app.getGPUFeatureStatus()` Returns [`GPUFeatureStatus`](structures/gpu-feature-status.md) - The Graphics Feature Status from `chrome://gpu/`. > [!NOTE] > This information is only usable after the `gpu-info-update` event is emitted. ### `app.getGPUInfo(infoType)` * `infoType` string - Can be `basic` or `complete`. Returns `Promise` For `infoType` equal to `complete`: Promise is fulfilled with `Object` containing all the GPU Information as in [chromium's GPUInfo object](https://chromium.googlesource.com/chromium/src/+/4178e190e9da409b055e5dff469911ec6f6b716f/gpu/config/gpu_info.cc). This includes the version and driver information that's shown on `chrome://gpu` page. For `infoType` equal to `basic`: Promise is fulfilled with `Object` containing fewer attributes than when requested with `complete`. Here's an example of basic response: ```js { auxAttributes: { amdSwitchable: true, canSupportThreadedTextureMailbox: false, directComposition: false, directRendering: true, glResetNotificationStrategy: 0, inProcessGpu: true, initializationTime: 0, jpegDecodeAcceleratorSupported: false, optimus: false, passthroughCmdDecoder: false, sandboxed: false, softwareRendering: false, supportsOverlays: false, videoDecodeAcceleratorFlags: 0 }, gpuDevice: [{ active: true, deviceId: 26657, vendorId: 4098 }, { active: false, deviceId: 3366, vendorId: 32902 }], machineModelName: 'MacBookPro', machineModelVersion: '11.5' } ``` Using `basic` should be preferred if only basic information like `vendorId` or `deviceId` is needed. ### `app.setBadgeCount([count])` _Linux_ _macOS_ * `count` Integer (optional) - If a value is provided, set the badge to the provided value otherwise, on macOS, display a plain white dot (e.g. unknown number of notifications). On Linux, if a value is not provided the badge will not display. Returns `boolean` - Whether the call succeeded. Sets the counter badge for current app. Setting the count to `0` will hide the badge. On macOS, it shows on the dock icon. On Linux, it only works for Unity launcher. > [!NOTE] > Unity launcher requires a `.desktop` file to work. For more information, > please read the [Unity integration documentation][unity-requirement]. > [!NOTE] > On macOS, you need to ensure that your application has the permission > to display notifications for this method to work. ### `app.getBadgeCount()` _Linux_ _macOS_ Returns `Integer` - The current value displayed in the counter badge. ### `app.isUnityRunning()` _Linux_ Returns `boolean` - Whether the current desktop environment is Unity launcher. ### `app.getLoginItemSettings([options])` _macOS_ _Windows_ * `options` Object (optional) * `type` string (optional) _macOS_ - Can be one of `mainAppService`, `agentService`, `daemonService`, or `loginItemService`. Defaults to `mainAppService`. Only available on macOS 13 and up. See [app.setLoginItemSettings](app.md#appsetloginitemsettingssettings-macos-windows) for more information about each type. * `serviceName` string (optional) _macOS_ - The name of the service. Required if `type` is non-default. Only available on macOS 13 and up. * `path` string (optional) _Windows_ - The executable path to compare against. Defaults to `process.execPath`. * `args` string[] (optional) _Windows_ - The command-line arguments to compare against. Defaults to an empty array. If you provided `path` and `args` options to `app.setLoginItemSettings`, then you need to pass the same arguments here for `openAtLogin` to be set correctly. Returns `Object`: * `openAtLogin` boolean - `true` if the app is set to open at login. * `openAsHidden` boolean _macOS_ _Deprecated_ - `true` if the app is set to open as hidden at login. This does not work on macOS 13 and up. * `wasOpenedAtLogin` boolean _macOS_ - `true` if the app was opened at login automatically. * `wasOpenedAsHidden` boolean _macOS_ _Deprecated_ - `true` if the app was opened as a hidden login item. This indicates that the app should not open any windows at startup. This setting is not available on [MAS builds][mas-builds] or on macOS 13 and up. * `restoreState` boolean _macOS_ _Deprecated_ - `true` if the app was opened as a login item that should restore the state from the previous session. This indicates that the app should restore the windows that were open the last time the app was closed. This setting is not available on [MAS builds][mas-builds] or on macOS 13 and up. * `status` string _macOS_ - can be one of `not-registered`, `enabled`, `requires-approval`, or `not-found`. * `executableWillLaunchAtLogin` boolean _Windows_ - `true` if app is set to open at login and its run key is not deactivated. This differs from `openAtLogin` as it ignores the `args` option, this property will be true if the given executable would be launched at login with **any** arguments. * `launchItems` Object[] _Windows_ * `name` string _Windows_ - name value of a registry entry. * `path` string _Windows_ - The executable to an app that corresponds to a registry entry. * `args` string[] _Windows_ - the command-line arguments to pass to the executable. * `scope` string _Windows_ - one of `user` or `machine`. Indicates whether the registry entry is under `HKEY_CURRENT USER` or `HKEY_LOCAL_MACHINE`. * `enabled` boolean _Windows_ - `true` if the app registry key is startup approved and therefore shows as `enabled` in Task Manager and Windows settings. ### `app.setLoginItemSettings(settings)` _macOS_ _Windows_ * `settings` Object * `openAtLogin` boolean (optional) - `true` to open the app at login, `false` to remove the app as a login item. Defaults to `false`. * `openAsHidden` boolean (optional) _macOS_ _Deprecated_ - `true` to open the app as hidden. Defaults to `false`. The user can edit this setting from the System Preferences so `app.getLoginItemSettings().wasOpenedAsHidden` should be checked when the app is opened to know the current value. This setting is not available on [MAS builds][mas-builds] or on macOS 13 and up. * `type` string (optional) _macOS_ - The type of service to add as a login item. Defaults to `mainAppService`. Only available on macOS 13 and up. * `mainAppService` - The primary application. * `agentService` - The property list name for a launch agent. The property list name must correspond to a property list in the app’s `Contents/Library/LaunchAgents` directory. * `daemonService` string (optional) _macOS_ - The property list name for a launch agent. The property list name must correspond to a property list in the app’s `Contents/Library/LaunchDaemons` directory. * `loginItemService` string (optional) _macOS_ - The property list name for a login item service. The property list name must correspond to a property list in the app’s `Contents/Library/LoginItems` directory. * `serviceName` string (optional) _macOS_ - The name of the service. Required if `type` is non-default. Only available on macOS 13 and up. * `path` string (optional) _Windows_ - The executable to launch at login. Defaults to `process.execPath`. * `args` string[] (optional) _Windows_ - The command-line arguments to pass to the executable. Defaults to an empty array. Take care to wrap paths in quotes. * `enabled` boolean (optional) _Windows_ - `true` will change the startup approved registry key and `enable / disable` the App in Task Manager and Windows Settings. Defaults to `true`. * `name` string (optional) _Windows_ - value name to write into registry. Defaults to the app's AppUserModelId(). Set the app's login item settings. To work with Electron's `autoUpdater` on Windows, which uses [Squirrel][Squirrel-Windows], you'll want to set the launch path to your executable's name but a directory up, which is a stub application automatically generated by Squirrel which will automatically launch the latest version. ``` js const { app } = require('electron') const path = require('node:path') const appFolder = path.dirname(process.execPath) const ourExeName = path.basename(process.execPath) const stubLauncher = path.resolve(appFolder, '..', ourExeName) app.setLoginItemSettings({ openAtLogin: true, path: stubLauncher, args: [ // You might want to pass a parameter here indicating that this // app was launched via login, but you don't have to ] }) ``` For more information about setting different services as login items on macOS 13 and up, see [`SMAppService`](https://developer.apple.com/documentation/servicemanagement/smappservice?language=objc). ### `app.isAccessibilitySupportEnabled()` _macOS_ _Windows_ Returns `boolean` - `true` if Chrome's accessibility support is enabled, `false` otherwise. This API will return `true` if the use of assistive technologies, such as screen readers, has been detected. See https://www.chromium.org/developers/design-documents/accessibility for more details. ### `app.setAccessibilitySupportEnabled(enabled)` _macOS_ _Windows_ * `enabled` boolean - Enable or disable [accessibility tree](https://developers.google.com/web/fundamentals/accessibility/semantics-builtin/the-accessibility-tree) rendering Manually enables Chrome's accessibility support, allowing to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default. This API must be called after the `ready` event is emitted. > [!NOTE] > Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default. Calling this method will enable the following accessibility support features: `nativeAPIs`, `webContents`, `inlineTextBoxes`, and `extendedProperties`. ### `app.getAccessibilitySupportFeatures()` _macOS_ _Windows_ Returns `string[]` - Array of strings naming currently enabled accessibility support components. Possible values: * `nativeAPIs` - Native OS accessibility APIs integration enabled. * `webContents` - Web contents accessibility tree exposure enabled. * `inlineTextBoxes` - Inline text boxes (character bounding boxes) enabled. * `extendedProperties` - Extended accessibility properties enabled. * `screenReader` - Screen reader specific mode enabled. * `html` - HTML accessibility tree construction enabled. * `labelImages` - Accessibility support for automatic image annotations. * `pdfPrinting` - Accessibility support for PDF printing enabled. Notes: * The array may be empty if no accessibility modes are active. * Use `app.isAccessibilitySupportEnabled()` for the legacy boolean check; prefer this method for granular diagnostics or telemetry. Example: ```js const { app } = require('electron') app.whenReady().then(() => { if (app.getAccessibilitySupportFeatures().includes('screenReader')) { // Change some app UI to better work with Screen Readers. } }) ``` ### `app.setAccessibilitySupportFeatures(features)` _macOS_ _Windows_ * `features` string[] - An array of the accessibility features to enable. Possible values are: * `nativeAPIs` - Native OS accessibility APIs integration enabled. * `webContents` - Web contents accessibility tree exposure enabled. * `inlineTextBoxes` - Inline text boxes (character bounding boxes) enabled. * `extendedProperties` - Extended accessibility properties enabled. * `screenReader` - Screen reader specific mode enabled. * `html` - HTML accessibility tree construction enabled. * `labelImages` - Accessibility support for automatic image annotations. * `pdfPrinting` - Accessibility support for PDF printing enabled. To disable all supported features, pass an empty array `[]`. Example: ```js const { app } = require('electron') app.whenReady().then(() => { // Enable a subset of features: app.setAccessibilitySupportFeatures([ 'screenReader', 'pdfPrinting', 'webContents' ]) // Other logic // Some time later, disable all features: app.setAccessibilitySupportFeatures([]) }) ``` ### `app.showAboutPanel()` Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`. This function runs asynchronously. ### `app.setAboutPanelOptions(options)` * `options` Object * `applicationName` string (optional) - The app's name. * `applicationVersion` string (optional) - The app's version. * `copyright` string (optional) - Copyright information. * `version` string (optional) _macOS_ - The app's build version number. * `credits` string (optional) _macOS_ _Windows_ - Credit information. * `authors` string[] (optional) _Linux_ - List of app authors. * `website` string (optional) _Linux_ - The app's website. * `iconPath` string (optional) _Linux_ _Windows_ - Path to the app's icon in a JPEG or PNG file format. On Linux, will be shown as 64x64 pixels while retaining aspect ratio. On Windows, a 48x48 PNG will result in the best visual quality. Set the about panel options. This will override the values defined in the app's `.plist` file on macOS. See the [Apple docs][about-panel-options] for more details. On Linux, values must be set in order to be shown; there are no defaults. If you do not set `credits` but still wish to surface them in your app, AppKit will look for a file named "Credits.html", "Credits.rtf", and "Credits.rtfd", in that order, in the bundle returned by the NSBundle class method main. The first file found is used, and if none is found, the info area is left blank. See Apple [documentation](https://developer.apple.com/documentation/appkit/nsaboutpaneloptioncredits?language=objc) for more information. ### `app.isEmojiPanelSupported()` Returns `boolean` - whether or not the current OS version allows for native emoji pickers. ### `app.showEmojiPanel()` _macOS_ _Windows_ Show the platform's native emoji picker. ### `app.startAccessingSecurityScopedResource(bookmarkData)` _mas_ * `bookmarkData` string - The base64 encoded security scoped bookmark data returned by the `dialog.showOpenDialog` or `dialog.showSaveDialog` methods. Returns `Function` - This function **must** be called once you have finished accessing the security scoped file. If you do not remember to stop accessing the bookmark, [kernel resources will be leaked](https://developer.apple.com/reference/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc) and your app will lose its ability to reach outside the sandbox completely, until your app is restarted. ```js const { app, dialog } = require('electron') const fs = require('node:fs') let filepath let bookmark dialog.showOpenDialog(null, { securityScopedBookmarks: true }).then(({ filePaths, bookmarks }) => { filepath = filePaths[0] bookmark = bookmarks[0] fs.readFileSync(filepath) }) // ... restart app ... const stopAccessingSecurityScopedResource = app.startAccessingSecurityScopedResource(bookmark) fs.readFileSync(filepath) stopAccessingSecurityScopedResource() ``` Start accessing a security scoped resource. With this method Electron applications that are packaged for the Mac App Store may reach outside their sandbox to access files chosen by the user. See [Apple's documentation](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) for a description of how this system works. ### `app.enableSandbox()` Enables full sandbox mode on the app. This means that all renderers will be launched sandboxed, regardless of the value of the `sandbox` flag in [`WebPreferences`](structures/web-preferences.md). This method can only be called before app is ready. ### `app.isInApplicationsFolder()` _macOS_ Returns `boolean` - Whether the application is currently running from the systems Application folder. Use in combination with `app.moveToApplicationsFolder()` ### `app.moveToApplicationsFolder([options])` _macOS_ * `options` Object (optional) * `conflictHandler` Function\ (optional) - A handler for potential conflict in move failure. * `conflictType` string - The type of move conflict encountered by the handler; can be `exists` or `existsAndRunning`, where `exists` means that an app of the same name is present in the Applications directory and `existsAndRunning` means both that it exists and that it's presently running. Returns `boolean` - Whether the move was successful. Please note that if the move is successful, your application will quit and relaunch. No confirmation dialog will be presented by default. If you wish to allow the user to confirm the operation, you may do so using the [`dialog`](dialog.md) API. **NOTE:** This method throws errors if anything other than the user causes the move to fail. For instance if the user cancels the authorization dialog, this method returns false. If we fail to perform the copy, then this method will throw an error. The message in the error should be informative and tell you exactly what went wrong. By default, if an app of the same name as the one being moved exists in the Applications directory and is _not_ running, the existing app will be trashed and the active app moved into its place. If it _is_ running, the preexisting running app will assume focus and the previously active app will quit itself. This behavior can be changed by providing the optional conflict handler, where the boolean returned by the handler determines whether or not the move conflict is resolved with default behavior. i.e. returning `false` will ensure no further action is taken, returning `true` will result in the default behavior and the method continuing. For example: ```js const { app, dialog } = require('electron') app.moveToApplicationsFolder({ conflictHandler: (conflictType) => { if (conflictType === 'exists') { return dialog.showMessageBoxSync({ type: 'question', buttons: ['Halt Move', 'Continue Move'], defaultId: 0, message: 'An app of this name already exists' }) === 1 } } }) ``` Would mean that if an app already exists in the user directory, if the user chooses to 'Continue Move' then the function would continue with its default behavior and the existing app will be trashed and the active app moved into its place. ### `app.isSecureKeyboardEntryEnabled()` _macOS_ Returns `boolean` - whether `Secure Keyboard Entry` is enabled. By default this API will return `false`. ### `app.setSecureKeyboardEntryEnabled(enabled)` _macOS_ * `enabled` boolean - Enable or disable `Secure Keyboard Entry` Set the `Secure Keyboard Entry` is enabled in your application. By using this API, important information such as password and other sensitive information can be prevented from being intercepted by other processes. See [Apple's documentation](https://developer.apple.com/library/archive/technotes/tn2150/_index.html) for more details. > [!NOTE] > Enable `Secure Keyboard Entry` only when it is needed and disable it when it is no longer needed. ### `app.setProxy(config)` * `config` [ProxyConfig](structures/proxy-config.md) Returns `Promise` - Resolves when the proxy setting process is complete. Sets the proxy settings for networks requests made without an associated [Session](session.md). Currently this will affect requests made with [Net](net.md) in the [utility process](../glossary.md#utility-process) and internal requests made by the runtime (ex: geolocation queries). This method can only be called after app is ready. ### `app.resolveProxy(url)` * `url` URL Returns `Promise` - Resolves with the proxy information for `url` that will be used when attempting to make requests using [Net](net.md) in the [utility process](../glossary.md#utility-process). ### `app.setClientCertRequestPasswordHandler(handler)` _Linux_ * `handler` Function\\> * `clientCertRequestParams` Object * `hostname` string - the hostname of the site requiring a client certificate * `tokenName` string - the token (or slot) name of the cryptographic device * `isRetry` boolean - whether there have been previous failed attempts at prompting the password Returns `Promise` - Resolves with the password The handler is called when a password is needed to unlock a client certificate for `hostname`. ```js const { app } = require('electron') async function passwordPromptUI (text) { return new Promise((resolve, reject) => { // display UI to prompt user for password // ... // ... resolve('the password') }) } app.setClientCertRequestPasswordHandler(async ({ hostname, tokenName, isRetry }) => { const text = `Please sign in to ${tokenName} to authenticate to ${hostname} with your certificate` const password = await passwordPromptUI(text) return password }) ``` ## Properties ### `app.accessibilitySupportEnabled` _macOS_ _Windows_ A `boolean` property that's `true` if Chrome's accessibility support is enabled, `false` otherwise. This property will be `true` if the use of assistive technologies, such as screen readers, has been detected. Setting this property to `true` manually enables Chrome's accessibility support, allowing developers to expose accessibility switch to users in application settings. See [Chromium's accessibility docs](https://www.chromium.org/developers/design-documents/accessibility) for more details. Disabled by default. This API must be called after the `ready` event is emitted. > [!NOTE] > Rendering accessibility tree can significantly affect the performance of your app. It should not be enabled by default. ### `app.applicationMenu` A `Menu | null` property that returns [`Menu`](menu.md) if one has been set and `null` otherwise. Users can pass a [Menu](menu.md) to set this property. ### `app.badgeCount` _Linux_ _macOS_ An `Integer` property that returns the badge count for current app. Setting the count to `0` will hide the badge. On macOS, setting this with any nonzero integer shows on the dock icon. On Linux, this property only works for Unity launcher. > [!NOTE] > Unity launcher requires a `.desktop` file to work. For more information, > please read the [Unity integration documentation][unity-requirement]. > [!NOTE] > On macOS, you need to ensure that your application has the permission > to display notifications for this property to take effect. ### `app.commandLine` _Readonly_ A [`CommandLine`](./command-line.md) object that allows you to read and manipulate the command line arguments that Chromium uses. ### `app.dock` _macOS_ _Readonly_ A `Dock | undefined` property ([`Dock`](./dock.md) on macOS, `undefined` on all other platforms) that allows you to perform actions on your app icon in the user's dock. ### `app.isPackaged` _Readonly_ A `boolean` property that returns `true` if the app is packaged, `false` otherwise. For many apps, this property can be used to distinguish development and production environments. [tasks]:https://learn.microsoft.com/en-us/windows/win32/shell/taskbar-extensions#tasks [app-user-model-id]: https://learn.microsoft.com/en-us/windows/win32/shell/appids [electron-forge]: https://www.electronforge.io/ [electron-packager]: https://github.com/electron/packager [CFBundleURLTypes]: https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/TP40009249-102207-TPXREF115 [LSCopyDefaultHandlerForURLScheme]: https://developer.apple.com/documentation/coreservices/1441725-lscopydefaulthandlerforurlscheme?language=objc [handoff]: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html [activity-type]: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType [unity-requirement]: https://help.ubuntu.com/community/UnityLaunchersAndDesktopFiles#Adding_shortcuts_to_a_launcher [mas-builds]: ../tutorial/mac-app-store-submission-guide.md [Squirrel-Windows]: https://github.com/Squirrel/Squirrel.Windows [JumpListBeginListMSDN]: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-icustomdestinationlist-beginlist [about-panel-options]: https://developer.apple.com/reference/appkit/nsapplication/1428479-orderfrontstandardaboutpanelwith?language=objc [happy-eyeballs-v3]: https://datatracker.ietf.org/doc/draft-pauly-happy-happyeyeballs-v3/ ### `app.name` A `string` property that indicates 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. ### `app.userAgentFallback` A `string` which is the user agent string Electron will use as a global fallback. This is the user agent that will be used when no user agent is set at the `webContents` or `session` level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used. ### `app.runningUnderARM64Translation` _Readonly_ _macOS_ _Windows_ A `boolean` which when `true` indicates that the app is currently running under an ARM64 translator (like the macOS [Rosetta Translator Environment](https://en.wikipedia.org/wiki/Rosetta_(software)) or Windows [WOW](https://en.wikipedia.org/wiki/Windows_on_Windows)). You can use this property to prompt users to download the arm64 version of your application when they are mistakenly running the x64 version under Rosetta or WOW. --- # autoUpdater > Enable apps to automatically update themselves. Process: [Main](../glossary.md#main-process) **See also: [A detailed guide about how to implement updates in your application](../tutorial/updates.md).** `autoUpdater` is an [EventEmitter][event-emitter]. ## Platform Notices Currently, only macOS and Windows are supported. There is no built-in support for auto-updater on Linux, so it is recommended to use the distribution's package manager to update your app. In addition, there are some subtle differences on each platform: ### macOS On macOS, the `autoUpdater` module is built upon [Squirrel.Mac][squirrel-mac], meaning you don't need any special setup to make it work. For server-side requirements, you can read [Server Support][server-support]. Note that [App Transport Security](https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW35) (ATS) applies to all requests made as part of the update process. Apps that need to disable ATS can add the `NSAllowsArbitraryLoads` key to their app's plist. > [!IMPORTANT] > Your application must be signed for automatic updates on macOS. > This is a requirement of `Squirrel.Mac`. ### Windows On Windows, you have to install your app into a user's machine before you can use the `autoUpdater`, so it is recommended that you use [electron-winstaller][installer-lib] or [Electron Forge's Squirrel.Windows maker][electron-forge-lib] to generate a Windows installer. Apps built with Squirrel.Windows will trigger [custom launch events](https://github.com/Squirrel/Squirrel.Windows/blob/51f5e2cb01add79280a53d51e8d0cfa20f8c9f9f/docs/using/custom-squirrel-events-non-cs.md#application-startup-commands) that must be handled by your Electron application to ensure proper setup and teardown. Squirrel.Windows apps will launch with the `--squirrel-firstrun` argument immediately after installation. During this time, Squirrel.Windows will obtain a file lock on your app, and `autoUpdater` requests will fail until the lock is released. In practice, this means that you won't be able to check for updates on first launch for the first few seconds. You can work around this by not checking for updates when `process.argv` contains the `--squirrel-firstrun` flag or by setting a 10-second timeout on your update checks (see [electron/electron#7155](https://github.com/electron/electron/issues/7155) for more information). The installer generated with Squirrel.Windows will create a shortcut icon with an [Application User Model ID][app-user-model-id] in the format of `com.squirrel.PACKAGE_ID.YOUR_EXE_WITHOUT_DOT_EXE`, examples are `com.squirrel.slack.Slack` and `com.squirrel.code.Code`. You have to use the same ID for your app with `app.setAppUserModelId` API, otherwise Windows will not be able to pin your app properly in task bar. ## Events The `autoUpdater` object emits the following events: ### Event: 'error' Returns: * `error` Error Emitted when there is an error while updating. ### Event: 'checking-for-update' Emitted when checking for an available update has started. ### Event: 'update-available' Emitted when there is an available update. The update is downloaded automatically. ### Event: 'update-not-available' Emitted when there is no available update. ### Event: 'update-downloaded' Returns: * `event` Event * `releaseNotes` string * `releaseName` string * `releaseDate` Date * `updateURL` string Emitted when an update has been downloaded. On Windows only `releaseName` is available. > [!NOTE] > It is not strictly necessary to handle this event. A successfully > downloaded update will still be applied the next time the application starts. ### Event: 'before-quit-for-update' This event is emitted after a user calls `quitAndInstall()`. When this API is called, the `before-quit` event is not emitted before all windows are closed. As a result you should listen to this event if you wish to perform actions before the windows are closed while a process is quitting, as well as listening to `before-quit`. ## Methods The `autoUpdater` object has the following methods: ### `autoUpdater.setFeedURL(options)` * `options` Object * `url` string * `headers` Record\ (optional) _macOS_ - HTTP request headers. * `serverType` string (optional) _macOS_ - Can be `json` or `default`, see the [Squirrel.Mac][squirrel-mac] README for more information. Sets the `url` and initialize the auto updater. ### `autoUpdater.getFeedURL()` Returns `string` - The current update feed URL. ### `autoUpdater.checkForUpdates()` Asks the server whether there is an update. You must call `setFeedURL` before using this API. > [!NOTE] > If an update is available it will be downloaded automatically. > Calling `autoUpdater.checkForUpdates()` twice will download the update two times. ### `autoUpdater.quitAndInstall()` Restarts the app and installs the update after it has been downloaded. It should only be called after `update-downloaded` has been emitted. Under the hood calling `autoUpdater.quitAndInstall()` will close all application windows first, and automatically call `app.quit()` after all windows have been closed. > [!NOTE] > It is not strictly necessary to call this function to apply an update, > as a successfully downloaded update will always be applied the next time the > application starts. [squirrel-mac]: https://github.com/Squirrel/Squirrel.Mac [server-support]: https://github.com/Squirrel/Squirrel.Mac#server-support [installer-lib]: https://github.com/electron/windows-installer [electron-forge-lib]: https://www.electronforge.io/config/makers/squirrel.windows [app-user-model-id]: https://learn.microsoft.com/en-us/windows/win32/shell/appids [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter --- # BaseWindow > Create and control windows. Process: [Main](../glossary.md#main-process) > [!NOTE] > `BaseWindow` provides a flexible way to compose multiple web views in a > single window. For windows with only a single, full-size web view, the > [`BrowserWindow`](browser-window.md) class may be a simpler option. This module cannot be used until the `ready` event of the `app` module is emitted. ```js // In the main process. const { BaseWindow, WebContentsView } = require('electron') const win = new BaseWindow({ width: 800, height: 600 }) const leftView = new WebContentsView() leftView.webContents.loadURL('https://electronjs.org') win.contentView.addChildView(leftView) const rightView = new WebContentsView() rightView.webContents.loadURL('https://github.com/electron/electron') win.contentView.addChildView(rightView) leftView.setBounds({ x: 0, y: 0, width: 400, height: 600 }) rightView.setBounds({ x: 400, y: 0, width: 400, height: 600 }) ``` ## Parent and child windows By using `parent` option, you can create child windows: ```js const { BaseWindow } = require('electron') const parent = new BaseWindow() const child = new BaseWindow({ parent }) ``` The `child` window will always show on top of the `parent` window. ## Modal windows A modal window is a child window that disables parent window. To create a modal window, you have to set both the `parent` and `modal` options: ```js const { BaseWindow } = require('electron') const parent = new BaseWindow() const child = new BaseWindow({ parent, modal: true }) ``` ## Platform notices * On macOS modal windows will be displayed as sheets attached to the parent window. * On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move. * On Linux the type of modal windows will be changed to `dialog`. * On Linux many desktop environments do not support hiding a modal window. ## Resource management When you add a [`WebContentsView`](web-contents-view.md) to a `BaseWindow` and the `BaseWindow` is closed, the [`webContents`](web-contents.md) of the `WebContentsView` are not destroyed automatically. It is your responsibility to close the `webContents` when you no longer need them, e.g. when the `BaseWindow` is closed: ```js const { BaseWindow, WebContentsView } = require('electron') const win = new BaseWindow({ width: 800, height: 600 }) const view = new WebContentsView() win.contentView.addChildView(view) win.on('closed', () => { view.webContents.close() }) ``` Unlike with a [`BrowserWindow`](browser-window.md), if you don't explicitly close the `webContents`, you'll encounter memory leaks. ## Class: BaseWindow > Create and control windows. Process: [Main](../glossary.md#main-process) `BaseWindow` is an [EventEmitter][event-emitter]. It creates a new `BaseWindow` with native properties as set by the `options`. > [!WARNING] > Electron's built-in classes cannot be subclassed in user code. > For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules). ### `new BaseWindow([options])` * `options` [BaseWindowConstructorOptions](structures/base-window-options.md?inline) (optional) ### Instance Events Objects created with `new BaseWindow` emit the following events: > [!NOTE] > Some events are only available on specific operating systems and are > labeled as such. #### Event: 'close' Returns: * `event` Event Emitted when the window is going to be closed. It's emitted before the `beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()` will cancel the close. Usually you would want to use the `beforeunload` handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than `undefined` would cancel the close. For example: ```js window.onbeforeunload = (e) => { console.log('I do not want to be closed') // Unlike usual browsers that a message box will be prompted to users, returning // a non-void value will silently cancel the close. // It is recommended to use the dialog API to let the user confirm closing the // application. e.returnValue = false } ``` > [!NOTE] > There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and > `window.addEventListener('beforeunload', handler)`. It is recommended to always set the > `event.returnValue` explicitly, instead of only returning a value, as the former works more > consistently within Electron. #### Event: 'closed' Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more. #### Event: 'query-session-end' _Windows_ Returns: * `event` [WindowSessionEndEvent][window-session-end-event] Emitted when a session is about to end due to a shutdown, machine restart, or user log-off. Calling `event.preventDefault()` can delay the system shutdown, though it’s generally best to respect the user’s choice to end the session. However, you may choose to use it if ending the session puts the user at risk of losing data. #### Event: 'session-end' _Windows_ Returns: * `event` [WindowSessionEndEvent][window-session-end-event] Emitted when a session is about to end due to a shutdown, machine restart, or user log-off. Once this event fires, there is no way to prevent the session from ending. #### Event: 'blur' Returns: * `event` Event Emitted when the window loses focus. #### Event: 'focus' Returns: * `event` Event Emitted when the window gains focus. #### Event: 'show' Emitted when the window is shown. #### Event: 'hide' Emitted when the window is hidden. #### Event: 'maximize' Emitted when window is maximized. #### Event: 'unmaximize' Emitted when the window exits from a maximized state. #### Event: 'minimize' Emitted when the window is minimized. #### Event: 'restore' Emitted when the window is restored from a minimized state. #### Event: 'will-resize' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to. * `details` Object * `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`. Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized. Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event. The possible values and behaviors of the `edge` option are platform dependent. Possible values are: * On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`. * On macOS, possible values are `bottom` and `right`. * The value `bottom` is used to denote vertical resizing. * The value `right` is used to denote horizontal resizing. #### Event: 'resize' Emitted after the window has been resized. #### Event: 'resized' _macOS_ _Windows_ Emitted once when the window has finished being resized. This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished. #### Event: 'will-move' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to. Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved. Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event. #### Event: 'move' Emitted when the window is being moved to a new position. #### Event: 'moved' _macOS_ _Windows_ Emitted once when the window is moved to a new position. > [!NOTE] > On macOS, this event is an alias of `move`. #### Event: 'enter-full-screen' Emitted when the window enters a full-screen state. #### Event: 'leave-full-screen' Emitted when the window leaves a full-screen state. #### Event: 'always-on-top-changed' Returns: * `event` Event * `isAlwaysOnTop` boolean Emitted when the window is set or unset to show always on top of other windows. #### Event: 'app-command' _Windows_ _Linux_ Returns: * `event` Event * `command` string Emitted when an [App Command](https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-appcommand) is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. Commands are lowercased, underscores are replaced with hyphens, and the `APPCOMMAND_` prefix is stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. ```js const { BaseWindow } = require('electron') const win = new BaseWindow() win.on('app-command', (e, cmd) => { // Navigate the window back when the user hits their mouse back button if (cmd === 'browser-backward') { // Find the appropriate WebContents to navigate. } }) ``` The following app commands are explicitly supported on Linux: * `browser-backward` * `browser-forward` #### Event: 'swipe' _macOS_ Returns: * `event` Event * `direction` string Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`. The method underlying this event is built to handle older macOS-style trackpad swiping, where the content on the screen doesn't move with the swipe. Most macOS trackpads are not configured to allow this kind of swiping anymore, so in order for it to emit properly the 'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be set to 'Swipe with two or three fingers'. #### Event: 'rotate-gesture' _macOS_ Returns: * `event` Event * `rotation` Float Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is ended. The `rotation` value on each emission is the angle in degrees rotated since the last emission. The last emitted event upon a rotation gesture will always be of value `0`. Counter-clockwise rotation values are positive, while clockwise ones are negative. #### Event: 'sheet-begin' _macOS_ Emitted when the window opens a sheet. #### Event: 'sheet-end' _macOS_ Emitted when the window has closed a sheet. #### Event: 'new-window-for-tab' _macOS_ Emitted when the native new tab button is clicked. #### Event: 'system-context-menu' _Windows_ _Linux_ Returns: * `event` Event * `point` [Point](structures/point.md) - The screen coordinates where the context menu was triggered. Emitted when the system context menu is triggered on the window, this is normally only triggered when the user right clicks on the non-client area of your window. This is the window titlebar or any area you have declared as `-webkit-app-region: drag` in a frameless window. Calling `event.preventDefault()` will prevent the menu from being displayed. To convert `point` to DIP, use [`screen.screenToDipPoint(point)`](./screen.md#screenscreentodippointpoint-windows-linux). ### Static Methods The `BaseWindow` class has the following static methods: #### `BaseWindow.getAllWindows()` Returns `BaseWindow[]` - An array of all opened browser windows. #### `BaseWindow.getFocusedWindow()` Returns `BaseWindow | null` - The window that is focused in this application, otherwise returns `null`. #### `BaseWindow.fromId(id)` * `id` Integer Returns `BaseWindow | null` - The window with the given `id`. ### Instance Properties Objects created with `new BaseWindow` have the following properties: ```js const { BaseWindow } = require('electron') // In this example `win` is our instance const win = new BaseWindow({ width: 800, height: 600 }) ``` #### `win.id` _Readonly_ A `Integer` property representing the unique ID of the window. Each ID is unique among all `BaseWindow` instances of the entire Electron application. #### `win.contentView` A `View` property for the content view of the window. #### `win.tabbingIdentifier` _macOS_ _Readonly_ A `string` (optional) property that is equal to the `tabbingIdentifier` passed to the `BrowserWindow` constructor or `undefined` if none was set. #### `win.autoHideMenuBar` _Linux_ _Windows_ A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, setting this property to `true` won't hide it immediately. #### `win.simpleFullScreen` A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode. #### `win.fullScreen` A `boolean` property that determines whether the window is in fullscreen mode. #### `win.focusable` _Windows_ _macOS_ A `boolean` property that determines whether the window is focusable. #### `win.visibleOnAllWorkspaces` _macOS_ _Linux_ A `boolean` property that determines whether the window is visible on all workspaces. > [!NOTE] > Always returns false on Windows. #### `win.shadow` A `boolean` property that determines whether the window has a shadow. #### `win.menuBarVisible` _Windows_ _Linux_ A `boolean` property that determines whether the menu bar should be visible. > [!NOTE] > If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.kiosk` A `boolean` property that determines whether the window is in kiosk mode. #### `win.documentEdited` _macOS_ A `boolean` property that specifies whether the window’s document has been edited. The icon in title bar will become gray when set to `true`. #### `win.representedFilename` _macOS_ A `string` property that determines the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.title` A `string` property that determines the title of the native window. > [!NOTE] > The title of the web page can be different from the title of the native window. #### `win.minimizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually minimized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.maximizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually maximized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.fullScreenable` A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.resizable` A `boolean` property that determines whether the window can be manually resized by user. #### `win.closable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually closed by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.movable` _macOS_ _Windows_ A `boolean` property that determines Whether the window can be moved by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.excludedFromShownWindowsMenu` _macOS_ A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default. ```js @ts-expect-error=[12] const { Menu, BaseWindow } = require('electron') const win = new BaseWindow({ height: 600, width: 600 }) const template = [ { role: 'windowmenu' } ] win.excludedFromShownWindowsMenu = true const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ``` #### `win.accessibleTitle` A `string` property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users. #### `win.snapped` _Windows_ _Readonly_ A `boolean` property that indicates whether the window is arranged via [Snap.](https://support.microsoft.com/en-us/windows/snap-your-windows-885a9b1e-a983-a3b1-16cd-c531795e6241) ### Instance Methods Objects created with `new BaseWindow` have the following instance methods: > [!NOTE] > Some methods are only available on specific operating systems and are > labeled as such. #### `win.setContentView(view)` * `view` [View](view.md) Sets the content view of the window. #### `win.getContentView()` Returns [`View`](view.md) - The content view of the window. #### `win.destroy()` Force closing the window, the `unload` and `beforeunload` event won't be emitted for the web page, and `close` event will also not be emitted for this window, but it guarantees the `closed` event will be emitted. #### `win.close()` Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the [close event](#event-close). #### `win.focus()` Focuses on the window. #### `win.blur()` Removes focus from the window. #### `win.isFocused()` Returns `boolean` - Whether the window is focused. #### `win.isDestroyed()` Returns `boolean` - Whether the window is destroyed. #### `win.show()` Shows and gives focus to the window. #### `win.showInactive()` Shows the window but doesn't focus on it. #### `win.hide()` Hides the window. #### `win.isVisible()` Returns `boolean` - Whether the window is visible to the user in the foreground of the app. #### `win.isModal()` Returns `boolean` - Whether current window is a modal window. #### `win.maximize()` Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. #### `win.unmaximize()` Unmaximizes the window. #### `win.isMaximized()` Returns `boolean` - Whether the window is maximized. #### `win.minimize()` Minimizes the window. On some platforms the minimized window will be shown in the Dock. #### `win.restore()` Restores the window from minimized state to its previous state. #### `win.isMinimized()` Returns `boolean` - Whether the window is minimized. #### `win.setFullScreen(flag)` * `flag` boolean Sets whether the window should be in fullscreen mode. > [!NOTE] > On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the ['enter-full-screen'](base-window.md#event-enter-full-screen) or > ['leave-full-screen'](base-window.md#event-leave-full-screen) events. #### `win.isFullScreen()` Returns `boolean` - Whether the window is in fullscreen mode. #### `win.setSimpleFullScreen(flag)` _macOS_ * `flag` boolean Enters or leaves simple fullscreen mode. Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7). #### `win.isSimpleFullScreen()` _macOS_ Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode. #### `win.isNormal()` Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode). #### `win.setAspectRatio(aspectRatio[, extraSize])` * `aspectRatio` Float - The aspect ratio to maintain for some portion of the content view. * `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while maintaining the aspect ratio. This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size. Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and \{ width: 40, height: 50 \}. The second argument doesn't care where the extra width and height are within the content view--only that they exist. Sum any extra width and height areas you have within the overall content view. The aspect ratio is not respected when window is resized programmatically with APIs like `win.setSize`. To reset an aspect ratio, pass 0 as the `aspectRatio` value: `win.setAspectRatio(0)`. #### `win.setBackgroundColor(backgroundColor)` * `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type. Examples of valid `backgroundColor` values: * Hex * #fff (shorthand RGB) * #ffff (shorthand ARGB) * #ffffff (RGB) * #ffffffff (ARGB) * RGB * `rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)` * e.g. rgb(255, 255, 255) * RGBA * `rgba\(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)\)` * e.g. rgba(255, 255, 255, 1.0) * HSL * `hsl\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)` * e.g. hsl(200, 20%, 50%) * HSLA * `hsla\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)` * e.g. hsla(200, 20%, 50%, 0.5) * Color name * Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148) * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * e.g. `blueviolet` or `red` Sets the background color of the window. See [Setting `backgroundColor`](browser-window.md#setting-the-backgroundcolor-property). #### `win.previewFile(path[, displayName])` _macOS_ * `path` string - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open. * `displayName` string (optional) - The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to `path`. Uses [Quick Look][quick-look] to preview a file at a given path. #### `win.closeFilePreview()` _macOS_ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` * `bounds` Partial\<[Rectangle](structures/rectangle.md)\> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. ```js const { BaseWindow } = require('electron') const win = new BaseWindow() // set all bounds properties win.setBounds({ x: 440, y: 225, width: 800, height: 600 }) // set a single bounds property win.setBounds({ width: 100 }) // { x: 440, y: 225, width: 100, height: 600 } console.log(win.getBounds()) ``` > [!NOTE] > On macOS, the y-coordinate value cannot be smaller than the [Tray](tray.md) height. The tray height has changed over time and depends on the operating system, but is between 20-40px. Passing a value lower than the tray height will result in a window that is flush to the tray. #### `win.getBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`. > [!NOTE] > On macOS, the y-coordinate value returned will be at minimum the [Tray](tray.md) height. For example, calling `win.setBounds({ x: 25, y: 20, width: 800, height: 600 })` with a tray height of 38 means that `win.getBounds()` will return `{ x: 25, y: 38, width: 800, height: 600 }`. #### `win.getBackgroundColor()` Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format. See [Setting `backgroundColor`](browser-window.md#setting-the-backgroundcolor-property). > [!NOTE] > The alpha value is _not_ returned alongside the red, green, and blue values. #### `win.setContentBounds(bounds[, animate])` * `bounds` [Rectangle](structures/rectangle.md) * `animate` boolean (optional) _macOS_ Resizes and moves the window's client area (e.g. the web page) to the supplied bounds. #### `win.getContentBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`. #### `win.getNormalBounds()` Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state > [!NOTE] > Whatever the current state of the window : maximized, minimized or in fullscreen, this function always returns the position and size of the window in normal state. In normal state, getBounds and getNormalBounds returns the same [`Rectangle`](structures/rectangle.md). #### `win.setEnabled(enable)` * `enable` boolean Disable or enable the window. #### `win.isEnabled()` Returns `boolean` - whether the window is enabled. #### `win.setSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size. #### `win.getSize()` Returns `Integer[]` - Contains the window's width and height. #### `win.setContentSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window's client area (e.g. the web page) to `width` and `height`. #### `win.getContentSize()` Returns `Integer[]` - Contains the window's client area's width and height. #### `win.setMinimumSize(width, height)` * `width` Integer * `height` Integer Sets the minimum size of window to `width` and `height`. #### `win.getMinimumSize()` Returns `Integer[]` - Contains the window's minimum width and height. #### `win.setMaximumSize(width, height)` * `width` Integer * `height` Integer Sets the maximum size of window to `width` and `height`. #### `win.getMaximumSize()` Returns `Integer[]` - Contains the window's maximum width and height. #### `win.setResizable(resizable)` * `resizable` boolean Sets whether the window can be manually resized by the user. #### `win.isResizable()` Returns `boolean` - Whether the window can be manually resized by the user. #### `win.setMovable(movable)` _macOS_ _Windows_ * `movable` boolean Sets whether the window can be moved by user. On Linux does nothing. #### `win.isMovable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be moved by user. On Linux always returns `true`. #### `win.setMinimizable(minimizable)` _macOS_ _Windows_ * `minimizable` boolean Sets whether the window can be manually minimized by user. On Linux does nothing. #### `win.isMinimizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually minimized by the user. On Linux always returns `true`. #### `win.setMaximizable(maximizable)` _macOS_ _Windows_ * `maximizable` boolean Sets whether the window can be manually maximized by user. On Linux does nothing. #### `win.isMaximizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually maximized by user. On Linux always returns `true`. #### `win.setFullScreenable(fullscreenable)` * `fullscreenable` boolean Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.isFullScreenable()` Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.setClosable(closable)` _macOS_ _Windows_ * `closable` boolean Sets whether the window can be manually closed by user. On Linux does nothing. #### `win.isClosable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually closed by user. On Linux always returns `true`. #### `win.setHiddenInMissionControl(hidden)` _macOS_ * `hidden` boolean Sets whether the window will be hidden when the user toggles into mission control. #### `win.isHiddenInMissionControl()` _macOS_ Returns `boolean` - Whether the window will be hidden when the user toggles into mission control. #### `win.setAlwaysOnTop(flag[, level][, relativeLevel])` * `flag` boolean * `level` string (optional) _macOS_ _Windows_ - Values include `normal`, `floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`, `pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is `floating` when `flag` is true. The `level` is reset to `normal` when the flag is false. Note that from `floating` to `status` included, the window is placed below the Dock on macOS and below the taskbar on Windows. From `pop-up-menu` to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the [macOS docs][window-levels] for more details. * `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set this window relative to the given `level`. The default is `0`. Note that Apple discourages setting levels higher than 1 above `screen-saver`. Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on. #### `win.isAlwaysOnTop()` Returns `boolean` - Whether the window is always on top of other windows. #### `win.moveAbove(mediaSourceId)` * `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0". Moves window above the source window in the sense of z-order. If the `mediaSourceId` is not of type window or if the window does not exist then this method throws an error. #### `win.moveTop()` Moves window to top(z-order) regardless of focus #### `win.center()` Moves window to the center of the screen. #### `win.setPosition(x, y[, animate])` * `x` Integer * `y` Integer * `animate` boolean (optional) _macOS_ Moves window to `x` and `y`. #### `win.getPosition()` Returns `Integer[]` - Contains the window's current position. #### `win.setTitle(title)` * `title` string Changes the title of native window to `title`. #### `win.getTitle()` Returns `string` - The title of the native window. > [!NOTE] > The title of the web page can be different from the title of the native > window. #### `win.setSheetOffset(offsetY[, offsetX])` _macOS_ * `offsetY` Float * `offsetX` Float (optional) Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example: ```js const { BaseWindow } = require('electron') const win = new BaseWindow() const toolbarRect = document.getElementById('toolbar').getBoundingClientRect() win.setSheetOffset(toolbarRect.height) ``` #### `win.flashFrame(flag)` * `flag` boolean Starts or stops flashing the window to attract user's attention. #### `win.setSkipTaskbar(skip)` _macOS_ _Windows_ * `skip` boolean Makes the window not show in the taskbar. #### `win.setKiosk(flag)` * `flag` boolean Enters or leaves kiosk mode. #### `win.isKiosk()` Returns `boolean` - Whether the window is in kiosk mode. #### `win.isTabletMode()` _Windows_ Returns `boolean` - Whether the window is in Windows 10 tablet mode. Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet), under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons. This API returns whether the window is in tablet mode, and the `resize` event can be be used to listen to changes to tablet mode. #### `win.getMediaSourceId()` Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0". More precisely the format is `window:id:other_id` where `id` is `HWND` on Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on Linux. `other_id` is used to identify web contents (tabs) so within the same top level window. #### `win.getNativeWindowHandle()` Returns `Buffer` - The platform-specific handle of the window. The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and `Window` (`unsigned long`) on Linux. #### `win.hookWindowMessage(message, callback)` _Windows_ * `message` Integer * `callback` Function * `wParam` Buffer - The `wParam` provided to the WndProc * `lParam` Buffer - The `lParam` provided to the WndProc Hooks a windows message. The `callback` is called when the message is received in the WndProc. #### `win.isWindowMessageHooked(message)` _Windows_ * `message` Integer Returns `boolean` - `true` or `false` depending on whether the message is hooked. #### `win.unhookWindowMessage(message)` _Windows_ * `message` Integer Unhook the window message. #### `win.unhookAllWindowMessages()` _Windows_ Unhooks all of the window messages. #### `win.setRepresentedFilename(filename)` _macOS_ * `filename` string Sets the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.getRepresentedFilename()` _macOS_ Returns `string` - The pathname of the file the window represents. #### `win.setDocumentEdited(edited)` _macOS_ * `edited` boolean Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to `true`. #### `win.isDocumentEdited()` _macOS_ Returns `boolean` - Whether the window's document has been edited. #### `win.setMenu(menu)` _Linux_ _Windows_ * `menu` Menu | null Sets the `menu` as the window's menu bar. #### `win.removeMenu()` _Linux_ _Windows_ Remove the window's menu bar. #### `win.setProgressBar(progress[, options])` * `progress` Double * `options` Object (optional) * `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`. Sets progress value in progress bar. Valid range is \[0, 1.0]. Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1. On Linux platform, only supports Unity desktop environment, you need to specify the `*.desktop` file name to `desktopName` field in `package.json`. By default, it will assume `{app.name}.desktop`. On Windows, a mode can be passed. Accepted values are `none`, `normal`, `indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a mode set (but with a value within the valid range), `normal` will be assumed. #### `win.setOverlayIcon(overlay, description)` _Windows_ * `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter is `null`, the overlay is cleared * `description` string - a description that will be provided to Accessibility screen readers Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user. #### `win.invalidateShadow()` _macOS_ Invalidates the window shadow so that it is recomputed based on the current window shape. `BaseWindow`s that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation. #### `win.setHasShadow(hasShadow)` * `hasShadow` boolean Sets whether the window should have a shadow. #### `win.hasShadow()` Returns `boolean` - Whether the window has a shadow. #### `win.setOpacity(opacity)` _Windows_ _macOS_ * `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque) Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the \[0, 1] range. #### `win.getOpacity()` Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1. #### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_ * `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window. Passing an empty list reverts the window to being rectangular. Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window. #### `win.setThumbarButtons(buttons)` _Windows_ * `buttons` [ThumbarButton[]](structures/thumbar-button.md) Returns `boolean` - Whether the buttons were added successfully Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a `boolean` object indicates whether the thumbnail has been added successfully. The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform's limitation. But you can call the API with an empty array to clean the buttons. The `buttons` is an array of `Button` objects: * `Button` Object * `icon` [NativeImage](native-image.md) - The icon showing in thumbnail toolbar. * `click` Function * `tooltip` string (optional) - The text of the button's tooltip. * `flags` string[] (optional) - Control specific states and behaviors of the button. By default, it is `['enabled']`. The `flags` is an array that can include following `string`s: * `enabled` - The button is active and available to the user. * `disabled` - The button is disabled. It is present, but has a visual state indicating it will not respond to user action. * `dismissonclick` - When the button is clicked, the thumbnail window closes immediately. * `nobackground` - Do not draw a button border, use only the image. * `hidden` - The button is not shown to the user. * `noninteractive` - The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification. #### `win.setThumbnailClip(region)` _Windows_ * `region` [Rectangle](structures/rectangle.md) - Region of the window Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: `{ x: 0, y: 0, width: 0, height: 0 }`. #### `win.setThumbnailToolTip(toolTip)` _Windows_ * `toolTip` string Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. #### `win.setAppDetails(options)` _Windows_ * `options` Object * `appId` string (optional) - Window's [App User Model ID](https://learn.microsoft.com/en-us/windows/win32/shell/appids). It has to be set, otherwise the other options will have no effect. * `appIconPath` string (optional) - Window's [Relaunch Icon](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchiconresource). * `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`. Ignored when `appIconPath` is not set. Default is `0`. * `relaunchCommand` string (optional) - Window's [Relaunch Command](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchcommand). * `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchdisplaynameresource). Sets the properties for the window's taskbar button. > [!NOTE] > `relaunchCommand` and `relaunchDisplayName` must always be set > together. If one of those properties is not set, then neither will be used. #### `win.setAccentColor(accentColor)` _Windows_ * `accentColor` boolean | string | null - The accent color for the window. By default, follows user preference in System Settings. To reset to system default, pass `null`. Sets the system accent color and highlighting of active window border. The `accentColor` parameter accepts the following values: * **Color string** - Like `true`, but sets a custom accent color using standard CSS color formats (Hex, RGB, RGBA, HSL, HSLA, or named colors). Alpha values in RGBA/HSLA formats are ignored and the color is treated as fully opaque. * **`true`** - Enable accent color highlighting for the window with the system accent color regardless of whether accent colors are enabled for windows in System `Settings.` * **`false`** - Disable accent color highlighting for the window regardless of whether accent colors are currently enabled for windows in System Settings. * **`null`** - Reset window accent color behavior to follow behavior set in System Settings. Examples: ```js const win = new BrowserWindow({ frame: false }) // Set red accent color. win.setAccentColor('#ff0000') // RGB format (alpha ignored if present). win.setAccentColor('rgba(255,0,0,0.5)') // Enable accent color, using the color specified in System Settings. win.setAccentColor(true) // Disable accent color. win.setAccentColor(false) // Reset window accent color behavior to follow behavior set in System Settings. win.setAccentColor(null) ``` #### `win.getAccentColor()` _Windows_ Returns `string | boolean` - the system accent color and highlighting of active window border in Hex RGB format. If a color has been set for the window that differs from the system accent color, the window accent color will be returned. Otherwise, a boolean will be returned, with `true` indicating that the window uses the global system accent color, and `false` indicating that accent color highlighting is disabled for this window. #### `win.setIcon(icon)` _Windows_ _Linux_ * `icon` [NativeImage](native-image.md) | string Changes window icon. #### `win.setWindowButtonVisibility(visible)` _macOS_ * `visible` boolean Sets whether the window traffic light buttons should be visible. #### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_ * `hide` boolean Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately. #### `win.isMenuBarAutoHide()` _Windows_ _Linux_ Returns `boolean` - Whether menu bar automatically hides itself. #### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_ * `visible` boolean Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.isMenuBarVisible()` _Windows_ _Linux_ Returns `boolean` - Whether the menu bar is visible. #### `win.isSnapped()` _Windows_ Returns `boolean` - whether the window is arranged via [Snap.](https://support.microsoft.com/en-us/windows/snap-your-windows-885a9b1e-a983-a3b1-16cd-c531795e6241) The window is snapped via buttons shown when the mouse is hovered over window maximize button, or by dragging it to the edges of the screen. #### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_ * `visible` boolean * `options` Object (optional) * `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether the window should be visible above fullscreen windows. * `skipTransformProcessType` boolean (optional) _macOS_ - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType. Sets whether the window should be visible on all workspaces. > [!NOTE] > This API does nothing on Windows. #### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_ Returns `boolean` - Whether the window is visible on all workspaces. > [!NOTE] > This API always returns false on Windows. #### `win.setIgnoreMouseEvents(ignore[, options])` * `ignore` boolean * `options` Object (optional) * `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move messages to Chromium, enabling mouse related events such as `mouseleave`. Only used when `ignore` is true. If `ignore` is false, forwarding is always disabled regardless of this value. Makes the window ignore all mouse events. All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events. #### `win.setContentProtection(enable)` _macOS_ _Windows_ * `enable` boolean Prevents the window contents from being captured by other apps. On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with `WDA_EXCLUDEFROMCAPTURE`. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window. #### `win.isContentProtected()` _macOS_ _Windows_ Returns `boolean` - whether or not content protection is currently enabled. #### `win.setFocusable(focusable)` _macOS_ _Windows_ * `focusable` boolean Changes whether the window can be focused. On macOS it does not remove the focus from the window. #### `win.isFocusable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be focused. #### `win.setParentWindow(parent)` * `parent` BaseWindow | null Sets `parent` as current window's parent window, passing `null` will turn current window into a top-level window. #### `win.getParentWindow()` Returns `BaseWindow | null` - The parent window or `null` if there is no parent. #### `win.getChildWindows()` Returns `BaseWindow[]` - All child windows. #### `win.setAutoHideCursor(autoHide)` _macOS_ * `autoHide` boolean Controls whether to hide cursor when typing. #### `win.selectPreviousTab()` _macOS_ Selects the previous tab when native tabs are enabled and there are other tabs in the window. #### `win.selectNextTab()` _macOS_ Selects the next tab when native tabs are enabled and there are other tabs in the window. #### `win.showAllTabs()` _macOS_ Shows or hides the tab overview when native tabs are enabled. #### `win.mergeAllWindows()` _macOS_ Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window. #### `win.moveTabToNewWindow()` _macOS_ Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window. #### `win.toggleTabBar()` _macOS_ Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window. #### `win.addTabbedWindow(baseWindow)` _macOS_ * `baseWindow` BaseWindow Adds a window as a tab on this window, after the tab for the window instance. #### `win.setVibrancy(type)` _macOS_ * `type` string | null - Can be `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See the [macOS documentation][vibrancy-docs] for more details. Adds a vibrancy effect to the window. Passing `null` or an empty string will remove the vibrancy effect on the window. #### `win.setBackgroundMaterial(material)` _Windows_ * `material` string * `auto` - Let the Desktop Window Manager (DWM) automatically decide the system-drawn backdrop material for this window. This is the default. * `none` - Don't draw any system backdrop. * `mica` - Draw the backdrop material effect corresponding to a long-lived window. * `acrylic` - Draw the backdrop material effect corresponding to a transient window. * `tabbed` - Draw the backdrop material effect corresponding to a window with a tabbed title bar. This method sets the browser window's system-drawn background material, including behind the non-client area. See the [Windows documentation](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type) for more details. > [!NOTE] > This method is only supported on Windows 11 22H2 and up. #### `win.setWindowButtonPosition(position)` _macOS_ * `position` [Point](structures/point.md) | null Set a custom position for the traffic light buttons in frameless window. Passing `null` will reset the position to default. #### `win.getWindowButtonPosition()` _macOS_ Returns `Point | null` - The custom position for the traffic light buttons in frameless window, `null` will be returned when there is no custom position. #### `win.setTouchBar(touchBar)` _macOS_ * `touchBar` TouchBar | null Sets the touchBar layout for the current window. Specifying `null` or `undefined` clears the touch bar. This method only has an effect if the machine has a touch bar. > [!NOTE] > The TouchBar API is currently experimental and may change or be > removed in future Electron releases. #### `win.setTitleBarOverlay(options)` _Windows_ _Linux_ * `options` Object * `color` String (optional) - The CSS color of the Window Controls Overlay when enabled. * `symbolColor` String (optional) - The CSS color of the symbols on the Window Controls Overlay when enabled. * `height` Integer (optional) - The height of the title bar and Window Controls Overlay in pixels. On a Window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay. On Linux, the `symbolColor` is automatically calculated to have minimum accessible contrast to the `color` if not explicitly set. [quick-look]: https://en.wikipedia.org/wiki/Quick_Look [vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc [window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [window-session-end-event]:../api/structures/window-session-end-event.md --- # BrowserView > [!NOTE] > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. A `BrowserView` can be used to embed additional web content into a [`BrowserWindow`](browser-window.md). It is like a child window, except that it is positioned relative to its owning window. It is meant to be an alternative to the `webview` tag. ## Class: BrowserView > Create and control views. > [!NOTE] > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. Process: [Main](../glossary.md#main-process) This module cannot be used until the `ready` event of the `app` module is emitted. > [!WARNING] > Electron's built-in classes cannot be subclassed in user code. > For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules). ### Example ```js // In the main process. const { app, BrowserView, BrowserWindow } = require('electron') app.whenReady().then(() => { const win = new BrowserWindow({ width: 800, height: 600 }) const view = new BrowserView() win.setBrowserView(view) view.setBounds({ x: 0, y: 0, width: 300, height: 300 }) view.webContents.loadURL('https://electronjs.org') }) ``` ### `new BrowserView([options])` _Experimental_ _Deprecated_ * `options` Object (optional) * `webPreferences` [WebPreferences](structures/web-preferences.md?inline) (optional) - Settings of web page's features. ### Instance Properties Objects created with `new BrowserView` have the following properties: #### `view.webContents` _Experimental_ _Deprecated_ A [`WebContents`](web-contents.md) object owned by this view. ### Instance Methods Objects created with `new BrowserView` have the following instance methods: #### `view.setAutoResize(options)` _Experimental_ _Deprecated_ * `options` Object * `width` boolean (optional) - If `true`, the view's width will grow and shrink together with the window. `false` by default. * `height` boolean (optional) - If `true`, the view's height will grow and shrink together with the window. `false` by default. * `horizontal` boolean (optional) - If `true`, the view's x position and width will grow and shrink proportionally with the window. `false` by default. * `vertical` boolean (optional) - If `true`, the view's y position and height will grow and shrink proportionally with the window. `false` by default. #### `view.setBounds(bounds)` _Experimental_ _Deprecated_ * `bounds` [Rectangle](structures/rectangle.md) Resizes and moves the view to the supplied bounds relative to the window. #### `view.getBounds()` _Experimental_ _Deprecated_ Returns [`Rectangle`](structures/rectangle.md) The `bounds` of this BrowserView instance as `Object`. #### `view.setBackgroundColor(color)` _Experimental_ _Deprecated_ * `color` string - Color in Hex, RGB, ARGB, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type. Examples of valid `color` values: * Hex * `#fff` (RGB) * `#ffff` (ARGB) * `#ffffff` (RRGGBB) * `#ffffffff` (AARRGGBB) * RGB * `rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)` * e.g. `rgb(255, 255, 255)` * RGBA * `rgba\(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)\)` * e.g. `rgba(255, 255, 255, 1.0)` * HSL * `hsl\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)` * e.g. `hsl(200, 20%, 50%)` * HSLA * `hsla\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)` * e.g. `hsla(200, 20%, 50%, 0.5)` * Color name * Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148) * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * e.g. `blueviolet` or `red` > [!NOTE] > Hex format with alpha takes `AARRGGBB` or `ARGB`, _not_ `RRGGBBAA` or `RGB`. --- # BrowserWindow > Create and control browser windows. Process: [Main](../glossary.md#main-process) This module cannot be used until the `ready` event of the `app` module is emitted. ```js // In the main process. const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) // Load a remote URL win.loadURL('https://github.com') // Or load a local HTML file win.loadFile('index.html') ``` ## Window customization The `BrowserWindow` class exposes various ways to modify the look and behavior of your app's windows. For more details, see the [Window Customization](../tutorial/window-customization.md) tutorial. ## Showing the window gracefully When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without a visual flash, there are two solutions for different situations. ### Using the `ready-to-show` event While loading the page, the `ready-to-show` event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash: ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow({ show: false }) win.once('ready-to-show', () => { win.show() }) ``` This event is usually emitted after the `did-finish-load` event, but for pages with many remote resources, it may be emitted before the `did-finish-load` event. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` ### Setting the `backgroundColor` property For a complex app, the `ready-to-show` event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a `backgroundColor` close to your app's background: ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow({ backgroundColor: '#2e2c29' }) win.loadURL('https://github.com') ``` Note that even for apps that use `ready-to-show` event, it is still recommended to set `backgroundColor` to make the app feel more native. Some examples of valid `backgroundColor` values include: ```js const win = new BrowserWindow() win.setBackgroundColor('hsl(230, 100%, 50%)') win.setBackgroundColor('rgb(255, 145, 145)') win.setBackgroundColor('#ff00a3') win.setBackgroundColor('blueviolet') ``` For more information about these color types see valid options in [win.setBackgroundColor](browser-window.md#winsetbackgroundcolorbackgroundcolor). ## Parent and child windows By using `parent` option, you can create child windows: ```js const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top }) child.show() top.show() ``` The `child` window will always show on top of the `top` window. ## Modal windows A modal window is a child window that disables parent window. To create a modal window, you have to set both the `parent` and `modal` options: ```js const { BrowserWindow } = require('electron') const top = new BrowserWindow() const child = new BrowserWindow({ parent: top, modal: true, show: false }) child.loadURL('https://github.com') child.once('ready-to-show', () => { child.show() }) ``` ## Page visibility The [Page Visibility API][page-visibility-api] works as follows: * On all platforms, the visibility state tracks whether the window is hidden/minimized or not. * Additionally, on macOS, the visibility state also tracks the window occlusion state. If the window is occluded (i.e. fully covered) by another window, the visibility state will be `hidden`. On other platforms, the visibility state will be `hidden` only when the window is minimized or explicitly hidden with `win.hide()`. * If a `BrowserWindow` is created with `show: false`, the initial visibility state will be `visible` despite the window actually being hidden. * If `backgroundThrottling` is disabled, the visibility state will remain `visible` even if the window is minimized, occluded, or hidden. It is recommended that you pause expensive operations when the visibility state is `hidden` in order to minimize power consumption. ## Platform notices * On macOS modal windows will be displayed as sheets attached to the parent window. * On macOS the child windows will keep the relative position to parent window when parent window moves, while on Windows and Linux child windows will not move. * On Linux the type of modal windows will be changed to `dialog`. * On Linux many desktop environments do not support hiding a modal window. * On Wayland (Linux) it is generally not possible to programmatically resize windows after creation, or to position, move, focus, or blur windows without user input. If your app needs these capabilities, run it in Xwayland by appending the flag `--ozone-platform=x11`. ## Class: BrowserWindow extends `BaseWindow` > Create and control browser windows. Process: [Main](../glossary.md#main-process) `BrowserWindow` is an [EventEmitter][event-emitter]. It creates a new `BrowserWindow` with native properties as set by the `options`. > [!WARNING] > Electron's built-in classes cannot be subclassed in user code. > For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules). ### `new BrowserWindow([options])` * `options` [BrowserWindowConstructorOptions](structures/browser-window-options.md?inline) (optional) ### Instance Events Objects created with `new BrowserWindow` emit the following events: > [!NOTE] > Some events are only available on specific operating systems and are labeled as such. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Emitted when the document changed its title, calling `event.preventDefault()` will prevent the native window's title from changing. `explicitSet` is false when title is synthesized from file URL. #### Event: 'close' Returns: * `event` Event Emitted when the window is going to be closed. It's emitted before the `beforeunload` and `unload` event of the DOM. Calling `event.preventDefault()` will cancel the close. Usually you would want to use the `beforeunload` handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than `undefined` would cancel the close. For example: ```js window.onbeforeunload = (e) => { console.log('I do not want to be closed') // Unlike usual browsers that a message box will be prompted to users, returning // a non-void value will silently cancel the close. // It is recommended to use the dialog API to let the user confirm closing the // application. e.returnValue = false } ``` > [!NOTE] > There is a subtle difference between the behaviors of `window.onbeforeunload = handler` and > `window.addEventListener('beforeunload', handler)`. It is recommended to always set the > `event.returnValue` explicitly, instead of only returning a value, as the former works more > consistently within Electron. #### Event: 'closed' Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more. #### Event: 'query-session-end' _Windows_ Returns: * `event` [WindowSessionEndEvent][window-session-end-event] Emitted when a session is about to end due to a shutdown, machine restart, or user log-off. Calling `event.preventDefault()` can delay the system shutdown, though it’s generally best to respect the user’s choice to end the session. However, you may choose to use it if ending the session puts the user at risk of losing data. #### Event: 'session-end' _Windows_ Returns: * `event` [WindowSessionEndEvent][window-session-end-event] Emitted when a session is about to end due to a shutdown, machine restart, or user log-off. Once this event fires, there is no way to prevent the session from ending. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'blur' Emitted when the window loses focus. #### Event: 'focus' Emitted when the window gains focus. #### Event: 'show' Emitted when the window is shown. #### Event: 'hide' Emitted when the window is hidden. #### Event: 'ready-to-show' Emitted when the web page has been rendered (while not being shown) and window can be displayed without a visual flash. Please note that using this event implies that the renderer will be considered "visible" and paint even though `show` is false. This event will never fire if you use `paintWhenInitiallyHidden: false` #### Event: 'maximize' Emitted when window is maximized. #### Event: 'unmaximize' Emitted when the window exits from a maximized state. #### Event: 'minimize' Emitted when the window is minimized. #### Event: 'restore' Emitted when the window is restored from a minimized state. #### Event: 'will-resize' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Size the window is being resized to. * `details` Object * `edge` (string) - The edge of the window being dragged for resizing. Can be `bottom`, `left`, `right`, `top-left`, `top-right`, `bottom-left` or `bottom-right`. Emitted before the window is resized. Calling `event.preventDefault()` will prevent the window from being resized. Note that this is only emitted when the window is being resized manually. Resizing the window with `setBounds`/`setSize` will not emit this event. The possible values and behaviors of the `edge` option are platform dependent. Possible values are: * On Windows, possible values are `bottom`, `top`, `left`, `right`, `top-left`, `top-right`, `bottom-left`, `bottom-right`. * On macOS, possible values are `bottom` and `right`. * The value `bottom` is used to denote vertical resizing. * The value `right` is used to denote horizontal resizing. #### Event: 'resize' Emitted after the window has been resized. #### Event: 'resized' _macOS_ _Windows_ Emitted once when the window has finished being resized. This is usually emitted when the window has been resized manually. On macOS, resizing the window with `setBounds`/`setSize` and setting the `animate` parameter to `true` will also emit this event once resizing has finished. #### Event: 'will-move' _macOS_ _Windows_ Returns: * `event` Event * `newBounds` [Rectangle](structures/rectangle.md) - Location the window is being moved to. Emitted before the window is moved. On Windows, calling `event.preventDefault()` will prevent the window from being moved. Note that this is only emitted when the window is being moved manually. Moving the window with `setPosition`/`setBounds`/`center` will not emit this event. #### Event: 'move' Emitted when the window is being moved to a new position. #### Event: 'moved' _macOS_ _Windows_ Emitted once when the window is moved to a new position. > [!NOTE] > On macOS, this event is an alias of `move`. #### Event: 'enter-full-screen' Emitted when the window enters a full-screen state. #### Event: 'leave-full-screen' Emitted when the window leaves a full-screen state. #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'always-on-top-changed' Returns: * `event` Event * `isAlwaysOnTop` boolean Emitted when the window is set or unset to show always on top of other windows. #### Event: 'app-command' _Windows_ _Linux_ Returns: * `event` Event * `command` string Emitted when an [App Command](https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-appcommand) is invoked. These are typically related to keyboard media keys or browser commands, as well as the "Back" button built into some mice on Windows. Commands are lowercased, underscores are replaced with hyphens, and the `APPCOMMAND_` prefix is stripped off. e.g. `APPCOMMAND_BROWSER_BACKWARD` is emitted as `browser-backward`. ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.on('app-command', (e, cmd) => { // Navigate the window back when the user hits their mouse back button if (cmd === 'browser-backward' && win.webContents.canGoBack()) { win.webContents.goBack() } }) ``` The following app commands are explicitly supported on Linux: * `browser-backward` * `browser-forward` #### Event: 'swipe' _macOS_ Returns: * `event` Event * `direction` string Emitted on 3-finger swipe. Possible directions are `up`, `right`, `down`, `left`. The method underlying this event is built to handle older macOS-style trackpad swiping, where the content on the screen doesn't move with the swipe. Most macOS trackpads are not configured to allow this kind of swiping anymore, so in order for it to emit properly the 'Swipe between pages' preference in `System Preferences > Trackpad > More Gestures` must be set to 'Swipe with two or three fingers'. #### Event: 'rotate-gesture' _macOS_ Returns: * `event` Event * `rotation` Float Emitted on trackpad rotation gesture. Continually emitted until rotation gesture is ended. The `rotation` value on each emission is the angle in degrees rotated since the last emission. The last emitted event upon a rotation gesture will always be of value `0`. Counter-clockwise rotation values are positive, while clockwise ones are negative. #### Event: 'sheet-begin' _macOS_ Emitted when the window opens a sheet. #### Event: 'sheet-end' _macOS_ Emitted when the window has closed a sheet. #### Event: 'new-window-for-tab' _macOS_ Emitted when the native new tab button is clicked. #### Event: 'system-context-menu' _Windows_ _Linux_ Returns: * `event` Event * `point` [Point](structures/point.md) - The screen coordinates where the context menu was triggered. Emitted when the system context menu is triggered on the window, this is normally only triggered when the user right clicks on the non-client area of your window. This is the window titlebar or any area you have declared as `-webkit-app-region: drag` in a frameless window. Calling `event.preventDefault()` will prevent the menu from being displayed. To convert `point` to DIP, use [`screen.screenToDipPoint(point)`](./screen.md#screenscreentodippointpoint-windows-linux). ### Static Methods The `BrowserWindow` class has the following static methods: #### `BrowserWindow.getAllWindows()` Returns `BrowserWindow[]` - An array of all opened browser windows. #### `BrowserWindow.getFocusedWindow()` Returns `BrowserWindow | null` - The window that is focused in this application, otherwise returns `null`. #### `BrowserWindow.fromWebContents(webContents)` * `webContents` [WebContents](web-contents.md) Returns `BrowserWindow | null` - The window that owns the given `webContents` or `null` if the contents are not owned by a window. #### `BrowserWindow.fromBrowserView(browserView)` _Deprecated_ * `browserView` [BrowserView](browser-view.md) > [!NOTE] > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. Returns `BrowserWindow | null` - The window that owns the given `browserView`. If the given view is not attached to any window, returns `null`. #### `BrowserWindow.fromId(id)` * `id` Integer Returns `BrowserWindow | null` - The window with the given `id`. ### Instance Properties Objects created with `new BrowserWindow` have the following properties: ```js const { BrowserWindow } = require('electron') // In this example `win` is our instance const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('https://github.com') ``` #### `win.webContents` _Readonly_ A `WebContents` object this window owns. All web page related events and operations will be done via it. See the [`webContents` documentation](web-contents.md) for its methods and events. #### `win.id` _Readonly_ A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application. #### `win.tabbingIdentifier` _macOS_ _Readonly_ A `string` (optional) property that is equal to the `tabbingIdentifier` passed to the `BrowserWindow` constructor or `undefined` if none was set. #### `win.autoHideMenuBar` _Linux_ _Windows_ A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, setting this property to `true` won't hide it immediately. #### `win.simpleFullScreen` A `boolean` property that determines whether the window is in simple (pre-Lion) fullscreen mode. #### `win.fullScreen` A `boolean` property that determines whether the window is in fullscreen mode. #### `win.focusable` _Windows_ _macOS_ A `boolean` property that determines whether the window is focusable. #### `win.visibleOnAllWorkspaces` _macOS_ _Linux_ A `boolean` property that determines whether the window is visible on all workspaces. > [!NOTE] > Always returns false on Windows. #### `win.shadow` A `boolean` property that determines whether the window has a shadow. #### `win.menuBarVisible` _Windows_ _Linux_ A `boolean` property that determines whether the menu bar should be visible. > [!NOTE] > If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.kiosk` A `boolean` property that determines whether the window is in kiosk mode. #### `win.documentEdited` _macOS_ A `boolean` property that specifies whether the window’s document has been edited. The icon in title bar will become gray when set to `true`. #### `win.representedFilename` _macOS_ A `string` property that determines the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.title` A `string` property that determines the title of the native window. > [!NOTE] > The title of the web page can be different from the title of the native window. #### `win.minimizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually minimized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.maximizable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually maximized by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.fullScreenable` A `boolean` property that determines whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.resizable` A `boolean` property that determines whether the window can be manually resized by user. #### `win.closable` _macOS_ _Windows_ A `boolean` property that determines whether the window can be manually closed by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.movable` _macOS_ _Windows_ A `boolean` property that determines Whether the window can be moved by user. On Linux the setter is a no-op, although the getter returns `true`. #### `win.excludedFromShownWindowsMenu` _macOS_ A `boolean` property that determines whether the window is excluded from the application’s Windows menu. `false` by default. ```js @ts-expect-error=[11] const win = new BrowserWindow({ height: 600, width: 600 }) const template = [ { role: 'windowmenu' } ] win.excludedFromShownWindowsMenu = true const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ``` #### `win.accessibleTitle` A `string` property that defines an alternative title provided only to accessibility tools such as screen readers. This string is not directly visible to users. #### `win.snapped` _Windows_ _Readonly_ A `boolean` property that indicates whether the window is arranged via [Snap.](https://support.microsoft.com/en-us/windows/snap-your-windows-885a9b1e-a983-a3b1-16cd-c531795e6241) ### Instance Methods Objects created with `new BrowserWindow` have the following instance methods: > [!NOTE] > Some methods are only available on specific operating systems and are > labeled as such. #### `win.destroy()` Force closing the window, the `unload` and `beforeunload` event won't be emitted for the web page, and `close` event will also not be emitted for this window, but it guarantees the `closed` event will be emitted. #### `win.close()` Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the [close event](#event-close). #### `win.focus()` Focuses on the window. On Wayland (Linux), the desktop environment may show a notification or flash the app icon if the window or app is not already focused. #### `win.blur()` Removes focus from the window. Not supported on Wayland (Linux). #### `win.isFocused()` Returns `boolean` - Whether the window is focused. #### `win.isDestroyed()` Returns `boolean` - Whether the window is destroyed. #### `win.show()` Shows and gives focus to the window. #### `win.showInactive()` Shows the window but doesn't focus on it. Not supported on Wayland (Linux). #### `win.hide()` Hides the window. #### `win.isVisible()` Returns `boolean` - Whether the window is visible to the user in the foreground of the app. #### `win.isModal()` Returns `boolean` - Whether current window is a modal window. #### `win.maximize()` Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. #### `win.unmaximize()` Unmaximizes the window. #### `win.isMaximized()` Returns `boolean` - Whether the window is maximized. #### `win.minimize()` Minimizes the window. On some platforms the minimized window will be shown in the Dock. #### `win.restore()` Restores the window from minimized state to its previous state. #### `win.isMinimized()` Returns `boolean` - Whether the window is minimized. #### `win.setFullScreen(flag)` * `flag` boolean Sets whether the window should be in fullscreen mode. > [!NOTE] > On macOS, fullscreen transitions take place asynchronously. If further actions depend on the fullscreen state, use the ['enter-full-screen'](browser-window.md#event-enter-full-screen) or ['leave-full-screen'](browser-window.md#event-leave-full-screen) events. #### `win.isFullScreen()` Returns `boolean` - Whether the window is in fullscreen mode. > [!NOTE] > On macOS, fullscreen transitions take place asynchronously. When querying for a BrowserWindow's fullscreen status, you should ensure that either the ['enter-full-screen'](browser-window.md#event-enter-full-screen) or ['leave-full-screen'](browser-window.md#event-leave-full-screen) events have been emitted. #### `win.setSimpleFullScreen(flag)` _macOS_ * `flag` boolean Enters or leaves simple fullscreen mode. Simple fullscreen mode emulates the native fullscreen behavior found in versions of macOS prior to Lion (10.7). #### `win.isSimpleFullScreen()` _macOS_ Returns `boolean` - Whether the window is in simple (pre-Lion) fullscreen mode. #### `win.isNormal()` Returns `boolean` - Whether the window is in normal state (not maximized, not minimized, not in fullscreen mode). #### `win.setAspectRatio(aspectRatio[, extraSize])` * `aspectRatio` Float - The aspect ratio to maintain for some portion of the content view. * `extraSize` [Size](structures/size.md) (optional) _macOS_ - The extra size not to be included while maintaining the aspect ratio. This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window's size and its content size. Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and \{ width: 40, height: 50 \}. The second argument doesn't care where the extra width and height are within the content view--only that they exist. Sum any extra width and height areas you have within the overall content view. The aspect ratio is not respected when window is resized programmatically with APIs like `win.setSize`. To reset an aspect ratio, pass 0 as the `aspectRatio` value: `win.setAspectRatio(0)`. #### `win.setBackgroundColor(backgroundColor)` * `backgroundColor` string - Color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. The alpha channel is optional for the hex type. Examples of valid `backgroundColor` values: * Hex * #fff (shorthand RGB) * #ffff (shorthand ARGB) * #ffffff (RGB) * #ffffffff (ARGB) * RGB * `rgb\(([\d]+),\s*([\d]+),\s*([\d]+)\)` * e.g. rgb(255, 255, 255) * RGBA * `rgba\(([\d]+),\s*([\d]+),\s*([\d]+),\s*([\d.]+)\)` * e.g. rgba(255, 255, 255, 1.0) * HSL * `hsl\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)` * e.g. hsl(200, 20%, 50%) * HSLA * `hsla\((-?[\d.]+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)` * e.g. hsla(200, 20%, 50%, 0.5) * Color name * Options are listed in [SkParseColor.cpp](https://source.chromium.org/chromium/chromium/src/+/main:third_party/skia/src/utils/SkParseColor.cpp;l=11-152;drc=eea4bf52cb0d55e2a39c828b017c80a5ee054148) * Similar to CSS Color Module Level 3 keywords, but case-sensitive. * e.g. `blueviolet` or `red` Sets the background color of the window. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). #### `win.previewFile(path[, displayName])` _macOS_ * `path` string - The absolute path to the file to preview with QuickLook. This is important as Quick Look uses the file name and file extension on the path to determine the content type of the file to open. * `displayName` string (optional) - The name of the file to display on the Quick Look modal view. This is purely visual and does not affect the content type of the file. Defaults to `path`. Uses [Quick Look][quick-look] to preview a file at a given path. #### `win.closeFilePreview()` _macOS_ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` * `bounds` Partial\<[Rectangle](structures/rectangle.md)\> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. On Wayland (Linux), has the same limitations as `setSize` and `setPosition`. ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() // set all bounds properties win.setBounds({ x: 440, y: 225, width: 800, height: 600 }) // set a single bounds property win.setBounds({ width: 100 }) // { x: 440, y: 225, width: 100, height: 600 } console.log(win.getBounds()) ``` > [!NOTE] > On macOS, the y-coordinate value cannot be smaller than the [Tray](tray.md) height. The tray height has changed over time and depends on the operating system, but is between 20-40px. Passing a value lower than the tray height will result in a window that is flush to the tray. #### `win.getBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window as `Object`. > [!NOTE] > On macOS, the y-coordinate value returned will be at minimum the [Tray](tray.md) height. For example, calling `win.setBounds({ x: 25, y: 20, width: 800, height: 600 })` with a tray height of 38 means that `win.getBounds()` will return `{ x: 25, y: 38, width: 800, height: 600 }`. #### `win.getBackgroundColor()` Returns `string` - Gets the background color of the window in Hex (`#RRGGBB`) format. See [Setting `backgroundColor`](#setting-the-backgroundcolor-property). > [!NOTE] > The alpha value is _not_ returned alongside the red, green, and blue values. #### `win.setContentBounds(bounds[, animate])` * `bounds` [Rectangle](structures/rectangle.md) * `animate` boolean (optional) _macOS_ Resizes and moves the window's client area (e.g. the web page) to the supplied bounds. On Wayland (Linux), has the same limitations as `setContentSize` and `setPosition`. #### `win.getContentBounds()` Returns [`Rectangle`](structures/rectangle.md) - The `bounds` of the window's client area as `Object`. #### `win.getNormalBounds()` Returns [`Rectangle`](structures/rectangle.md) - Contains the window bounds of the normal state > [!NOTE] > Whatever the current state of the window (maximized, minimized or in fullscreen), this function always returns the position and size of the window in normal state. In normal state, `getBounds` and `getNormalBounds` return the same [`Rectangle`](structures/rectangle.md). #### `win.setEnabled(enable)` * `enable` boolean Disable or enable the window. #### `win.isEnabled()` Returns `boolean` - whether the window is enabled. #### `win.setSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window to `width` and `height`. If `width` or `height` are below any set minimum size constraints the window will snap to its minimum size. On Wayland (Linux), may not work as some window managers restrict programmatic window resizing. #### `win.getSize()` Returns `Integer[]` - Contains the window's width and height. #### `win.setContentSize(width, height[, animate])` * `width` Integer * `height` Integer * `animate` boolean (optional) _macOS_ Resizes the window's client area (e.g. the web page) to `width` and `height`. On Wayland (Linux), may not work as some window managers restrict programmatic window resizing. #### `win.getContentSize()` Returns `Integer[]` - Contains the window's client area's width and height. #### `win.setMinimumSize(width, height)` * `width` Integer * `height` Integer Sets the minimum size of window to `width` and `height`. #### `win.getMinimumSize()` Returns `Integer[]` - Contains the window's minimum width and height. #### `win.setMaximumSize(width, height)` * `width` Integer * `height` Integer Sets the maximum size of window to `width` and `height`. #### `win.getMaximumSize()` Returns `Integer[]` - Contains the window's maximum width and height. #### `win.setResizable(resizable)` * `resizable` boolean Sets whether the window can be manually resized by the user. #### `win.isResizable()` Returns `boolean` - Whether the window can be manually resized by the user. #### `win.setMovable(movable)` _macOS_ _Windows_ * `movable` boolean Sets whether the window can be moved by user. On Linux does nothing. #### `win.isMovable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be moved by user. On Linux always returns `true`. #### `win.setMinimizable(minimizable)` _macOS_ _Windows_ * `minimizable` boolean Sets whether the window can be manually minimized by user. On Linux does nothing. #### `win.isMinimizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually minimized by the user. On Linux always returns `true`. #### `win.setMaximizable(maximizable)` _macOS_ _Windows_ * `maximizable` boolean Sets whether the window can be manually maximized by user. On Linux does nothing. #### `win.isMaximizable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually maximized by user. On Linux always returns `true`. #### `win.setFullScreenable(fullscreenable)` * `fullscreenable` boolean Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.isFullScreenable()` Returns `boolean` - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. #### `win.setClosable(closable)` _macOS_ _Windows_ * `closable` boolean Sets whether the window can be manually closed by user. On Linux does nothing. #### `win.isClosable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be manually closed by user. On Linux always returns `true`. #### `win.setHiddenInMissionControl(hidden)` _macOS_ * `hidden` boolean Sets whether the window will be hidden when the user toggles into mission control. #### `win.isHiddenInMissionControl()` _macOS_ Returns `boolean` - Whether the window will be hidden when the user toggles into mission control. #### `win.setAlwaysOnTop(flag[, level][, relativeLevel])` * `flag` boolean * `level` string (optional) _macOS_ _Windows_ - Values include `normal`, `floating`, `torn-off-menu`, `modal-panel`, `main-menu`, `status`, `pop-up-menu`, `screen-saver`, and ~~`dock`~~ (Deprecated). The default is `floating` when `flag` is true. The `level` is reset to `normal` when the flag is false. Note that from `floating` to `status` included, the window is placed below the Dock on macOS and below the taskbar on Windows. From `pop-up-menu` to a higher it is shown above the Dock on macOS and above the taskbar on Windows. See the [macOS docs][window-levels] for more details. * `relativeLevel` Integer (optional) _macOS_ - The number of layers higher to set this window relative to the given `level`. The default is `0`. Note that Apple discourages setting levels higher than 1 above `screen-saver`. Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on. #### `win.isAlwaysOnTop()` Returns `boolean` - Whether the window is always on top of other windows. #### `win.moveAbove(mediaSourceId)` * `mediaSourceId` string - Window id in the format of DesktopCapturerSource's id. For example "window:1869:0". Moves window above the source window in the sense of z-order. If the `mediaSourceId` is not of type window or if the window does not exist then this method throws an error. #### `win.moveTop()` Moves window to top(z-order) regardless of focus. Not supported on Wayland (Linux). #### `win.center()` Moves window to the center of the screen. Not supported on Wayland (Linux). #### `win.setPosition(x, y[, animate])` * `x` Integer * `y` Integer * `animate` boolean (optional) _macOS_ Moves window to `x` and `y`. Not supported on Wayland (Linux). #### `win.getPosition()` Returns `Integer[]` - Contains the window's current position. #### `win.setTitle(title)` * `title` string Changes the title of native window to `title`. #### `win.getTitle()` Returns `string` - The title of the native window. > [!NOTE] > The title of the web page can be different from the title of the native > window. #### `win.setSheetOffset(offsetY[, offsetX])` _macOS_ * `offsetY` Float * `offsetX` Float (optional) Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example: ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() const toolbarRect = document.getElementById('toolbar').getBoundingClientRect() win.setSheetOffset(toolbarRect.height) ``` #### `win.flashFrame(flag)` * `flag` boolean Starts or stops flashing the window to attract user's attention. #### `win.setSkipTaskbar(skip)` _macOS_ _Windows_ * `skip` boolean Makes the window not show in the taskbar. #### `win.setKiosk(flag)` * `flag` boolean Enters or leaves kiosk mode. #### `win.isKiosk()` Returns `boolean` - Whether the window is in kiosk mode. #### `win.isTabletMode()` _Windows_ Returns `boolean` - Whether the window is in Windows 10 tablet mode. Since Windows 10 users can [use their PC as tablet](https://support.microsoft.com/en-us/help/17210/windows-10-use-your-pc-like-a-tablet), under this mode apps can choose to optimize their UI for tablets, such as enlarging the titlebar and hiding titlebar buttons. This API returns whether the window is in tablet mode, and the `resize` event can be be used to listen to changes to tablet mode. #### `win.getMediaSourceId()` Returns `string` - Window id in the format of DesktopCapturerSource's id. For example "window:1324:0". More precisely the format is `window:id:other_id` where `id` is `HWND` on Windows, `CGWindowID` (`uint64_t`) on macOS and `Window` (`unsigned long`) on Linux. `other_id` is used to identify web contents (tabs) so within the same top level window. #### `win.getNativeWindowHandle()` Returns `Buffer` - The platform-specific handle of the window. The native type of the handle is `HWND` on Windows, `NSView*` on macOS, and `Window` (`unsigned long`) on Linux. #### `win.hookWindowMessage(message, callback)` _Windows_ * `message` Integer * `callback` Function * `wParam` Buffer - The `wParam` provided to the WndProc * `lParam` Buffer - The `lParam` provided to the WndProc Hooks a windows message. The `callback` is called when the message is received in the WndProc. #### `win.isWindowMessageHooked(message)` _Windows_ * `message` Integer Returns `boolean` - `true` or `false` depending on whether the message is hooked. #### `win.unhookWindowMessage(message)` _Windows_ * `message` Integer Unhook the window message. #### `win.unhookAllWindowMessages()` _Windows_ Unhooks all of the window messages. #### `win.setRepresentedFilename(filename)` _macOS_ * `filename` string Sets the pathname of the file the window represents, and the icon of the file will show in window's title bar. #### `win.getRepresentedFilename()` _macOS_ Returns `string` - The pathname of the file the window represents. #### `win.setDocumentEdited(edited)` _macOS_ * `edited` boolean Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to `true`. #### `win.isDocumentEdited()` _macOS_ Returns `boolean` - Whether the window's document has been edited. #### `win.focusOnWebView()` #### `win.blurWebView()` #### `win.capturePage([rect, opts])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture * `opts` Object (optional) * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. Default is `false`. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Default is `false`. Returns `Promise` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. If the page is not visible, `rect` may be empty. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. #### `win.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer URL. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n" * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base URL (with trailing path separator) for files to be loaded by the data URL. This is needed only if the specified `url` is a data URL and needs to load other files. Returns `Promise` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors. If the existing page has a beforeUnload handler, [`did-fail-load`](web-contents.md#event-did-fail-load) will be called unless [`will-prevent-unload`](web-contents.md#event-did-fail-load) is handled. Same as [`webContents.loadURL(url[, options])`](web-contents.md#contentsloadurlurl-options). The `url` can be a remote address (e.g. `http://`) or a path to a local HTML file using the `file://` protocol. To ensure that file URLs are properly formatted, it is recommended to use Node's [`url.format`](https://nodejs.org/api/url.html#url_url_format_urlobject) method: ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() const url = require('node:url').format({ protocol: 'file', slashes: true, pathname: require('node:path').join(__dirname, 'index.html') }) win.loadURL(url) ``` You can load a URL using a `POST` request with URL-encoded data by doing the following: ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('http://localhost:8000/post', { postData: [{ type: 'rawData', bytes: Buffer.from('hello=world') }], extraHeaders: 'Content-Type: application/x-www-form-urlencoded' }) ``` #### `win.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record\ (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Same as `webContents.loadFile`, `filePath` should be a path to an HTML file relative to the root of your application. See the `webContents` docs for more information. #### `win.reload()` Same as `webContents.reload`. #### `win.setMenu(menu)` _Linux_ _Windows_ * `menu` Menu | null Sets the `menu` as the window's menu bar. #### `win.removeMenu()` _Linux_ _Windows_ Remove the window's menu bar. #### `win.setProgressBar(progress[, options])` * `progress` Double * `options` Object (optional) * `mode` string _Windows_ - Mode for the progress bar. Can be `none`, `normal`, `indeterminate`, `error` or `paused`. Sets progress value in progress bar. Valid range is \[0, 1.0]. Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1. On Linux platform, only supports Unity desktop environment, you need to specify the `*.desktop` file name to `desktopName` field in `package.json`. By default, it will assume `{app.name}.desktop`. On Windows, a mode can be passed. Accepted values are `none`, `normal`, `indeterminate`, `error`, and `paused`. If you call `setProgressBar` without a mode set (but with a value within the valid range), `normal` will be assumed. #### `win.setOverlayIcon(overlay, description)` _Windows_ * `overlay` [NativeImage](native-image.md) | null - the icon to display on the bottom right corner of the taskbar icon. If this parameter is `null`, the overlay is cleared * `description` string - a description that will be provided to Accessibility screen readers Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user. #### `win.invalidateShadow()` _macOS_ Invalidates the window shadow so that it is recomputed based on the current window shape. `BrowserWindows` that are transparent can sometimes leave behind visual artifacts on macOS. This method can be used to clear these artifacts when, for example, performing an animation. #### `win.setHasShadow(hasShadow)` * `hasShadow` boolean Sets whether the window should have a shadow. #### `win.hasShadow()` Returns `boolean` - Whether the window has a shadow. #### `win.setOpacity(opacity)` _Windows_ _macOS_ * `opacity` number - between 0.0 (fully transparent) and 1.0 (fully opaque) Sets the opacity of the window. On Linux, does nothing. Out of bound number values are clamped to the \[0, 1] range. #### `win.getOpacity()` Returns `number` - between 0.0 (fully transparent) and 1.0 (fully opaque). On Linux, always returns 1. #### `win.setShape(rects)` _Windows_ _Linux_ _Experimental_ * `rects` [Rectangle[]](structures/rectangle.md) - Sets a shape on the window. Passing an empty list reverts the window to being rectangular. Setting a window shape determines the area within the window where the system permits drawing and user interaction. Outside of the given region, no pixels will be drawn and no mouse events will be registered. Mouse events outside of the region will not be received by that window, but will fall through to whatever is behind the window. #### `win.setThumbarButtons(buttons)` _Windows_ * `buttons` [ThumbarButton[]](structures/thumbar-button.md) Returns `boolean` - Whether the buttons were added successfully Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a `boolean` object indicates whether the thumbnail has been added successfully. The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform's limitation. But you can call the API with an empty array to clean the buttons. The `buttons` is an array of `Button` objects: * `Button` Object * `icon` [NativeImage](native-image.md) - The icon showing in thumbnail toolbar. * `click` Function * `tooltip` string (optional) - The text of the button's tooltip. * `flags` string[] (optional) - Control specific states and behaviors of the button. By default, it is `['enabled']`. The `flags` is an array that can include following `string`s: * `enabled` - The button is active and available to the user. * `disabled` - The button is disabled. It is present, but has a visual state indicating it will not respond to user action. * `dismissonclick` - When the button is clicked, the thumbnail window closes immediately. * `nobackground` - Do not draw a button border, use only the image. * `hidden` - The button is not shown to the user. * `noninteractive` - The button is enabled but not interactive; no pressed button state is drawn. This value is intended for instances where the button is used in a notification. #### `win.setThumbnailClip(region)` _Windows_ * `region` [Rectangle](structures/rectangle.md) - Region of the window Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: `{ x: 0, y: 0, width: 0, height: 0 }`. #### `win.setThumbnailToolTip(toolTip)` _Windows_ * `toolTip` string Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. #### `win.setAppDetails(options)` _Windows_ * `options` Object * `appId` string (optional) - Window's [App User Model ID](https://learn.microsoft.com/en-us/windows/win32/shell/appids). It has to be set, otherwise the other options will have no effect. * `appIconPath` string (optional) - Window's [Relaunch Icon](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchiconresource). * `appIconIndex` Integer (optional) - Index of the icon in `appIconPath`. Ignored when `appIconPath` is not set. Default is `0`. * `relaunchCommand` string (optional) - Window's [Relaunch Command](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchcommand). * `relaunchDisplayName` string (optional) - Window's [Relaunch Display Name](https://learn.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-relaunchdisplaynameresource). Sets the properties for the window's taskbar button. > [!NOTE] > `relaunchCommand` and `relaunchDisplayName` must always be set > together. If one of those properties is not set, then neither will be used. #### `win.setAccentColor(accentColor)` _Windows_ * `accentColor` boolean | string | null - The accent color for the window. By default, follows user preference in System Settings. To reset to system default, pass `null`. Sets the system accent color and highlighting of active window border. The `accentColor` parameter accepts the following values: * **Color string** - Like `true`, but sets a custom accent color using standard CSS color formats (Hex, RGB, RGBA, HSL, HSLA, or named colors). Alpha values in RGBA/HSLA formats are ignored and the color is treated as fully opaque. * **`true`** - Enable accent color highlighting for the window with the system accent color regardless of whether accent colors are enabled for windows in System `Settings.` * **`false`** - Disable accent color highlighting for the window regardless of whether accent colors are currently enabled for windows in System Settings. * **`null`** - Reset window accent color behavior to follow behavior set in System Settings. Examples: ```js const win = new BrowserWindow({ frame: false }) // Set red accent color. win.setAccentColor('#ff0000') // RGB format (alpha ignored if present). win.setAccentColor('rgba(255,0,0,0.5)') // Enable accent color, using the color specified in System Settings. win.setAccentColor(true) // Disable accent color. win.setAccentColor(false) // Reset window accent color behavior to follow behavior set in System Settings. win.setAccentColor(null) ``` #### `win.getAccentColor()` _Windows_ Returns `string | boolean` - the system accent color and highlighting of active window border in Hex RGB format. If a color has been set for the window that differs from the system accent color, the window accent color will be returned. Otherwise, a boolean will be returned, with `true` indicating that the window uses the global system accent color, and `false` indicating that accent color highlighting is disabled for this window. #### `win.showDefinitionForSelection()` _macOS_ Same as `webContents.showDefinitionForSelection()`. #### `win.setIcon(icon)` _Windows_ _Linux_ * `icon` [NativeImage](native-image.md) | string Changes window icon. #### `win.setWindowButtonVisibility(visible)` _macOS_ * `visible` boolean Sets whether the window traffic light buttons should be visible. #### `win.setAutoHideMenuBar(hide)` _Windows_ _Linux_ * `hide` boolean Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single `Alt` key. If the menu bar is already visible, calling `setAutoHideMenuBar(true)` won't hide it immediately. #### `win.isMenuBarAutoHide()` _Windows_ _Linux_ Returns `boolean` - Whether menu bar automatically hides itself. #### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_ * `visible` boolean Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single `Alt` key. #### `win.isMenuBarVisible()` _Windows_ _Linux_ Returns `boolean` - Whether the menu bar is visible. #### `win.isSnapped()` _Windows_ Returns `boolean` - whether the window is arranged via [Snap.](https://support.microsoft.com/en-us/windows/snap-your-windows-885a9b1e-a983-a3b1-16cd-c531795e6241) The window is snapped via buttons shown when the mouse is hovered over window maximize button, or by dragging it to the edges of the screen. #### `win.setVisibleOnAllWorkspaces(visible[, options])` _macOS_ _Linux_ * `visible` boolean * `options` Object (optional) * `visibleOnFullScreen` boolean (optional) _macOS_ - Sets whether the window should be visible above fullscreen windows. * `skipTransformProcessType` boolean (optional) _macOS_ - Calling setVisibleOnAllWorkspaces will by default transform the process type between UIElementApplication and ForegroundApplication to ensure the correct behavior. However, this will hide the window and dock for a short time every time it is called. If your window is already of type UIElementApplication, you can bypass this transformation by passing true to skipTransformProcessType. Sets whether the window should be visible on all workspaces. > [!NOTE] > This API does nothing on Windows. #### `win.isVisibleOnAllWorkspaces()` _macOS_ _Linux_ Returns `boolean` - Whether the window is visible on all workspaces. > [!NOTE] > This API always returns false on Windows. #### `win.setIgnoreMouseEvents(ignore[, options])` * `ignore` boolean * `options` Object (optional) * `forward` boolean (optional) _macOS_ _Windows_ - If true, forwards mouse move messages to Chromium, enabling mouse related events such as `mouseleave`. Only used when `ignore` is true. If `ignore` is false, forwarding is always disabled regardless of this value. Makes the window ignore all mouse events. All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events. #### `win.setContentProtection(enable)` _macOS_ _Windows_ * `enable` boolean Prevents the window contents from being captured by other apps. On Windows, it calls [`SetWindowDisplayAffinity`](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowdisplayaffinity) with `WDA_EXCLUDEFROMCAPTURE`. For Windows 10 version 2004 and up the window will be removed from capture entirely, older Windows versions behave as if `WDA_MONITOR` is applied capturing a black window. On macOS, it sets the `NSWindow`'s [`sharingType`](https://developer.apple.com/documentation/appkit/nswindow/sharingtype-swift.property?language=objc) to [`NSWindowSharingNone`](https://developer.apple.com/documentation/appkit/nswindow/sharingtype-swift.enum/none?language=objc). Unfortunately, due to an intentional change in macOS, newer Mac applications that use `ScreenCaptureKit` will capture your window despite `win.setContentProtection(true)`. See [here](https://github.com/electron/electron/issues/48258#issuecomment-3269893618). #### `win.isContentProtected()` _macOS_ _Windows_ Returns `boolean` - whether or not content protection is currently enabled. #### `win.setFocusable(focusable)` _macOS_ _Windows_ * `focusable` boolean Changes whether the window can be focused. On macOS it does not remove the focus from the window. #### `win.isFocusable()` _macOS_ _Windows_ Returns `boolean` - Whether the window can be focused. #### `win.setParentWindow(parent)` * `parent` BrowserWindow | null Sets `parent` as current window's parent window, passing `null` will turn current window into a top-level window. #### `win.getParentWindow()` Returns `BrowserWindow | null` - The parent window or `null` if there is no parent. #### `win.getChildWindows()` Returns `BrowserWindow[]` - All child windows. #### `win.setAutoHideCursor(autoHide)` _macOS_ * `autoHide` boolean Controls whether to hide cursor when typing. #### `win.selectPreviousTab()` _macOS_ Selects the previous tab when native tabs are enabled and there are other tabs in the window. #### `win.selectNextTab()` _macOS_ Selects the next tab when native tabs are enabled and there are other tabs in the window. #### `win.showAllTabs()` _macOS_ Shows or hides the tab overview when native tabs are enabled. #### `win.mergeAllWindows()` _macOS_ Merges all windows into one window with multiple tabs when native tabs are enabled and there is more than one open window. #### `win.moveTabToNewWindow()` _macOS_ Moves the current tab into a new window if native tabs are enabled and there is more than one tab in the current window. #### `win.toggleTabBar()` _macOS_ Toggles the visibility of the tab bar if native tabs are enabled and there is only one tab in the current window. #### `win.addTabbedWindow(browserWindow)` _macOS_ * `browserWindow` BrowserWindow Adds a window as a tab on this window, after the tab for the window instance. #### `win.setVibrancy(type[, options])` _macOS_ * `type` string | null - Can be `titlebar`, `selection`, `menu`, `popover`, `sidebar`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. See the [macOS documentation][vibrancy-docs] for more details. * `options` Object (optional) * `animationDuration` number (optional) - if greater than zero, the change to vibrancy will be animated over the given duration (in milliseconds). Adds a vibrancy effect to the browser window. Passing `null` or an empty string will remove the vibrancy effect on the window. The `animationDuration` parameter only animates fading in or fading out the vibrancy effect. Animating between different types of vibrancy is not supported. #### `win.setBackgroundMaterial(material)` _Windows_ * `material` string * `auto` - Let the Desktop Window Manager (DWM) automatically decide the system-drawn backdrop material for this window. This is the default. * `none` - Don't draw any system backdrop. * `mica` - Draw the backdrop material effect corresponding to a long-lived window. * `acrylic` - Draw the backdrop material effect corresponding to a transient window. * `tabbed` - Draw the backdrop material effect corresponding to a window with a tabbed title bar. This method sets the browser window's system-drawn background material, including behind the non-client area. See the [Windows documentation](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type) for more details. > [!NOTE] > This method is only supported on Windows 11 22H2 and up. #### `win.setWindowButtonPosition(position)` _macOS_ * `position` [Point](structures/point.md) | null Set a custom position for the traffic light buttons in frameless window. Passing `null` will reset the position to default. #### `win.getWindowButtonPosition()` _macOS_ Returns `Point | null` - The custom position for the traffic light buttons in frameless window, `null` will be returned when there is no custom position. #### `win.setTouchBar(touchBar)` _macOS_ * `touchBar` TouchBar | null Sets the touchBar layout for the current window. Specifying `null` or `undefined` clears the touch bar. This method only has an effect if the machine has a touch bar. > [!NOTE] > The TouchBar API is currently experimental and may change or be > removed in future Electron releases. #### `win.setBrowserView(browserView)` _Experimental_ _Deprecated_ * `browserView` [BrowserView](browser-view.md) | null - Attach `browserView` to `win`. If there are other `BrowserView`s attached, they will be removed from this window. > [!WARNING] > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.getBrowserView()` _Experimental_ _Deprecated_ Returns `BrowserView | null` - The `BrowserView` attached to `win`. Returns `null` if one is not attached. Throws an error if multiple `BrowserView`s are attached. > [!WARNING] > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.addBrowserView(browserView)` _Experimental_ _Deprecated_ * `browserView` [BrowserView](browser-view.md) Replacement API for setBrowserView supporting work with multi browser views. > [!WARNING] > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.removeBrowserView(browserView)` _Experimental_ _Deprecated_ * `browserView` [BrowserView](browser-view.md) > [!WARNING] > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.setTopBrowserView(browserView)` _Experimental_ _Deprecated_ * `browserView` [BrowserView](browser-view.md) Raises `browserView` above other `BrowserView`s attached to `win`. Throws an error if `browserView` is not attached to `win`. > [!WARNING] > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.getBrowserViews()` _Experimental_ _Deprecated_ Returns `BrowserView[]` - a sorted by z-index array of all BrowserViews that have been attached with `addBrowserView` or `setBrowserView`. The top-most BrowserView is the last element of the array. > [!WARNING] > The `BrowserView` class is deprecated, and replaced by the new > [`WebContentsView`](web-contents-view.md) class. #### `win.setTitleBarOverlay(options)` _Windows_ _Linux_ * `options` Object * `color` String (optional) - The CSS color of the Window Controls Overlay when enabled. * `symbolColor` String (optional) - The CSS color of the symbols on the Window Controls Overlay when enabled. * `height` Integer (optional) - The height of the title bar and Window Controls Overlay in pixels. On a window with Window Controls Overlay already enabled, this method updates the style of the title bar overlay. On Linux, the `symbolColor` is automatically calculated to have minimum accessible contrast to the `color` if not explicitly set. [page-visibility-api]: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API [quick-look]: https://en.wikipedia.org/wiki/Quick_Look [vibrancy-docs]: https://developer.apple.com/documentation/appkit/nsvisualeffectview?preferredLanguage=objc [window-levels]: https://developer.apple.com/documentation/appkit/nswindow/level [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [window-session-end-event]:../api/structures/window-session-end-event.md --- ## Class: ClientRequest > Make HTTP/HTTPS requests. Process: [Main](../glossary.md#main-process), [Utility](../glossary.md#utility-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ `ClientRequest` implements the [Writable Stream](https://nodejs.org/api/stream.html#stream_writable_streams) interface and is therefore an [EventEmitter][event-emitter]. ### `new ClientRequest(options)` * `options` (Object | string) - If `options` is a string, it is interpreted as the request URL. If it is an object, it is expected to fully specify an HTTP request via the following properties: * `method` string (optional) - The HTTP request method. Defaults to the GET method. * `url` string (optional) - The request URL. Must be provided in the absolute form with the protocol scheme specified as http or https. * `headers` Record\ (optional) - Headers to be sent with the request. * `session` Session (optional) - The [`Session`](session.md) instance with which the request is associated. * `partition` string (optional) - The name of the [`partition`](session.md) with which the request is associated. Defaults to the empty string. The `session` option supersedes `partition`. Thus if a `session` is explicitly specified, `partition` is ignored. * `bypassCustomProtocolHandlers` boolean (optional) - When set to `true`, custom protocol handlers registered for the request's URL scheme will not be called. This allows forwarding an intercepted request to the built-in handler. [webRequest](web-request.md) handlers will still be triggered when bypassing custom protocols. Defaults to `false`. * `credentials` string (optional) - Can be `include`, `omit` or `same-origin`. Whether to send [credentials](https://fetch.spec.whatwg.org/#credentials) with this request. If set to `include`, credentials from the session associated with the request will be used. If set to `omit`, credentials will not be sent with the request (and the `'login'` event will not be triggered in the event of a 401). If set to `same-origin`, `origin` must also be specified. This matches the behavior of the [fetch](https://fetch.spec.whatwg.org/#concept-request-credentials-mode) option of the same name. If this option is not specified, authentication data from the session will be sent, and cookies will not be sent (unless `useSessionCookies` is set). * `useSessionCookies` boolean (optional) - Whether to send cookies with this request from the provided session. If `credentials` is specified, this option has no effect. Default is `false`. * `protocol` string (optional) - Can be `http:` or `https:`. The protocol scheme in the form 'scheme:'. Defaults to 'http:'. * `host` string (optional) - The server host provided as a concatenation of the hostname and the port number 'hostname:port'. * `hostname` string (optional) - The server host name. * `port` Integer (optional) - The server's listening port number. * `path` string (optional) - The path part of the request URL. * `redirect` string (optional) - Can be `follow`, `error` or `manual`. The redirect mode for this request. When mode is `error`, any redirection will be aborted. When mode is `manual` the redirection will be cancelled unless [`request.followRedirect`](#requestfollowredirect) is invoked synchronously during the [`redirect`](#event-redirect) event. Defaults to `follow`. * `origin` string (optional) - The origin URL of the request. * `referrerPolicy` string (optional) - can be "", `no-referrer`, `no-referrer-when-downgrade`, `origin`, `origin-when-cross-origin`, `unsafe-url`, `same-origin`, `strict-origin`, or `strict-origin-when-cross-origin`. Defaults to `strict-origin-when-cross-origin`. * `cache` string (optional) - can be `default`, `no-store`, `reload`, `no-cache`, `force-cache` or `only-if-cached`. * `priority` string (optional) - can be `throttled`, `idle`, `lowest`, `low`, `medium`, or `highest`. Defaults to `idle`. * `priorityIncremental` boolean (optional) - the incremental loading flag as part of HTTP extensible priorities (RFC 9218). Default is `true`. `options` properties such as `protocol`, `host`, `hostname`, `port` and `path` strictly follow the Node.js model as described in the [URL](https://nodejs.org/api/url.html) module. For instance, we could have created the same request to 'github.com' as follows: ```js const request = net.request({ method: 'GET', protocol: 'https:', hostname: 'github.com', port: 443, path: '/' }) ``` ### Instance Events #### Event: 'response' Returns: * `response` [IncomingMessage](incoming-message.md) - An object representing the HTTP response message. #### Event: 'login' Returns: * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when an authenticating proxy is asking for user credentials. The `callback` function is expected to be called back with user credentials: * `username` string * `password` string ```js @ts-type={request:Electron.ClientRequest} request.on('login', (authInfo, callback) => { callback('username', 'password') }) ``` Providing empty credentials will cancel the request and report an authentication error on the response object: ```js @ts-type={request:Electron.ClientRequest} request.on('response', (response) => { console.log(`STATUS: ${response.statusCode}`) response.on('error', (error) => { console.log(`ERROR: ${JSON.stringify(error)}`) }) }) request.on('login', (authInfo, callback) => { callback() }) ``` #### Event: 'finish' Emitted just after the last chunk of the `request`'s data has been written into the `request` object. #### Event: 'abort' Emitted when the `request` is aborted. The `abort` event will not be fired if the `request` is already closed. #### Event: 'error' Returns: * `error` Error - an error object providing some information about the failure. Emitted when the `net` module fails to issue a network request. Typically when the `request` object emits an `error` event, a `close` event will subsequently follow and no response object will be provided. #### Event: 'close' Emitted as the last event in the HTTP request-response transaction. The `close` event indicates that no more events will be emitted on either the `request` or `response` objects. #### Event: 'redirect' Returns: * `statusCode` Integer * `method` string * `redirectUrl` string * `responseHeaders` Record\ Emitted when the server returns a redirect response (e.g. 301 Moved Permanently). Calling [`request.followRedirect`](#requestfollowredirect) will continue with the redirection. If this event is handled, [`request.followRedirect`](#requestfollowredirect) must be called **synchronously**, otherwise the request will be cancelled. ### Instance Properties #### `request.chunkedEncoding` A `boolean` specifying whether the request will use HTTP chunked transfer encoding or not. Defaults to false. The property is readable and writable, however it can be set only before the first write operation as the HTTP headers are not yet put on the wire. Trying to set the `chunkedEncoding` property after the first write will throw an error. Using chunked encoding is strongly recommended if you need to send a large request body as data will be streamed in small chunks instead of being internally buffered inside Electron process memory. ### Instance Methods #### `request.setHeader(name, value)` * `name` string - An extra HTTP header name. * `value` string - An extra HTTP header value. Adds an extra HTTP header. The header name will be issued as-is without lowercasing. It can be called only before first write. Calling this method after the first write will throw an error. If the passed value is not a `string`, its `toString()` method will be called to obtain the final value. Certain headers are restricted from being set by apps. These headers are listed below. More information on restricted headers can be found in [Chromium's header utils](https://source.chromium.org/chromium/chromium/src/+/main:services/network/public/cpp/header_util.cc;drc=1562cab3f1eda927938f8f4a5a91991fefde66d3;bpv=1;bpt=1;l=22). * `Content-Length` * `Host` * `Trailer` or `Te` * `Upgrade` * `Cookie2` * `Keep-Alive` * `Transfer-Encoding` Additionally, setting the `Connection` header to the value `upgrade` is also disallowed. #### `request.getHeader(name)` * `name` string - Specify an extra header name. Returns `string` - The value of a previously set extra header name. #### `request.removeHeader(name)` * `name` string - Specify an extra header name. Removes a previously set extra header name. This method can be called only before first write. Trying to call it after the first write will throw an error. #### `request.write(chunk[, encoding][, callback])` * `chunk` (string | Buffer) - A chunk of the request body's data. If it is a string, it is converted into a Buffer using the specified encoding. * `encoding` string (optional) - Used to convert string chunks into Buffer objects. Defaults to 'utf-8'. * `callback` Function (optional) - Called after the write operation ends. `callback` is essentially a dummy function introduced in the purpose of keeping similarity with the Node.js API. It is called asynchronously in the next tick after `chunk` content have been delivered to the Chromium networking layer. Contrary to the Node.js implementation, it is not guaranteed that `chunk` content have been flushed on the wire before `callback` is called. Adds a chunk of data to the request body. The first write operation may cause the request headers to be issued on the wire. After the first write operation, it is not allowed to add or remove a custom header. #### `request.end([chunk][, encoding][, callback])` * `chunk` (string | Buffer) (optional) * `encoding` string (optional) * `callback` Function (optional) Returns `this`. Sends the last chunk of the request data. Subsequent write or end operations will not be allowed. The `finish` event is emitted just after the end operation. #### `request.abort()` Cancels an ongoing HTTP transaction. If the request has already emitted the `close` event, the abort operation will have no effect. Otherwise an ongoing event will emit `abort` and `close` events. Additionally, if there is an ongoing response object,it will emit the `aborted` event. #### `request.followRedirect()` Continues any pending redirection. Can only be called during a `'redirect'` event. #### `request.getUploadProgress()` Returns `Object`: * `active` boolean - Whether the request is currently active. If this is false no other properties will be set * `started` boolean - Whether the upload has started. If this is false both `current` and `total` will be set to 0. * `current` Integer - The number of bytes that have been uploaded so far * `total` Integer - The number of bytes that will be uploaded this request You can use this method in conjunction with `POST` requests to get the progress of a file upload or other data transfer. [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter --- # clipboard > Perform copy and paste operations on the system clipboard. Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) _Deprecated_ (non-sandboxed only) > [!NOTE] > Using the `clipoard` API from the renderer process is deprecated. > [!IMPORTANT] > If you want to call this API from a renderer process, > place the API call in your preload script and > [expose](../tutorial/context-isolation.md#after-context-isolation-enabled) it using the > [`contextBridge`](context-bridge.md) API. On Linux, there is also a `selection` clipboard. To manipulate it you need to pass `selection` to each method: ```js const { clipboard } = require('electron') clipboard.writeText('Example string', 'selection') console.log(clipboard.readText('selection')) ``` ## Methods The `clipboard` module has the following methods: > [!NOTE] > Experimental APIs are marked as such and could be removed in future. ### `clipboard.readText([type])` * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Returns `string` - The content in the clipboard as plain text. ```js const { clipboard } = require('electron') clipboard.writeText('hello i am a bit of text!') const text = clipboard.readText() console.log(text) // hello i am a bit of text!' ``` ### `clipboard.writeText(text[, type])` * `text` string * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Writes the `text` into the clipboard as plain text. ```js const { clipboard } = require('electron') const text = 'hello i am a bit of text!' clipboard.writeText(text) ``` ### `clipboard.readHTML([type])` * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Returns `string` - The content in the clipboard as markup. ```js const { clipboard } = require('electron') clipboard.writeHTML('Hi') const html = clipboard.readHTML() console.log(html) // Hi ``` ### `clipboard.writeHTML(markup[, type])` * `markup` string * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Writes `markup` to the clipboard. ```js const { clipboard } = require('electron') clipboard.writeHTML('Hi') ``` ### `clipboard.readImage([type])` * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Returns [`NativeImage`](native-image.md) - The image content in the clipboard. ### `clipboard.writeImage(image[, type])` * `image` [NativeImage](native-image.md) * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Writes `image` to the clipboard. ### `clipboard.readRTF([type])` * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Returns `string` - The content in the clipboard as RTF. ```js const { clipboard } = require('electron') clipboard.writeRTF('{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\nThis is some {\\b bold} text.\\par\n}') const rtf = clipboard.readRTF() console.log(rtf) // {\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\nThis is some {\\b bold} text.\\par\n} ``` ### `clipboard.writeRTF(text[, type])` * `text` string * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Writes the `text` into the clipboard in RTF. ```js const { clipboard } = require('electron') const rtf = '{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\nThis is some {\\b bold} text.\\par\n}' clipboard.writeRTF(rtf) ``` ### `clipboard.readBookmark()` _macOS_ _Windows_ Returns `Object`: * `title` string * `url` string Returns an Object containing `title` and `url` keys representing the bookmark in the clipboard. The `title` and `url` values will be empty strings when the bookmark is unavailable. The `title` value will always be empty on Windows. ### `clipboard.writeBookmark(title, url[, type])` _macOS_ _Windows_ * `title` string - Unused on Windows * `url` string * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Writes the `title` (macOS only) and `url` into the clipboard as a bookmark. > [!NOTE] > Most apps on Windows don't support pasting bookmarks into them so > you can use `clipboard.write` to write both a bookmark and fallback text to the > clipboard. ```js const { clipboard } = require('electron') clipboard.writeBookmark('Electron Homepage', 'https://electronjs.org') ``` ### `clipboard.readFindText()` _macOS_ Returns `string` - The text on the find pasteboard, which is the pasteboard that holds information about the current state of the active application’s find panel. This method uses synchronous IPC when called from the renderer process. The cached value is reread from the find pasteboard whenever the application is activated. ### `clipboard.writeFindText(text)` _macOS_ * `text` string Writes the `text` into the find pasteboard (the pasteboard that holds information about the current state of the active application’s find panel) as plain text. This method uses synchronous IPC when called from the renderer process. ### `clipboard.clear([type])` * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Clears the clipboard content. ### `clipboard.availableFormats([type])` * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Returns `string[]` - An array of supported formats for the clipboard `type`. ```js const { clipboard } = require('electron') const formats = clipboard.availableFormats() console.log(formats) // [ 'text/plain', 'text/html' ] ``` ### `clipboard.has(format[, type])` _Experimental_ * `format` string * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Returns `boolean` - Whether the clipboard supports the specified `format`. ```js const { clipboard } = require('electron') const hasFormat = clipboard.has('public/utf8-plain-text') console.log(hasFormat) // 'true' or 'false' ``` ### `clipboard.read(format)` _Experimental_ * `format` string Returns `string` - Reads `format` type from the clipboard. `format` should contain valid ASCII characters and have `/` separator. `a/c`, `a/bc` are valid formats while `/abc`, `abc/`, `a/`, `/a`, `a` are not valid. ### `clipboard.readBuffer(format)` _Experimental_ * `format` string Returns `Buffer` - Reads `format` type from the clipboard. ```js const { clipboard } = require('electron') const buffer = Buffer.from('this is binary', 'utf8') clipboard.writeBuffer('public/utf8-plain-text', buffer) const ret = clipboard.readBuffer('public/utf8-plain-text') console.log(buffer.equals(ret)) // true ``` ### `clipboard.writeBuffer(format, buffer[, type])` _Experimental_ * `format` string * `buffer` Buffer * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Writes the `buffer` into the clipboard as `format`. ```js const { clipboard } = require('electron') const buffer = Buffer.from('writeBuffer', 'utf8') clipboard.writeBuffer('public/utf8-plain-text', buffer) ``` ### `clipboard.write(data[, type])` * `data` Object * `text` string (optional) * `html` string (optional) * `image` [NativeImage](native-image.md) (optional) * `rtf` string (optional) * `bookmark` string (optional) - The title of the URL at `text`. * `type` string (optional) - Can be `selection` or `clipboard`; default is 'clipboard'. `selection` is only available on Linux. Writes `data` to the clipboard. ```js const { clipboard } = require('electron') clipboard.write({ text: 'test', html: 'Hi', rtf: '{\\rtf1\\utf8 text}', bookmark: 'a title' }) console.log(clipboard.readText()) // 'test' console.log(clipboard.readHTML()) // Hi console.log(clipboard.readRTF()) // '{\\rtf1\\utf8 text}' console.log(clipboard.readBookmark()) // { title: 'a title', url: 'test' } ``` --- # Supported Command Line Switches > Command line switches supported by Electron. You can use [app.commandLine.appendSwitch][append-switch] to append them in your app's main script before the [ready][ready] event of the [app][app] module is emitted: ```js const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1') app.whenReady().then(() => { // Your code here }) ``` ## Electron CLI Flags ### --auth-server-whitelist=`url` A comma-separated list of servers for which integrated authentication is enabled. For example: ```sh --auth-server-whitelist='*example.com, *foobar.com, *baz' ``` then any `url` ending with `example.com`, `foobar.com`, `baz` will be considered for integrated authentication. Without `*` prefix the URL has to match exactly. ### --auth-negotiate-delegate-whitelist=`url` A comma-separated list of servers for which delegation of user credentials is required. Without `*` prefix the URL has to match exactly. ### --disable-ntlm-v2 Disables NTLM v2 for POSIX platforms, no effect elsewhere. ### --disable-http-cache Disables the disk cache for HTTP requests. ### --disable-http2 Disable HTTP/2 and SPDY/3.1 protocols. ### --disable-geolocation _macOS_ Disables the Geolocation API. Permission requests for geolocation will be denied internally regardless of the decision made by a handler set via `session.setPermissionRequestHandler`. This functionality is currently implemented only for macOS. Has no effect on other platforms. ### --disable-renderer-backgrounding Prevents Chromium from lowering the priority of invisible pages' renderer processes. This flag is global to all renderer processes, if you only want to disable throttling in one window, you can take the hack of [playing silent audio][play-silent-audio]. ### --disk-cache-size=`size` Forces the maximum disk space to be used by the disk cache, in bytes. ### --enable-logging\[=file] Prints Chromium's logging to stderr (or a log file). The `ELECTRON_ENABLE_LOGGING` environment variable has the same effect as passing `--enable-logging`. Passing `--enable-logging` will result in logs being printed on stderr. Passing `--enable-logging=file` will result in logs being saved to the file specified by `--log-file=...`, or to `electron_debug.log` in the user-data directory if `--log-file` is not specified. > [!NOTE] > On Windows, logs from child processes cannot be sent to stderr. > Logging to a file is the most reliable way to collect logs on Windows. See also `--log-file`, `--log-level`, `--v`, and `--vmodule`. ### --force-fieldtrials=`trials` Field trials to be forcefully enabled or disabled. For example: `WebRTC-Audio-Red-For-Opus/Enabled/` ### --host-rules=`rules` _Deprecated_ A comma-separated list of `rules` that control how hostnames are mapped. For example: * `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1 * `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to "proxy". * `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will also force the port of the resulting socket address to be 77. * `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for "www.google.com". These mappings apply to the endpoint host in a net request (the TCP connect and host resolver in a direct connection, and the `CONNECT` in an HTTP proxy connection, and the endpoint host in a `SOCKS` proxy connection). **Deprecated:** Use the `--host-resolver-rules` switch instead. ### --host-resolver-rules=`rules` A comma-separated list of `rules` that control how hostnames are mapped. For example: * `MAP * 127.0.0.1` Forces all hostnames to be mapped to 127.0.0.1 * `MAP *.google.com proxy` Forces all google.com subdomains to be resolved to "proxy". * `MAP test.com [::1]:77` Forces "test.com" to resolve to IPv6 loopback. Will also force the port of the resulting socket address to be 77. * `MAP * baz, EXCLUDE www.google.com` Remaps everything to "baz", except for "www.google.com". These `rules` only apply to the host resolver. ### --ignore-certificate-errors Ignores certificate related errors. ### --ignore-connections-limit=`domains` Ignore the connections limit for `domains` list separated by `,`. ### --js-flags=`flags` Specifies the flags passed to the [V8 engine](https://v8.dev). In order to enable the `flags` in the main process, this switch must be passed on startup. ```sh $ electron --js-flags="--harmony_proxies --harmony_collections" your-app ``` Run `node --v8-options` or `electron --js-flags="--help"` in your terminal for the list of available flags. These can be used to enable early-stage JavaScript features, or log and manipulate garbage collection, among other things. For example, to trace V8 optimization and deoptimization: ```sh $ electron --js-flags="--trace-opt --trace-deopt" your-app ``` ### --lang Set a custom locale. ### --log-file=`path` If `--enable-logging` is specified, logs will be written to the given path. The parent directory must exist. Setting the `ELECTRON_LOG_FILE` environment variable is equivalent to passing this flag. If both are present, the command-line switch takes precedence. ### --log-net-log=`path` Enables net log events to be saved and writes them to `path`. ### --log-level=`N` Sets the verbosity of logging when used together with `--enable-logging`. `N` should be one of [Chrome's LogSeverities][severities]. Note that two complimentary logging mechanisms in Chromium -- `LOG()` and `VLOG()` -- are controlled by different switches. `--log-level` controls `LOG()` messages, while `--v` and `--vmodule` control `VLOG()` messages. So you may want to use a combination of these three switches depending on the granularity you want and what logging calls are made by the code you're trying to watch. See [Chromium Logging source][logging] for more information on how `LOG()` and `VLOG()` interact. Loosely speaking, `VLOG()` can be thought of as sub-levels / per-module levels inside `LOG(INFO)` to control the firehose of `LOG(INFO)` data. See also `--enable-logging`, `--log-level`, `--v`, and `--vmodule`. ### --no-proxy-server Don't use a proxy server and always make direct connections. Overrides any other proxy server flags that are passed. ### --no-sandbox Disables the Chromium [sandbox](https://www.chromium.org/developers/design-documents/sandbox). Forces renderer process and Chromium helper processes to run un-sandboxed. Should only be used for testing. ### --no-stdio-init Disable stdio initialization during node initialization. Used to avoid node initialization crash when the nul device is disabled on Windows platform. ### --proxy-bypass-list=`hosts` Instructs Electron to bypass the proxy server for the given semi-colon-separated list of hosts. This flag has an effect only if used in tandem with `--proxy-server`. For example: ```js const { app } = require('electron') app.commandLine.appendSwitch('proxy-bypass-list', ';*.google.com;*foo.com;1.2.3.4:5678') ``` Will use the proxy server for all hosts except for local addresses (`localhost`, `127.0.0.1` etc.), `google.com` subdomains, hosts that contain the suffix `foo.com` and anything at `1.2.3.4:5678`. ### --proxy-pac-url=`url` Uses the PAC script at the specified `url`. ### --proxy-server=`address:port` Use a specified proxy server, which overrides the system setting. This switch only affects requests with HTTP protocol, including HTTPS and WebSocket requests. It is also noteworthy that not all proxy servers support HTTPS and WebSocket requests. The proxy URL does not support username and password authentication [per Chromium issue](https://bugs.chromium.org/p/chromium/issues/detail?id=615947). ### --remote-debugging-port=`port` Enables remote debugging over HTTP on the specified `port`. ### --v=`log_level` Gives the default maximal active V-logging level; 0 is the default. Normally positive values are used for V-logging levels. This switch only works when `--enable-logging` is also passed. See also `--enable-logging`, `--log-level`, and `--vmodule`. ### --vmodule=`pattern` Gives the per-module maximal V-logging levels to override the value given by `--v`. E.g. `my_module=2,foo*=3` would change the logging level for all code in source files `my_module.*` and `foo*.*`. Any pattern containing a forward or backward slash will be tested against the whole pathname and not only the module. E.g. `*/foo/bar/*=2` would change the logging level for all code in the source files under a `foo/bar` directory. This switch only works when `--enable-logging` is also passed. See also `--enable-logging`, `--log-level`, and `--v`. ### --force_high_performance_gpu Force using discrete GPU when there are multiple GPUs available. ### --force_low_power_gpu Force using integrated GPU when there are multiple GPUs available. ### --xdg-portal-required-version=`version` Sets the minimum required version of XDG portal implementation to `version` in order to use the portal backend for file dialogs on linux. File dialogs will fallback to using gtk or kde depending on the desktop environment when the required version is unavailable. Current default is set to `3`. ## Node.js Flags Electron supports some of the [CLI flags][node-cli] supported by Node.js. > [!NOTE] > Passing unsupported command line switches to Electron when it is not running in `ELECTRON_RUN_AS_NODE` will have no effect. ### `--inspect-brk[=[host:]port]` Activate inspector on host:port and break at start of user script. Default host:port is 127.0.0.1:9229. Aliased to `--debug-brk=[host:]port`. #### `--inspect-brk-node[=[host:]port]` Activate inspector on `host:port` and break at start of the first internal JavaScript script executed when the inspector is available. Default `host:port` is `127.0.0.1:9229`. ### `--inspect-port=[host:]port` Set the `host:port` to be used when the inspector is activated. Useful when activating the inspector by sending the SIGUSR1 signal. Default host is `127.0.0.1`. Aliased to `--debug-port=[host:]port`. ### `--inspect[=[host:]port]` Activate inspector on `host:port`. Default is `127.0.0.1:9229`. V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug and profile Electron instances. The tools attach to Electron instances via a TCP port and communicate using the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/). See the [Debugging the Main Process][debugging-main-process] guide for more details. Aliased to `--debug[=[host:]port`. ### `--inspect-publish-uid=stderr,http` Specify ways of the inspector web socket url exposure. By default inspector websocket url is available in stderr and under /json/list endpoint on `http://host:port/json/list`. ### `--experimental-network-inspection` Enable support for devtools network inspector events, for visibility into requests made by the nodejs `http` and `https` modules. ### `--no-deprecation` Silence deprecation warnings. ### `--throw-deprecation` Throw errors for deprecations. ### `--trace-deprecation` Print stack traces for deprecations. ### `--trace-warnings` Print stack traces for process warnings (including deprecations). ### `--dns-result-order=order` Set the default value of the `verbatim` parameter in the Node.js [`dns.lookup()`](https://nodejs.org/api/dns.html#dnslookuphostname-options-callback) and [`dnsPromises.lookup()`](https://nodejs.org/api/dns.html#dnspromiseslookuphostname-options) functions. The value could be: * `ipv4first`: sets default `verbatim` `false`. * `verbatim`: sets default `verbatim` `true`. The default is `verbatim` and `dns.setDefaultResultOrder()` have higher priority than `--dns-result-order`. ### `--diagnostic-dir=directory` Set the directory to which all Node.js diagnostic output files are written. Defaults to current working directory. Affects the default output directory of [v8.setHeapSnapshotNearHeapLimit](https://nodejs.org/docs/latest/api/v8.html#v8setheapsnapshotnearheaplimitlimit). ### `--no-experimental-global-navigator` Disable exposition of [Navigator API][] on the global scope from Node.js. ## Chromium Flags There isn't a documented list of all Chromium switches, but there are a few ways to find them. The easiest way is through Chromium's flags page, which you can access at `about://flags`. These flags don't directly match switch names, but they show up in the process's command-line arguments. To see these arguments, enable a flag in `about://flags`, then go to `about://version` in Chromium. You'll find a list of command-line arguments, including `--flag-switches-begin --your --list --flag-switches-end`, which contains the list of your flag enabled switches. Most flags are included as part of `--enable-features=`, but some are standalone switches, like `--enable-experimental-web-platform-features`. A complete list of flags exists in [Chromium's flag metadata page](https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/flag-metadata.json), but this list includes platform, environment and GPU specific, expired and potentially non-functional flags, so many of them might not always work in every situation. Keep in mind that standalone switches can sometimes be split into individual features, so there's no fully complete list of switches. Finally, you'll need to ensure that the version of Chromium in Electron matches the version of the browser you're using to cross-reference the switches. [app]: app.md [append-switch]: command-line.md#commandlineappendswitchswitch-value [debugging-main-process]: ../tutorial/debugging-main-process.md [logging]: https://source.chromium.org/chromium/chromium/src/+/main:base/logging.h [node-cli]: https://nodejs.org/api/cli.html [play-silent-audio]: https://github.com/atom/atom/pull/9485/files [ready]: app.md#event-ready [severities]: https://source.chromium.org/chromium/chromium/src/+/main:base/logging.h?q=logging::LogSeverity&ss=chromium [Navigator API]: https://github.com/nodejs/node/blob/main/doc/api/globals.md#navigator --- ## Class: CommandLine > Manipulate the command line arguments for your app that Chromium reads Process: [Main](../glossary.md#main-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ The following example shows how to check if the `--disable-gpu` flag is set. ```js const { app } = require('electron') app.commandLine.hasSwitch('disable-gpu') ``` For more information on what kinds of flags and switches you can use, check out the [Command Line Switches](./command-line-switches.md) document. ### Instance Methods #### `commandLine.appendSwitch(switch[, value])` * `switch` string - A command-line switch, without the leading `--`. * `value` string (optional) - A value for the given switch. Append a switch (with optional `value`) to Chromium's command line. > [!NOTE] > This will not affect `process.argv`. The intended usage of this function is to > control Chromium's behavior. ```js const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') ``` #### `commandLine.appendArgument(value)` * `value` string - The argument to append to the command line. Append an argument to Chromium's command line. The argument will be quoted correctly. Switches will precede arguments regardless of appending order. If you're appending an argument like `--switch=value`, consider using `appendSwitch('switch', 'value')` instead. ```js const { app } = require('electron') app.commandLine.appendArgument('--enable-experimental-web-platform-features') ``` > [!NOTE] > This will not affect `process.argv`. The intended usage of this function is to > control Chromium's behavior. #### `commandLine.hasSwitch(switch)` * `switch` string - A command-line switch. Returns `boolean` - Whether the command-line switch is present. ```js const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') const hasPort = app.commandLine.hasSwitch('remote-debugging-port') console.log(hasPort) // true ``` #### `commandLine.getSwitchValue(switch)` * `switch` string - A command-line switch. Returns `string` - The command-line switch value. This function is meant to obtain Chromium command line switches. It is not meant to be used for application-specific command line arguments. For the latter, please use `process.argv`. ```js const { app } = require('electron') app.commandLine.appendSwitch('remote-debugging-port', '8315') const portValue = app.commandLine.getSwitchValue('remote-debugging-port') console.log(portValue) // '8315' ``` > [!NOTE] > When the switch is not present or has no value, it returns empty string. #### `commandLine.removeSwitch(switch)` * `switch` string - A command-line switch. Removes the specified switch from Chromium's command line. ```js 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 ``` > [!NOTE] > This will not affect `process.argv`. The intended usage of this function is to > control Chromium's behavior. --- # contentTracing > Collect tracing data from Chromium to find performance bottlenecks and slow operations. Process: [Main](../glossary.md#main-process) This module does not include a web interface. To view recorded traces, use [trace viewer][], available at `chrome://tracing` in Chrome. > [!NOTE] > You should not use this module until the `ready` event of the app > module is emitted. ```js 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) })() }) ``` ## Methods The `contentTracing` module has the following methods: ### `contentTracing.getCategories()` Returns `Promise` - resolves with an array of category groups once all child processes have acknowledged the `getCategories` request Get a set of category groups. The category groups can change as new code paths are reached. See also the [list of built-in tracing categories](https://chromium.googlesource.com/chromium/src/+/main/base/trace_event/builtin_categories.h). > **NOTE:** Electron adds a non-default tracing category called `"electron"`. > This category can be used to capture Electron-specific tracing events. ### `contentTracing.startRecording(options)` * `options` ([TraceConfig](structures/trace-config.md) | [TraceCategoriesAndOptions](structures/trace-categories-and-options.md)) Returns `Promise` - resolved once all child processes have acknowledged the `startRecording` request. Start recording on all processes. 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.stopRecording([resultFilePath])` * `resultFilePath` string (optional) Returns `Promise` - resolves with a path to a file that contains the traced data once all child processes have acknowledged the `stopRecording` request Stop recording on all processes. Child processes typically cache trace data and only rarely flush and send trace data back to the main process. This helps to minimize the runtime overhead of tracing since sending trace data over IPC can be an expensive operation. So, to end tracing, Chromium asynchronously asks all child processes to flush any pending trace data. Trace data will be written into `resultFilePath`. 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.getTraceBufferUsage()` Returns `Promise` - Resolves with an object containing the `value` and `percentage` of trace buffer maximum usage * `value` number * `percentage` number Get the maximum usage across processes of trace buffer as a percentage of the full state. [trace viewer]: https://chromium.googlesource.com/catapult/+/HEAD/tracing/README.md --- # contextBridge > Create a safe, bi-directional, synchronous bridge across isolated contexts Process: [Renderer](../glossary.md#renderer-process) An example of exposing an API to a renderer from an isolated preload script is given below: ```js // Preload (Isolated World) const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld( 'electron', { doThing: () => ipcRenderer.send('do-a-thing') } ) ``` ```js @ts-nocheck // Renderer (Main World) window.electron.doThing() ``` ## Glossary ### Main World The "Main World" is the JavaScript context that your main renderer code runs in. By default, the page you load in your renderer executes code in this world. ### Isolated World When `contextIsolation` is enabled in your `webPreferences` (this is the default behavior since Electron 12.0.0), your `preload` scripts run in an "Isolated World". You can read more about context isolation and what it affects in the [security](../tutorial/security.md#3-enable-context-isolation) docs. ## Methods The `contextBridge` module has the following methods: ### `contextBridge.exposeInMainWorld(apiKey, api)` * `apiKey` string - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]`. * `api` any - Your API, more information on what this API can be and how it works is available below. ### `contextBridge.exposeInIsolatedWorld(worldId, apiKey, api)` * `worldId` Integer - The ID of the world to inject the API into. `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. Using 999 would expose the object for preload context. We recommend using 1000+ while creating isolated world. * `apiKey` string - The key to inject the API onto `window` with. The API will be accessible on `window[apiKey]`. * `api` any - Your API, more information on what this API can be and how it works is available below. ### `contextBridge.executeInMainWorld(executionScript)` _Experimental_ * `executionScript` Object * `func` (...args: any[]) => any - A JavaScript function to execute. This function will be serialized which means that any bound parameters and execution context will be lost. * `args` any[] (optional) - An array of arguments to pass to the provided function. These arguments will be copied between worlds in accordance with [the table of supported types.](#parameter--error--return-type-support) Returns `any` - A copy of the resulting value from executing the function in the main world. [Refer to the table](#parameter--error--return-type-support) on how values are copied between worlds. ## Usage ### API The `api` provided to [`exposeInMainWorld`](#contextbridgeexposeinmainworldapikey-api) must be a `Function`, `string`, `number`, `Array`, `boolean`, or an object whose keys are strings and values are a `Function`, `string`, `number`, `Array`, `boolean`, or another nested object that meets the same conditions. `Function` values are proxied to the other context and all other values are **copied** and **frozen**. Any data / primitives sent in the API become immutable and updates on either side of the bridge do not result in an update on the other side. An example of a complex API is shown below: ```js const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld( 'electron', { doThing: () => ipcRenderer.send('do-a-thing'), myPromises: [Promise.resolve(), Promise.reject(new Error('whoops'))], anAsyncFunction: async () => 123, data: { myFlags: ['a', 'b', 'c'], bootTime: 1234 }, nestedAPI: { evenDeeper: { youCanDoThisAsMuchAsYouWant: { fn: () => ({ returnData: 123 }) } } } } ) ``` An example of `exposeInIsolatedWorld` is shown below: ```js const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInIsolatedWorld( 1004, 'electron', { doThing: () => ipcRenderer.send('do-a-thing') } ) ``` ```js @ts-nocheck // Renderer (In isolated world id1004) window.electron.doThing() ``` ### API Functions `Function` values that you bind through the `contextBridge` are proxied through Electron to ensure that contexts remain isolated. This results in some key limitations that we've outlined below. #### Parameter / Error / Return Type support Because parameters, errors and return values are **copied** when they are sent over the bridge, there are only certain types that can be used. At a high level, if the type you want to use can be serialized and deserialized into the same object it will work. A table of type support has been included below for completeness: | Type | Complexity | Parameter Support | Return Value Support | Limitations | | ---- | ---------- | ----------------- | -------------------- | ----------- | | `string` | Simple | ✅ | ✅ | N/A | | `number` | Simple | ✅ | ✅ | N/A | | `boolean` | Simple | ✅ | ✅ | N/A | | `Object` | Complex | ✅ | ✅ | Keys must be supported using only "Simple" types in this table. Values must be supported in this table. Prototype modifications are dropped. Sending custom classes will copy values but not the prototype. | | `Array` | Complex | ✅ | ✅ | Same limitations as the `Object` type | | `Error` | Complex | ✅ | ✅ | Errors that are thrown are also copied, this can result in the message and stack trace of the error changing slightly due to being thrown in a different context, and any custom properties on the Error object [will be lost](https://github.com/electron/electron/issues/25596) | | `Promise` | Complex | ✅ | ✅ | N/A | | `Function` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending classes or constructors will not work. | | [Cloneable Types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) | Simple | ✅ | ✅ | See the linked document on cloneable types | | `Element` | Complex | ✅ | ✅ | Prototype modifications are dropped. Sending custom elements will not work. | | `Blob` | Complex | ✅ | ✅ | N/A | | `VideoFrame` | Complex | ✅ | ✅ | N/A | | `Symbol` | N/A | ❌ | ❌ | Symbols cannot be copied across contexts so they are dropped | If the type you care about is not in the above table, it is probably not supported. ### Exposing ipcRenderer Attempting to send the entire `ipcRenderer` module as an object over the `contextBridge` will result in an empty object on the receiving side of the bridge. Sending over `ipcRenderer` in full can let any code send any message, which is a security footgun. To interact through `ipcRenderer`, provide a safe wrapper like below: ```js // Preload (Isolated World) contextBridge.exposeInMainWorld('electron', { onMyEventName: (callback) => ipcRenderer.on('MyEventName', (e, ...args) => callback(args)) }) ``` ```js @ts-nocheck // Renderer (Main World) window.electron.onMyEventName(data => { /* ... */ }) ``` ### Exposing Node Global Symbols The `contextBridge` can be used by the preload script to give your renderer access to Node APIs. The table of supported types described above also applies to Node APIs that you expose through `contextBridge`. Please note that many Node APIs grant access to local system resources. Be very cautious about which globals and APIs you expose to untrusted remote content. ```js const { contextBridge } = require('electron') const crypto = require('node:crypto') contextBridge.exposeInMainWorld('nodeCrypto', { sha256sum (data) { const hash = crypto.createHash('sha256') hash.update(data) return hash.digest('hex') } }) ``` --- ## Class: Cookies > Query and modify a session's cookies. Process: [Main](../glossary.md#main-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ Instances of the `Cookies` class are accessed by using `cookies` property of a `Session`. For example: ```js 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) }) // Set a cookie with the given cookie data; // may overwrite equivalent cookies if they exist. const cookie = { url: 'https://www.github.com', name: 'dummy_name', value: 'dummy' } session.defaultSession.cookies.set(cookie) .then(() => { // success }, (error) => { console.error(error) }) ``` ### Instance Events The following events are available on instances of `Cookies`: #### Event: 'changed' Returns: * `event` Event * `cookie` [Cookie](structures/cookie.md) - The cookie that was changed. * `cause` string - The cause of the change with one of the following values: * `explicit` - The cookie was changed directly by a consumer's action. * `overwrite` - The cookie was automatically removed due to an insert operation that overwrote it. * `expired` - The cookie was automatically removed as it expired. * `evicted` - The cookie was automatically evicted during garbage collection. * `expired-overwrite` - The cookie was overwritten with an already-expired expiration date. * `removed` boolean - `true` if the cookie was removed, `false` otherwise. Emitted when a cookie is changed because it was added, edited, removed, or expired. ### Instance Methods The following methods are available on instances of `Cookies`: #### `cookies.get(filter)` * `filter` Object * `url` string (optional) - Retrieves cookies which are associated with `url`. Empty implies retrieving cookies of all URLs. * `name` string (optional) - Filters cookies by name. * `domain` string (optional) - Retrieves cookies whose domains match or are subdomains of `domains`. * `path` string (optional) - Retrieves cookies whose path matches `path`. * `secure` boolean (optional) - Filters cookies by their Secure property. * `session` boolean (optional) - Filters out session or persistent cookies. * `httpOnly` boolean (optional) - Filters cookies by httpOnly. Returns `Promise` - A promise which resolves an array of cookie objects. Sends a request to get all cookies matching `filter`, and resolves a promise with the response. #### `cookies.set(details)` * `details` Object * `url` string - The URL to associate the cookie with. The promise will be rejected if the URL is invalid. * `name` string (optional) - The name of the cookie. Empty by default if omitted. * `value` string (optional) - The value of the cookie. Empty by default if omitted. * `domain` string (optional) - The domain of the cookie; this will be normalized with a preceding dot so that it's also valid for subdomains. Empty by default if omitted. * `path` string (optional) - The path of the cookie. Empty by default if omitted. * `secure` boolean (optional) - Whether the cookie should be marked as Secure. Defaults to false unless [Same Site=None](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure) attribute is used. * `httpOnly` boolean (optional) - Whether the cookie should be marked as HTTP only. Defaults to false. * `expirationDate` Double (optional) - The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted then the cookie becomes a session cookie and will not be retained between sessions. * `sameSite` string (optional) - The [Same Site](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_cookies) policy to apply to this cookie. Can be `unspecified`, `no_restriction`, `lax` or `strict`. Default is `lax`. Returns `Promise` - A promise which resolves when the cookie has been set Sets a cookie with `details`. #### `cookies.remove(url, name)` * `url` string - The URL associated with the cookie. * `name` string - The name of cookie to remove. Returns `Promise` - A promise which resolves when the cookie has been removed Removes the cookies matching `url` and `name` #### `cookies.flushStore()` Returns `Promise` - A promise which resolves when the cookie store has been flushed Writes any unwritten cookies data to disk Cookies written by any method will not be written to disk immediately, but will be written every 30 seconds or 512 operations Calling this method can cause the cookie to be written to disk immediately. --- ## CSS Rule: `-electron-corner-smoothing` > Smoothes out the corner rounding of the `border-radius` CSS rule. The rounded corners of elements with [the `border-radius` CSS rule](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius) can be smoothed out using the `-electron-corner-smoothing` CSS rule. This smoothness is very similar to Apple's "continuous" rounded corners in SwiftUI and Figma's "corner smoothing" control on design elements. ![There is a black rectangle on the left using simple rounded corners, and a blue rectangle on the right using smooth rounded corners. In between those rectangles is a magnified view of the same corner from both rectangles overlapping to show the subtle difference in shape.](../images/corner-smoothing-summary.svg) Integrating with the operating system and its design language is important to many desktop applications. The shape of a rounded corner can be a subtle detail to many users. However, aligning closely to the system's design language that users are familiar with makes the application's design feel familiar too. Beyond matching the design language of macOS, designers may decide to use smoother round corners for many other reasons. `-electron-corner-smoothing` affects the shape of borders, outlines, and shadows on the target element. Mirroring the behavior of `border-radius`, smoothing will gradually back off if an element's size is too small for the chosen value. The `-electron-corner-smoothing` CSS rule is **only implemented for Electron** and has no effect in browsers. Avoid using this rule outside of Electron. This CSS rule is considered experimental and may require migration in the future if replaced by a CSS standard. ### Example The following example shows the effect of corner smoothing at different percents. ```css .box { width: 128px; height: 128px; background-color: cornflowerblue; border-radius: 24px; -electron-corner-smoothing: var(--percent); /* Column header in table below. */ } ``` | 0% | 30% | 60% | 100% | | --- | --- | --- | --- | | ![A rectangle with round corners at 0% smoothness](../images/corner-smoothing-example-0.svg) | ![A rectangle with round corners at 30% smoothness](../images/corner-smoothing-example-30.svg) | ![A rectangle with round corners at 60% smoothness](../images/corner-smoothing-example-60.svg) | ![A rectangle with round corners at 100% smoothness](../images/corner-smoothing-example-100.svg) | ### Matching the system UI Use the `system-ui` keyword to match the smoothness to the OS design language. ```css .box { width: 128px; height: 128px; background-color: cornflowerblue; border-radius: 24px; -electron-corner-smoothing: system-ui; /* Match the system UI design. */ } ``` | OS: | macOS | Windows, Linux | | --- | --- | --- | | Value: | `60%` | `0%` | | Example: | ![A rectangle with round corners whose smoothness matches macOS](../images/corner-smoothing-example-60.svg) | ![A rectangle with round corners whose smoothness matches Windows and Linux](../images/corner-smoothing-example-0.svg) | ### Controlling availibility This CSS rule can be disabled using the Blink feature flag `ElectronCSSCornerSmoothing`. ```js const myWindow = new BrowserWindow({ // [...] webPreferences: { disableBlinkFeatures: 'ElectronCSSCornerSmoothing' // Disables the `-electron-corner-smoothing` CSS rule } }) ``` ### Formal reference * **Initial value**: `0%` * **Inherited**: No * **Animatable**: No * **Computed value**: As specified ```css -electron-corner-smoothing = | system-ui ``` --- # crashReporter > Submit crash reports to a remote server. Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) > [!IMPORTANT] > If you want to call this API from a renderer process with context isolation enabled, > place the API call in your preload script and > [expose](../tutorial/context-isolation.md#after-context-isolation-enabled) it using the > [`contextBridge`](context-bridge.md) API. The following is an example of setting up Electron to automatically submit crash reports to a remote server: ```js const { crashReporter } = require('electron') crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' }) ``` For setting up a server to accept and process crash reports, you can use following projects: * [socorro](https://github.com/mozilla-services/socorro) * [mini-breakpad-server](https://github.com/electron/mini-breakpad-server) > [!NOTE] > Electron uses Crashpad, not Breakpad, to collect and upload > crashes, but for the time being, the [upload protocol is the same](https://chromium.googlesource.com/crashpad/crashpad/+/HEAD/doc/overview_design.md#Upload-to-collection-server). Or use a 3rd party hosted solution: * [Backtrace](https://backtrace.io/electron/) * [Sentry](https://docs.sentry.io/clients/electron) * [BugSplat](https://www.bugsplat.com/docs/platforms/electron) * [Bugsnag](https://docs.bugsnag.com/platforms/electron/) Crash reports are stored temporarily before being uploaded in a directory underneath the app's user data directory, called 'Crashpad'. You can override this directory by calling `app.setPath('crashDumps', '/path/to/crashes')` before starting the crash reporter. Electron uses [crashpad](https://chromium.googlesource.com/crashpad/crashpad/+/refs/heads/main/README.md) to monitor and report crashes. ## Methods The `crashReporter` module has the following methods: ### `crashReporter.start(options)` * `options` Object * `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_ - Deprecated alias for `{ globalExtra: { _companyName: ... } }`. * `uploadToServer` boolean (optional) - Whether crash reports should be sent to the server. If false, crash reports will be collected and stored in the crashes directory, but not uploaded. Default is `true`. * `ignoreSystemCrashHandler` boolean (optional) - If true, crashes generated in the main process will not be forwarded to the system crash handler. Default is `false`. * `rateLimit` boolean (optional) _macOS_ _Windows_ - If true, limit the number of crashes uploaded to 1/hour. Default is `false`. * `compress` boolean (optional) - If true, crash reports will be compressed and uploaded with `Content-Encoding: gzip`. Default is `true`. * `extra` Record\ (optional) - Extra string key/value annotations that will be sent along with crash reports that are generated in the main process. Only string values are supported. Crashes generated in child processes will not include these extra parameters. To add extra parameters to crash reports generated from child processes, call [`addExtraParameter`](#crashreporteraddextraparameterkey-value) from the child process. * `globalExtra` Record\ (optional) - Extra string key/value annotations that will be sent along with any crash reports generated in any process. These annotations cannot be changed once the crash reporter has been started. If a key is present in both the global extra parameters and the process-specific extra parameters, then the global one will take precedence. By default, `productName` and the app version are included, as well as the Electron version. This method must be called before using any other `crashReporter` APIs. Once initialized this way, 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 the crash reporter is not initialized at the time a renderer process is created, then that renderer process will not be monitored by the crash reporter. > [!NOTE] > You can test out the crash reporter by generating a crash using > `process.crash()`. > [!NOTE] > If you need to send additional/updated `extra` parameters after your > first call `start` you can call `addExtraParameter`. > [!NOTE] > Parameters passed in `extra`, `globalExtra` or set with > `addExtraParameter` have limits on the length of the keys and values. Key names > must be at most 39 bytes long, and values must be no longer than 127 bytes. > Keys with names longer than the maximum will be silently ignored. Key values > longer than the maximum length will be truncated. > [!NOTE] > This method is only available in the main process. ### `crashReporter.getLastCrashReport()` Returns [`CrashReport | null`](structures/crash-report.md) - 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. In the case that there are no uploaded reports, `null` is returned. > [!NOTE] > This method is only available in the main process. ### `crashReporter.getUploadedReports()` Returns [`CrashReport[]`](structures/crash-report.md): Returns all uploaded crash reports. Each report contains the date and uploaded ID. > [!NOTE] > This method is only available in the main process. ### `crashReporter.getUploadToServer()` Returns `boolean` - Whether reports should be submitted to the server. Set through the `start` method or `setUploadToServer`. > [!NOTE] > This method is only available in the main process. ### `crashReporter.setUploadToServer(uploadToServer)` * `uploadToServer` boolean - Whether reports should be submitted to the server. This would normally be controlled by user preferences. This has no effect if called before `start` is called. > [!NOTE] > This method is only available in the main process. ### `crashReporter.addExtraParameter(key, value)` * `key` string - Parameter key, must be no longer than 39 bytes. * `value` string - Parameter value, must be no longer than 127 bytes. Set an extra parameter to be sent with the crash report. The values specified here will be sent in addition to any values set via the `extra` option when `start` was called. Parameters added in this fashion (or via the `extra` parameter to `crashReporter.start`) are specific to the calling process. Adding extra parameters in the main process will not cause those parameters to be sent along with crashes from renderer or other child processes. Similarly, adding extra parameters in a renderer process will not result in those parameters being sent with crashes that occur in other renderer processes or in the main process. > [!NOTE] > Parameters have limits on the length of the keys and values. Key > names must be no longer than 39 bytes, and 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.removeExtraParameter(key)` * `key` string - Parameter key, must be no longer than 39 bytes. Remove an extra parameter from the current set of parameters. Future crashes will not include this parameter. ### `crashReporter.getParameters()` Returns `Record` - The current 'extra' parameters of the crash reporter. ## In Node child processes Since `require('electron')` is not available in Node child processes, the following APIs are available on the `process` object in Node child processes. #### `process.crashReporter.start(options)` See [`crashReporter.start()`](#crashreporterstartoptions). Note that 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 this method if the main process does not initialize the crash reporter. #### `process.crashReporter.getParameters()` See [`crashReporter.getParameters()`](#crashreportergetparameters). #### `process.crashReporter.addExtraParameter(key, value)` See [`crashReporter.addExtraParameter(key, value)`](#crashreporteraddextraparameterkey-value). #### `process.crashReporter.removeExtraParameter(key)` See [`crashReporter.removeExtraParameter(key)`](#crashreporterremoveextraparameterkey). ## Crash Report Payload The crash reporter will send the following data to the `submitURL` as a `multipart/form-data` `POST`: * `ver` string - The 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 - The version in `package.json`. * `_productName` string - The product name in the `crashReporter` `options` object. * `prod` string - Name of the underlying product. In this case Electron. * `_companyName` string - The company name in the `crashReporter` `options` object. * `upload_file_minidump` File - The crash report in the format of `minidump`. * All level one properties of the `extra` object in the `crashReporter` `options` object. --- ## Class: Debugger > An alternate transport for Chrome's remote debugging protocol. Process: [Main](../glossary.md#main-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ Chrome Developer Tools has a [special binding][rdp] available at JavaScript runtime that allows interacting with pages and instrumenting them. ```js const { BrowserWindow } = require('electron') const win = new BrowserWindow() try { win.webContents.debugger.attach('1.1') } catch (err) { console.log('Debugger attach failed : ', err) } win.webContents.debugger.on('detach', (event, reason) => { console.log('Debugger detached due to : ', reason) }) win.webContents.debugger.on('message', (event, method, params) => { if (method === 'Network.requestWillBeSent') { if (params.request.url === 'https://www.github.com') { win.webContents.debugger.detach() } } }) win.webContents.debugger.sendCommand('Network.enable') ``` ### Instance Events #### Event: 'detach' Returns: * `event` Event * `reason` string - Reason for detaching debugger. Emitted when the debugging session is terminated. This happens either when `webContents` is closed or devtools is invoked for the attached `webContents`. #### Event: 'message' Returns: * `event` Event * `method` string - Method name. * `params` any - Event parameters defined by the 'parameters' attribute in the remote debugging protocol. * `sessionId` string - Unique identifier of attached debugging session, will match the value sent from `debugger.sendCommand`. Emitted whenever the debugging target issues an instrumentation event. [rdp]: https://chromedevtools.github.io/devtools-protocol/ ### Instance Methods #### `debugger.attach([protocolVersion])` * `protocolVersion` string (optional) - Requested debugging protocol version. Attaches the debugger to the `webContents`. #### `debugger.isAttached()` Returns `boolean` - Whether a debugger is attached to the `webContents`. #### `debugger.detach()` Detaches the debugger from the `webContents`. #### `debugger.sendCommand(method[, commandParams, sessionId])` * `method` string - Method name, should be one of the methods defined by the [remote debugging protocol][rdp]. * `commandParams` any (optional) - JSON object with request parameters. * `sessionId` string (optional) - send command to the target with associated debugging session id. The initial value can be obtained by sending [Target.attachToTarget][attachToTarget] message. [attachToTarget]: https://chromedevtools.github.io/devtools-protocol/tot/Target/#method-attachToTarget Returns `Promise` - A promise that resolves with the response defined by the 'returns' attribute of the command description in the remote debugging protocol or is rejected indicating the failure of the command. Send given command to the debugging target. --- # desktopCapturer > Access information about media sources that can be used to capture audio and > video from the desktop using the [`navigator.mediaDevices.getUserMedia`][] API. Process: [Main](../glossary.md#main-process) The following example shows how to capture video from a desktop window whose title is `Electron`: ```js // main.js const { app, BrowserWindow, desktopCapturer, session } = require('electron') app.whenReady().then(() => { const mainWindow = new BrowserWindow() session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { desktopCapturer.getSources({ types: ['screen'] }).then((sources) => { // Grant access to the first screen found. callback({ video: sources[0], audio: 'loopback' }) }) // If true, use the system picker if available. // Note: this is currently experimental. If the system picker // is available, it will be used and the media request handler // will not be invoked. }, { useSystemPicker: true }) mainWindow.loadFile('index.html') }) ``` ```js // renderer.js const startButton = document.getElementById('startButton') const stopButton = document.getElementById('stopButton') const video = document.querySelector('video') startButton.addEventListener('click', () => { navigator.mediaDevices.getDisplayMedia({ audio: true, video: { width: 320, height: 240, frameRate: 30 } }).then(stream => { video.srcObject = stream video.onloadedmetadata = (e) => video.play() }).catch(e => console.log(e)) }) stopButton.addEventListener('click', () => { video.pause() }) ``` ```html ``` See [`navigator.mediaDevices.getDisplayMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia) for more information. > [!NOTE] > `navigator.mediaDevices.getDisplayMedia` does not permit the use of `deviceId` for > selection of a source - see [specification](https://w3c.github.io/mediacapture-screen-share/#constraints). ## Methods The `desktopCapturer` module has the following methods: ### `desktopCapturer.getSources(options)` * `options` Object * `types` string[] - An array of strings that lists the types of desktop sources to be captured, available types can be `screen` and `window`. * `thumbnailSize` [Size](structures/size.md) (optional) - The size that the media source thumbnail should be scaled to. Default is `150` x `150`. Set width or height to 0 when you do not need the thumbnails. This will save the processing time required for capturing the content of each window and screen. * `fetchWindowIcons` boolean (optional) - Set to true to enable fetching window icons. The default value is false. When false the appIcon property of the sources return null. Same if a source has the type screen. Returns `Promise` - Resolves with an array of [`DesktopCapturerSource`](structures/desktop-capturer-source.md) objects, each `DesktopCapturerSource` represents a screen or an individual window that can be captured. > [!NOTE] > Capturing the screen contents requires user consent on macOS 10.15 Catalina or higher, > which can detected by [`systemPreferences.getMediaAccessStatus`][]. [`navigator.mediaDevices.getUserMedia`]: https://developer.mozilla.org/en/docs/Web/API/MediaDevices/getUserMedia [`systemPreferences.getMediaAccessStatus`]: system-preferences.md#systempreferencesgetmediaaccessstatusmediatype-windows-macos ## Caveats `desktopCapturer.getSources(options)` only returns a single source on Linux when using Pipewire. PipeWire supports a single capture for both screens and windows. If you request the window and screen type, the selected source will be returned as a window capture. `navigator.mediaDevices.getUserMedia` does not work on macOS for audio capture due to a fundamental limitation whereby apps that want to access the system's audio require a [signed kernel extension](https://developer.apple.com/library/archive/documentation/Security/Conceptual/System_Integrity_Protection_Guide/KernelExtensions/KernelExtensions.html). Chromium, and by extension Electron, does not provide this. It is possible to circumvent this limitation by capturing system audio with another macOS app like Soundflower and passing it through a virtual audio input device. This virtual device can then be queried with `navigator.mediaDevices.getUserMedia`. --- # dialog > Display native system dialogs for opening and saving files, alerting, etc. Process: [Main](../glossary.md#main-process) An example of showing a dialog to select multiple files: ```js const { dialog } = require('electron') console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] })) ``` ## Methods The `dialog` module has the following methods: ### `dialog.showOpenDialogSync([window, ]options)` * `window` [BaseWindow](base-window.md) (optional) * `options` Object * `title` string (optional) * `defaultPath` string (optional) * `buttonLabel` string (optional) - Custom label for the confirmation button, when left empty the default label will be used. * `filters` [FileFilter[]](structures/file-filter.md) (optional) * `properties` string[] (optional) - Contains which features the dialog should use. The following values are supported: * `openFile` - Allow files to be selected. * `openDirectory` - Allow directories to be selected. * `multiSelections` - Allow multiple paths to be selected. * `showHiddenFiles` - Show hidden files in dialog. * `createDirectory` _macOS_ - Allow creating new directories from dialog. * `promptToCreate` _Windows_ - Prompt for creation if the file path entered in the dialog does not exist. This does not actually create the file at the path but allows non-existent paths to be returned that should be created by the application. * `noResolveAliases` _macOS_ - Disable the automatic alias (symlink) path resolution. Selected aliases will now return the alias path instead of their target path. * `treatPackageAsDirectory` _macOS_ - Treat packages, such as `.app` folders, as a directory instead of a file. * `dontAddToRecent` _Windows_ - Do not add the item being opened to the recent documents list. * `message` string (optional) _macOS_ - Message to display above input boxes. * `securityScopedBookmarks` boolean (optional) _macOS_ _mas_ - Create [security scoped bookmarks](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) when packaged for the Mac App Store. Returns `string[] | undefined`, the file paths chosen by the user; if the dialog is cancelled it returns `undefined`. The `window` argument allows the dialog to attach itself to a parent window, making it modal. The `filters` specifies an array of file types that can be displayed or selected when you want to limit the user to a specific type. For example: ```js { filters: [ { name: 'Images', extensions: ['jpg', 'png', 'gif'] }, { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] }, { name: 'Custom File Type', extensions: ['as'] }, { name: 'All Files', extensions: ['*'] } ] } ``` The `extensions` array should contain extensions without wildcards or dots (e.g. `'png'` is good but `'.png'` and `'*.png'` are bad). To show all files, use the `'*'` wildcard (no other wildcard is supported). > [!NOTE] > On Windows and Linux an open dialog can not be both a file selector > and a directory selector, so if you set `properties` to > `['openFile', 'openDirectory']` on these platforms, a directory selector will be > shown. ```js @ts-type={mainWindow:Electron.BaseWindow} dialog.showOpenDialogSync(mainWindow, { properties: ['openFile', 'openDirectory'] }) ``` > [!NOTE] > On Linux `defaultPath` is not supported when using portal file chooser > dialogs unless the portal backend is version 4 or higher. You can use `--xdg-portal-required-version` > [command-line switch](./command-line-switches.md#--xdg-portal-required-versionversion) > to force gtk or kde dialogs. ### `dialog.showOpenDialog([window, ]options)` * `window` [BaseWindow](base-window.md) (optional) * `options` Object * `title` string (optional) * `defaultPath` string (optional) * `buttonLabel` string (optional) - Custom label for the confirmation button, when left empty the default label will be used. * `filters` [FileFilter[]](structures/file-filter.md) (optional) * `properties` string[] (optional) - Contains which features the dialog should use. The following values are supported: * `openFile` - Allow files to be selected. * `openDirectory` - Allow directories to be selected. * `multiSelections` - Allow multiple paths to be selected. * `showHiddenFiles` - Show hidden files in dialog. * `createDirectory` _macOS_ - Allow creating new directories from dialog. * `promptToCreate` _Windows_ - Prompt for creation if the file path entered in the dialog does not exist. This does not actually create the file at the path but allows non-existent paths to be returned that should be created by the application. * `noResolveAliases` _macOS_ - Disable the automatic alias (symlink) path resolution. Selected aliases will now return the alias path instead of their target path. * `treatPackageAsDirectory` _macOS_ - Treat packages, such as `.app` folders, as a directory instead of a file. * `dontAddToRecent` _Windows_ - Do not add the item being opened to the recent documents list. * `message` string (optional) _macOS_ - Message to display above input boxes. * `securityScopedBookmarks` boolean (optional) _macOS_ _mas_ - Create [security scoped bookmarks](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) when packaged for the Mac App Store. Returns `Promise` - Resolve with an object containing the following: * `canceled` boolean - whether or not the dialog was canceled. * `filePaths` string[] - An array of file paths chosen by the user. If the dialog is cancelled this will be an empty array. * `bookmarks` string[] (optional) _macOS_ _mas_ - An array matching the `filePaths` array of base64 encoded strings which contains security scoped bookmark data. `securityScopedBookmarks` must be enabled for this to be populated. (For return values, see [table here](#bookmarks-array).) The `window` argument allows the dialog to attach itself to a parent window, making it modal. The `filters` specifies an array of file types that can be displayed or selected when you want to limit the user to a specific type. For example: ```js { filters: [ { name: 'Images', extensions: ['jpg', 'png', 'gif'] }, { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] }, { name: 'Custom File Type', extensions: ['as'] }, { name: 'All Files', extensions: ['*'] } ] } ``` The `extensions` array should contain extensions without wildcards or dots (e.g. `'png'` is good but `'.png'` and `'*.png'` are bad). To show all files, use the `'*'` wildcard (no other wildcard is supported). > [!NOTE] > On Windows and Linux an open dialog can not be both a file selector > and a directory selector, so if you set `properties` to > `['openFile', 'openDirectory']` on these platforms, a directory selector will be > shown. ```js @ts-type={mainWindow:Electron.BaseWindow} dialog.showOpenDialog(mainWindow, { properties: ['openFile', 'openDirectory'] }).then(result => { console.log(result.canceled) console.log(result.filePaths) }).catch(err => { console.log(err) }) ``` > [!NOTE] > On Linux `defaultPath` is not supported when using portal file chooser > dialogs unless the portal backend is version 4 or higher. You can use `--xdg-portal-required-version` > [command-line switch](./command-line-switches.md#--xdg-portal-required-versionversion) > to force gtk or kde dialogs. ### `dialog.showSaveDialogSync([window, ]options)` * `window` [BaseWindow](base-window.md) (optional) * `options` Object * `title` string (optional) - The dialog title. Cannot be displayed on some _Linux_ desktop environments. * `defaultPath` string (optional) - Absolute directory path, absolute file path, or file name to use by default. * `buttonLabel` string (optional) - Custom label for the confirmation button, when left empty the default label will be used. * `filters` [FileFilter[]](structures/file-filter.md) (optional) * `message` string (optional) _macOS_ - Message to display above text fields. * `nameFieldLabel` string (optional) _macOS_ - Custom label for the text displayed in front of the filename text field. * `showsTagField` boolean (optional) _macOS_ - Show the tags input box, defaults to `true`. * `properties` string[] (optional) * `showHiddenFiles` - Show hidden files in dialog. * `createDirectory` _macOS_ - Allow creating new directories from dialog. * `treatPackageAsDirectory` _macOS_ - Treat packages, such as `.app` folders, as a directory instead of a file. * `showOverwriteConfirmation` _Linux_ - Sets whether the user will be presented a confirmation dialog if the user types a file name that already exists. * `dontAddToRecent` _Windows_ - Do not add the item being saved to the recent documents list. * `securityScopedBookmarks` boolean (optional) _macOS_ _mas_ - Create a [security scoped bookmark](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) when packaged for the Mac App Store. If this option is enabled and the file doesn't already exist a blank file will be created at the chosen path. Returns `string`, the path of the file chosen by the user; if the dialog is cancelled it returns an empty string. The `window` argument allows the dialog to attach itself to a parent window, making it modal. The `filters` specifies an array of file types that can be displayed, see `dialog.showOpenDialog` for an example. ### `dialog.showSaveDialog([window, ]options)` * `window` [BaseWindow](base-window.md) (optional) * `options` Object * `title` string (optional) - The dialog title. Cannot be displayed on some _Linux_ desktop environments. * `defaultPath` string (optional) - Absolute directory path, absolute file path, or file name to use by default. * `buttonLabel` string (optional) - Custom label for the confirmation button, when left empty the default label will be used. * `filters` [FileFilter[]](structures/file-filter.md) (optional) * `message` string (optional) _macOS_ - Message to display above text fields. * `nameFieldLabel` string (optional) _macOS_ - Custom label for the text displayed in front of the filename text field. * `showsTagField` boolean (optional) _macOS_ - Show the tags input box, defaults to `true`. * `properties` string[] (optional) * `showHiddenFiles` - Show hidden files in dialog. * `createDirectory` _macOS_ - Allow creating new directories from dialog. * `treatPackageAsDirectory` _macOS_ - Treat packages, such as `.app` folders, as a directory instead of a file. * `showOverwriteConfirmation` _Linux_ - Sets whether the user will be presented a confirmation dialog if the user types a file name that already exists. * `dontAddToRecent` _Windows_ - Do not add the item being saved to the recent documents list. * `securityScopedBookmarks` boolean (optional) _macOS_ _mas_ - Create a [security scoped bookmark](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) when packaged for the Mac App Store. If this option is enabled and the file doesn't already exist a blank file will be created at the chosen path. Returns `Promise` - Resolve with an object containing the following: * `canceled` boolean - whether or not the dialog was canceled. * `filePath` string - If the dialog is canceled, this will be an empty string. * `bookmark` string (optional) _macOS_ _mas_ - Base64 encoded string which contains the security scoped bookmark data for the saved file. `securityScopedBookmarks` must be enabled for this to be present. (For return values, see [table here](#bookmarks-array).) The `window` argument allows the dialog to attach itself to a parent window, making it modal. The `filters` specifies an array of file types that can be displayed, see `dialog.showOpenDialog` for an example. > [!NOTE] > On macOS, using the asynchronous version is recommended to avoid issues when > expanding and collapsing the dialog. ### `dialog.showMessageBoxSync([window, ]options)` * `window` [BaseWindow](base-window.md) (optional) * `options` Object * `message` string - Content of the message box. * `type` string (optional) - Can be `none`, `info`, `error`, `question` or `warning`. On Windows, `question` displays the same icon as `info`, unless you set an icon using the `icon` option. On macOS, both `warning` and `error` display the same warning icon. * `buttons` string[] (optional) - Array of texts for buttons. On Windows, an empty array will result in one button labeled "OK". * `defaultId` Integer (optional) - Index of the button in the buttons array which will be selected by default when the message box opens. * `title` string (optional) - Title of the message box, some platforms will not show it. * `detail` string (optional) - Extra information of the message. * `icon` ([NativeImage](native-image.md) | string) (optional) * `textWidth` Integer (optional) _macOS_ - Custom width of the text in the message box. * `cancelId` Integer (optional) - The index of the button to be used to cancel the dialog, via the `Esc` key. By default this is assigned to the first button with "cancel" or "no" as the label. If no such labeled buttons exist and this option is not set, `0` will be used as the return value. * `noLink` boolean (optional) - On Windows Electron will try to figure out which one of the `buttons` are common buttons (like "Cancel" or "Yes"), and show the others as command links in the dialog. This can make the dialog appear in the style of modern Windows apps. If you don't like this behavior, you can set `noLink` to `true`. * `normalizeAccessKeys` boolean (optional) - Normalize the keyboard access keys across platforms. Default is `false`. Enabling this assumes `&` is used in the button labels for the placement of the keyboard shortcut access key and labels will be converted so they work correctly on each platform, `&` characters are removed on macOS, converted to `_` on Linux, and left untouched on Windows. For example, a button label of `Vie&w` will be converted to `Vie_w` on Linux and `View` on macOS and can be selected via `Alt-W` on Windows and Linux. Returns `Integer` - the index of the clicked button. Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button. The `window` argument allows the dialog to attach itself to a parent window, making it modal. If `window` is not shown dialog will not be attached to it. In such case it will be displayed as an independent window. ### `dialog.showMessageBox([window, ]options)` * `window` [BaseWindow](base-window.md) (optional) * `options` Object * `message` string - Content of the message box. * `type` string (optional) - Can be `none`, `info`, `error`, `question` or `warning`. On Windows, `question` displays the same icon as `info`, unless you set an icon using the `icon` option. On macOS, both `warning` and `error` display the same warning icon. * `buttons` string[] (optional) - Array of texts for buttons. On Windows, an empty array will result in one button labeled "OK". * `defaultId` Integer (optional) - Index of the button in the buttons array which will be selected by default when the message box opens. * `signal` AbortSignal (optional) - Pass an instance of [AbortSignal][] to optionally close the message box, the message box will behave as if it was cancelled by the user. On macOS, `signal` does not work with message boxes that do not have a parent window, since those message boxes run synchronously due to platform limitations. * `title` string (optional) - Title of the message box, some platforms will not show it. * `detail` string (optional) - Extra information of the message. * `checkboxLabel` string (optional) - If provided, the message box will include a checkbox with the given label. * `checkboxChecked` boolean (optional) - Initial checked state of the checkbox. `false` by default. * `icon` ([NativeImage](native-image.md) | string) (optional) * `textWidth` Integer (optional) _macOS_ - Custom width of the text in the message box. * `cancelId` Integer (optional) - The index of the button to be used to cancel the dialog, via the `Esc` key. By default this is assigned to the first button with "cancel" or "no" as the label. If no such labeled buttons exist and this option is not set, `0` will be used as the return value. * `noLink` boolean (optional) - On Windows Electron will try to figure out which one of the `buttons` are common buttons (like "Cancel" or "Yes"), and show the others as command links in the dialog. This can make the dialog appear in the style of modern Windows apps. If you don't like this behavior, you can set `noLink` to `true`. * `normalizeAccessKeys` boolean (optional) - Normalize the keyboard access keys across platforms. Default is `false`. Enabling this assumes `&` is used in the button labels for the placement of the keyboard shortcut access key and labels will be converted so they work correctly on each platform, `&` characters are removed on macOS, converted to `_` on Linux, and left untouched on Windows. For example, a button label of `Vie&w` will be converted to `Vie_w` on Linux and `View` on macOS and can be selected via `Alt-W` on Windows and Linux. Returns `Promise` - resolves with a promise containing the following properties: * `response` number - The index of the clicked button. * `checkboxChecked` boolean - The checked state of the checkbox if `checkboxLabel` was set. Otherwise `false`. Shows a message box. The `window` argument allows the dialog to attach itself to a parent window, making it modal. ### `dialog.showErrorBox(title, content)` * `title` string - The title to display in the error box. * `content` string - The text content to display in the error box. Displays a modal dialog that shows an error message. This API can be called safely before the `ready` event the `app` module emits, it is usually used to report errors in early stage of startup. If called before the app `ready`event on Linux, the message will be emitted to stderr, and no GUI dialog will appear. ### `dialog.showCertificateTrustDialog([window, ]options)` _macOS_ _Windows_ * `window` [BaseWindow](base-window.md) (optional) * `options` Object * `certificate` [Certificate](structures/certificate.md) - The certificate to trust/import. * `message` string - The message to display to the user. Returns `Promise` - resolves when the certificate trust dialog is shown. On macOS, this displays a modal dialog that shows a message and certificate information, and gives the user the option of trusting/importing the certificate. If you provide a `window` argument the dialog will be attached to the parent window, making it modal. On Windows the options are more limited, due to the Win32 APIs used: * The `message` argument is not used, as the OS provides its own confirmation dialog. * The `window` argument is ignored since it is not possible to make this confirmation dialog modal. ## Bookmarks array `showOpenDialog` and `showSaveDialog` resolve to an object with a `bookmarks` field. This field is an array of Base64 encoded strings that contain the [security scoped bookmark](https://developer.apple.com/library/content/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW16) data for the saved file. The `securityScopedBookmarks` option must be enabled for this to be present. | Build Type | securityScopedBookmarks boolean | Return Type | Return Value | |------------|---------------------------------|:-----------:|--------------------------------| | macOS mas | True | Success | `['LONGBOOKMARKSTRING']` | | macOS mas | True | Error | `['']` (array of empty string) | | macOS mas | False | NA | `[]` (empty array) | | non mas | any | NA | `[]` (empty array) | ## Sheets On macOS, dialogs are presented as sheets attached to a window if you provide a [`BaseWindow`](base-window.md) reference in the `window` parameter, or modals if no window is provided. You can call `BaseWindow.getCurrentWindow().setSheetOffset(offset)` to change the offset from the window frame where sheets are attached. [AbortSignal]: https://nodejs.org/api/globals.html#globals_class_abortsignal --- ## Class: Dock > Control your app in the macOS dock Process: [Main](../glossary.md#main-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ > [!TIP] > See also: [A detailed guide about how to implement Dock menus](../tutorial/macos-dock.md). ### Instance Methods #### `dock.bounce([type])` _macOS_ * `type` string (optional) - Can be `critical` or `informational`. The default is `informational` Returns `Integer` - an ID representing the request. When `critical` is passed, the dock icon will bounce until either the application becomes active or the request is canceled. When `informational` is passed, the dock icon will bounce for one second. However, the request remains active until either the application becomes active or the request is canceled. > [!NOTE] > This method can only be used while the app is not focused; when the app is focused it will return -1. #### `dock.cancelBounce(id)` _macOS_ * `id` Integer Cancel the bounce of `id`. #### `dock.downloadFinished(filePath)` _macOS_ * `filePath` string Bounces the Downloads stack if the filePath is inside the Downloads folder. #### `dock.setBadge(text)` _macOS_ * `text` string Sets the string to be displayed in the dock’s badging area. > [!IMPORTANT] > You need to ensure that your application has the permission to display notifications for this method to work. #### `dock.getBadge()` _macOS_ Returns `string` - The badge string of the dock. #### `dock.hide()` _macOS_ Hides the dock icon. #### `dock.show()` _macOS_ Returns `Promise` - Resolves when the dock icon is shown. #### `dock.isVisible()` _macOS_ Returns `boolean` - Whether the dock icon is visible. #### `dock.setMenu(menu)` _macOS_ * `menu` [Menu](menu.md) Sets the application's [dock menu][dock-menu]. #### `dock.getMenu()` _macOS_ Returns `Menu | null` - The application's [dock menu][dock-menu]. #### `dock.setIcon(image)` _macOS_ * `image` ([NativeImage](native-image.md) | string) Sets the `image` associated with this dock icon. [dock-menu]: https://developer.apple.com/design/human-interface-guidelines/dock-menus --- ## Class: DownloadItem > Control file downloads from remote sources. Process: [Main](../glossary.md#main-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ `DownloadItem` is an [EventEmitter][event-emitter] that represents a download item in Electron. It is used in `will-download` event of `Session` class, and allows users to control the download item. ```js // In the main process. const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.session.on('will-download', (event, item, webContents) => { // Set the save path, making Electron not to prompt a save dialog. item.setSavePath('/tmp/save.pdf') item.on('updated', (event, state) => { if (state === 'interrupted') { console.log('Download is interrupted but can be resumed') } else if (state === 'progressing') { if (item.isPaused()) { console.log('Download is paused') } else { console.log(`Received bytes: ${item.getReceivedBytes()}`) } } }) item.once('done', (event, state) => { if (state === 'completed') { console.log('Download successfully') } else { console.log(`Download failed: ${state}`) } }) }) ``` ### Instance Events #### Event: 'updated' Returns: * `event` Event * `state` string - Can be `progressing` or `interrupted`. Emitted when the download has been updated and is not done. The `state` can be one of following: * `progressing` - The download is in-progress. * `interrupted` - The download has interrupted and can be resumed. #### Event: 'done' Returns: * `event` Event * `state` string - Can be `completed`, `cancelled` or `interrupted`. Emitted when the download is in a terminal state. This includes a completed download, a cancelled download (via `downloadItem.cancel()`), and interrupted download that can't be resumed. The `state` can be one of following: * `completed` - The download completed successfully. * `cancelled` - The download has been cancelled. * `interrupted` - The download has interrupted and can not resume. ### Instance Methods The `downloadItem` object has the following methods: #### `downloadItem.setSavePath(path)` * `path` string - Set the save file path of the download item. The API is only available in session's `will-download` callback function. If `path` doesn't exist, Electron will try to make the directory recursively. If user doesn't set the save path via the API, Electron will use the original routine to determine the save path; this usually prompts a save dialog. #### `downloadItem.getSavePath()` Returns `string` - The save path of the download item. This will be either the path set via `downloadItem.setSavePath(path)` or the path selected from the shown save dialog. #### `downloadItem.setSaveDialogOptions(options)` * `options` SaveDialogOptions - Set the save file dialog options. This object has the same properties as the `options` parameter of [`dialog.showSaveDialog()`](dialog.md). This API allows the user to set custom options for the save dialog that opens for the download item by default. The API is only available in session's `will-download` callback function. #### `downloadItem.getSaveDialogOptions()` Returns `SaveDialogOptions` - Returns the object previously set by `downloadItem.setSaveDialogOptions(options)`. #### `downloadItem.pause()` Pauses the download. #### `downloadItem.isPaused()` Returns `boolean` - Whether the download is paused. #### `downloadItem.resume()` Resumes the download that has been paused. > [!NOTE] > To enable resumable downloads the server you are downloading from must support range requests and provide both `Last-Modified` and `ETag` header values. Otherwise `resume()` will dismiss previously received bytes and restart the download from the beginning. #### `downloadItem.canResume()` Returns `boolean` - Whether the download can resume. #### `downloadItem.cancel()` Cancels the download operation. #### `downloadItem.getURL()` Returns `string` - The origin URL where the item is downloaded from. #### `downloadItem.getMimeType()` Returns `string` - The files mime type. #### `downloadItem.hasUserGesture()` Returns `boolean` - Whether the download has user gesture. #### `downloadItem.getFilename()` Returns `string` - The file name of the download item. > [!NOTE] > The file name is not always the same as the actual one saved in local > disk. If user changes the file name in a prompted download saving dialog, the > actual name of saved file will be different. #### `downloadItem.getCurrentBytesPerSecond()` Returns `Integer` - The current download speed in bytes per second. #### `downloadItem.getTotalBytes()` Returns `Integer` - The total size in bytes of the download item. If the size is unknown, it returns 0. #### `downloadItem.getReceivedBytes()` Returns `Integer` - The received bytes of the download item. #### `downloadItem.getPercentComplete()` Returns `Integer` - The download completion in percent. #### `downloadItem.getContentDisposition()` Returns `string` - The Content-Disposition field from the response header. #### `downloadItem.getState()` Returns `string` - The current state. Can be `progressing`, `completed`, `cancelled` or `interrupted`. > [!NOTE] > The following methods are useful specifically to resume a > `cancelled` item when session is restarted. #### `downloadItem.getURLChain()` Returns `string[]` - The complete URL chain of the item including any redirects. #### `downloadItem.getLastModifiedTime()` Returns `string` - Last-Modified header value. #### `downloadItem.getETag()` Returns `string` - ETag header value. #### `downloadItem.getStartTime()` Returns `Double` - Number of seconds since the UNIX epoch when the download was started. #### `downloadItem.getEndTime()` Returns `Double` - Number of seconds since the UNIX epoch when the download ended. ### Instance Properties #### `downloadItem.savePath` A `string` property that determines the save file path of the download item. The property is only available in session's `will-download` callback function. If user doesn't set the save path via the property, Electron will use the original routine to determine the save path; this usually prompts a save dialog. [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter --- # Environment Variables > Control application configuration and behavior without changing code. Certain Electron behaviors are controlled by environment variables because they are initialized earlier than the command line flags and the app's code. POSIX shell example: ```sh $ export ELECTRON_ENABLE_LOGGING=true $ electron ``` Windows console example: ```powershell > set ELECTRON_ENABLE_LOGGING=true > electron ``` ## Production Variables The following environment variables are intended primarily for use at runtime in packaged Electron applications. ### `NODE_OPTIONS` Electron includes support for a subset of Node's [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options). The majority are supported with the exception of those which conflict with Chromium's use of BoringSSL. Example: ```sh export NODE_OPTIONS="--no-warnings --max-old-space-size=2048" ``` Unsupported options are: ```sh --use-bundled-ca --force-fips --enable-fips --openssl-config --use-openssl-ca ``` `NODE_OPTIONS` are explicitly disallowed in packaged apps, except for the following: ```sh --max-http-header-size --http-parser ``` If the [`nodeOptions` fuse](../tutorial/fuses.md#nodeoptions) is disabled, `NODE_OPTIONS` will be ignored. ### `NODE_EXTRA_CA_CERTS` See [Node.js cli documentation](https://github.com/nodejs/node/blob/main/doc/api/cli.md#node_extra_ca_certsfile) for details. ```sh export NODE_EXTRA_CA_CERTS=/path/to/cert.pem ``` If the [`nodeOptions` fuse](../tutorial/fuses.md#nodeoptions) is disabled, `NODE_EXTRA_CA_CERTS` will be ignored. ### `GOOGLE_API_KEY` Geolocation support in Electron requires the use of Google Cloud Platform's geolocation webservice. To enable this feature, acquire a [Google API key](https://developers.google.com/maps/documentation/geolocation/get-api-key) and place the following code in your main process file, before opening any browser windows that will make geolocation requests: ```js process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE' ``` By default, a newly generated Google API key may not be allowed to make geolocation requests. To enable the geolocation webservice for your project, enable it through the [API library](https://console.cloud.google.com/apis/library). N.B. You will need to add a [Billing Account](https://cloud.google.com/billing/docs/how-to/payment-methods#add_a_payment_method) to the project associated to the API key for the geolocation webservice to work. ### `ELECTRON_NO_ASAR` Disables ASAR support. This variable is only supported in forked child processes and spawned child processes that set `ELECTRON_RUN_AS_NODE`. ### `ELECTRON_RUN_AS_NODE` Starts the process as a normal Node.js process. In this mode, you will be able to pass [cli options](https://nodejs.org/api/cli.html) to Node.js as you would when running the normal Node.js executable, with the exception of the following flags: * "--openssl-config" * "--use-bundled-ca" * "--use-openssl-ca", * "--force-fips" * "--enable-fips" These flags are disabled owing to the fact that Electron uses BoringSSL instead of OpenSSL when building Node.js' `crypto` module, and so will not work as designed. If the [`runAsNode` fuse](../tutorial/fuses.md#runasnode) is disabled, `ELECTRON_RUN_AS_NODE` will be ignored. ### `ELECTRON_NO_ATTACH_CONSOLE` _Windows_ Don't attach to the current console session. ### `ELECTRON_FORCE_WINDOW_MENU_BAR` _Linux_ Don't use the global menu bar on Linux. ### `ELECTRON_TRASH` _Linux_ Set the trash implementation on Linux. Default is `gio`. Options: * `gvfs-trash` * `trash-cli` * `kioclient5` * `kioclient` ## Development Variables The following environment variables are intended primarily for development and debugging purposes. ### `ELECTRON_ENABLE_LOGGING` Prints Chromium's internal logging to the console. Setting this variable is the same as passing `--enable-logging` on the command line. For more info, see `--enable-logging` in [command-line switches](./command-line-switches.md#--enable-loggingfile). ### `ELECTRON_LOG_FILE` Sets the file destination for Chromium's internal logging. Setting this variable is the same as passing `--log-file` on the command line. For more info, see `--log-file` in [command-line switches](./command-line-switches.md#--log-filepath). ### `ELECTRON_DEBUG_NOTIFICATIONS` Adds extra logs to [`Notification`](./notification.md) lifecycles on macOS to aid in debugging. Extra logging will be displayed when new Notifications are created or activated. They will also be displayed when common actions are taken: a notification is shown, dismissed, its button is clicked, or it is replied to. Sample output: ```sh Notification created (com.github.Electron:notification:EAF7B87C-A113-43D7-8E76-F88EC9D73D44) Notification displayed (com.github.Electron:notification:EAF7B87C-A113-43D7-8E76-F88EC9D73D44) Notification activated (com.github.Electron:notification:EAF7B87C-A113-43D7-8E76-F88EC9D73D44) Notification replied to (com.github.Electron:notification:EAF7B87C-A113-43D7-8E76-F88EC9D73D44) ``` ### `ELECTRON_LOG_ASAR_READS` When Electron reads from an ASAR file, log the read offset and file path to the system `tmpdir`. The resulting file can be provided to the ASAR module to optimize file ordering. ### `ELECTRON_ENABLE_STACK_DUMPING` Prints the stack trace to the console when Electron crashes. This environment variable will not work if the `crashReporter` is started. ### `ELECTRON_DEFAULT_ERROR_MODE` _Windows_ Shows the Windows's crash dialog when Electron crashes. This environment variable will not work if the `crashReporter` is started. ### `ELECTRON_OVERRIDE_DIST_PATH` When running from the `electron` package, this variable tells the `electron` command to use the specified build of Electron instead of the one downloaded by `npm install`. Usage: ```sh export ELECTRON_OVERRIDE_DIST_PATH=/Users/username/projects/electron/out/Testing ``` --- ## Class: Extensions > Load and interact with extensions. Process: [Main](../glossary.md#main-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ Instances of the `Extensions` class are accessed by using `extensions` property of a `Session`. ### Instance Events The following events are available on instances of `Extensions`: #### Event: 'extension-loaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded. This occurs whenever an extension is added to the "enabled" set of extensions. This includes: * Extensions being loaded from `Extensions.loadExtension`. * Extensions being reloaded: * from a crash. * if the extension requested it ([`chrome.runtime.reload()`](https://developer.chrome.com/extensions/runtime#method-reload)). #### Event: 'extension-unloaded' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is unloaded. This occurs when `Session.removeExtension` is called. #### Event: 'extension-ready' Returns: * `event` Event * `extension` [Extension](structures/extension.md) Emitted after an extension is loaded and all necessary browser state is initialized to support the start of the extension's background page. ### Instance Methods The following methods are available on instances of `Extensions`: #### `extensions.loadExtension(path[, options])` * `path` string - Path to a directory containing an unpacked Chrome extension * `options` Object (optional) * `allowFileAccess` boolean - Whether to allow the extension to read local files over `file://` protocol and inject content scripts into `file://` pages. This is required e.g. for loading devtools extensions on `file://` URLs. Defaults to false. Returns `Promise` - resolves when the extension is loaded. This method will raise an exception if the extension could not be loaded. If there are warnings when installing the extension (e.g. if the extension requests an API that Electron does not support) then they will be logged to the console. Note that Electron does not support the full range of Chrome extensions APIs. See [Supported Extensions APIs](extensions.md#supported-extensions-apis) for more details on what is supported. Note that in previous versions of Electron, extensions that were loaded would be remembered for future runs of the application. This is no longer the case: `loadExtension` must be called on every boot of your app if you want the extension to be loaded. ```js const { app, session } = require('electron') const path = require('node:path') app.whenReady().then(async () => { await session.defaultSession.extensions.loadExtension( path.join(__dirname, 'react-devtools'), // allowFileAccess is required to load the devtools extension on file:// URLs. { allowFileAccess: true } ) // Note that in order to use the React DevTools extension, you'll need to // download and unzip a copy of the extension. }) ``` This API does not support loading packed (.crx) extensions. > [!NOTE] > This API cannot be called before the `ready` event of the `app` module > is emitted. > [!NOTE] > Loading extensions into in-memory (non-persistent) sessions is not > supported and will throw an error. #### `extensions.removeExtension(extensionId)` * `extensionId` string - ID of extension to remove Unloads an extension. > [!NOTE] > This API cannot be called before the `ready` event of the `app` module > is emitted. #### `extensions.getExtension(extensionId)` * `extensionId` string - ID of extension to query Returns `Extension | null` - The loaded extension with the given ID. > [!NOTE] > This API cannot be called before the `ready` event of the `app` module > is emitted. #### `extensions.getAllExtensions()` Returns `Extension[]` - A list of all loaded extensions. > [!NOTE] > This API cannot be called before the `ready` event of the `app` module > is emitted. --- # Chrome Extension Support Electron supports a subset of the [Chrome Extensions API][chrome-extensions-api-index], primarily to support DevTools extensions and Chromium-internal extensions, but it also happens to support some other extension capabilities. [chrome-extensions-api-index]: https://developer.chrome.com/extensions/api_index > [!NOTE] > Electron does not support arbitrary Chrome extensions from the > store, and it is a **non-goal** of the Electron project to be perfectly > compatible with Chrome's implementation of Extensions. ## Loading extensions Electron only supports loading unpacked extensions (i.e., `.crx` files do not work). Extensions are installed per-`session`. To load an extension, call [`ses.extensions.loadExtension`](extensions-api.md#extensionsloadextensionpath-options): ```js const { session } = require('electron') session.defaultSession.loadExtension('path/to/unpacked/extension').then(({ id }) => { // ... }) ``` Loaded extensions will not be automatically remembered across exits; if you do not call `loadExtension` when the app runs, the extension will not be loaded. Note that loading extensions is only supported in persistent sessions. Attempting to load an extension into an in-memory session will throw an error. See the [`session`](session.md) documentation for more information about loading, unloading, and querying active extensions. ## Supported Extensions APIs We support the following extensions APIs, with some caveats. Other APIs may additionally be supported, but support for any APIs not listed here is provisional and may be removed. ### Supported Manifest Keys - `name` - `version` - `author` - `permissions` - `content_scripts` - `default_locale` - `devtools_page` - `short_name` - `host_permissions` (Manifest V3) - `manifest_version` - `background` (Manifest V2) - `minimum_chrome_version` See [Manifest file format](https://developer.chrome.com/docs/extensions/mv3/manifest/) for more information about the purpose of each possible key. ### `chrome.devtools.inspectedWindow` All features of this API are supported. See [official documentation](https://developer.chrome.com/docs/extensions/reference/devtools_inspectedWindow) for more information. ### `chrome.devtools.network` All features of this API are supported. See [official documentation](https://developer.chrome.com/docs/extensions/reference/devtools_network) for more information. ### `chrome.devtools.panels` All features of this API are supported. See [official documentation](https://developer.chrome.com/docs/extensions/reference/devtools_panels) for more information. ### `chrome.extension` The following properties of `chrome.extension` are supported: - `chrome.extension.lastError` The following methods of `chrome.extension` are supported: - `chrome.extension.getURL` - `chrome.extension.getBackgroundPage` See [official documentation](https://developer.chrome.com/docs/extensions/reference/extension) for more information. ### `chrome.management` The following methods of `chrome.management` are supported: - `chrome.management.getAll` - `chrome.management.get` - `chrome.management.getSelf` - `chrome.management.getPermissionWarningsById` - `chrome.management.getPermissionWarningsByManifest` The following events of `chrome.management` are supported: - `chrome.management.onEnabled` - `chrome.management.onDisabled` See [official documentation](https://developer.chrome.com/docs/extensions/reference/management) for more information. ### `chrome.runtime` The following properties of `chrome.runtime` are supported: - `chrome.runtime.lastError` - `chrome.runtime.id` The following methods of `chrome.runtime` are supported: - `chrome.runtime.getBackgroundPage` - `chrome.runtime.getManifest` - `chrome.runtime.getPlatformInfo` - `chrome.runtime.getURL` - `chrome.runtime.connect` - `chrome.runtime.sendMessage` - `chrome.runtime.reload` The following events of `chrome.runtime` are supported: - `chrome.runtime.onStartup` - `chrome.runtime.onInstalled` - `chrome.runtime.onSuspend` - `chrome.runtime.onSuspendCanceled` - `chrome.runtime.onConnect` - `chrome.runtime.onMessage` See [official documentation](https://developer.chrome.com/docs/extensions/reference/runtime) for more information. ### `chrome.scripting` All features of this API are supported. See [official documentation](https://developer.chrome.com/docs/extensions/reference/scripting) for more information. ### `chrome.storage` The following methods of `chrome.storage` are supported: - `chrome.storage.local` `chrome.storage.sync` and `chrome.storage.managed` are **not** supported. See [official documentation](https://developer.chrome.com/docs/extensions/reference/storage) for more information. ### `chrome.tabs` The following methods of `chrome.tabs` are supported: - `chrome.tabs.sendMessage` - `chrome.tabs.reload` - `chrome.tabs.executeScript` - `chrome.tabs.query` (partial support) - supported properties: `url`, `title`, `audible`, `active`, `muted`. - `chrome.tabs.update` (partial support) - supported properties: `url`, `muted`. > [!NOTE] > In Chrome, passing `-1` as a tab ID signifies the "currently active > tab". Since Electron has no such concept, passing `-1` as a tab ID is not > supported and will raise an error. See [official documentation](https://developer.chrome.com/docs/extensions/reference/tabs) for more information. ### `chrome.webRequest` All features of this API are supported. > [!NOTE] > Electron's [`webRequest`](web-request.md) module takes precedence over `chrome.webRequest` if there are conflicting handlers. See [official documentation](https://developer.chrome.com/docs/extensions/reference/webRequest) for more information. --- # globalShortcut > Detect keyboard events when the application does not have keyboard focus. Process: [Main](../glossary.md#main-process) The `globalShortcut` module can register/unregister a global keyboard shortcut with the operating system so that you can customize the operations for various shortcuts. > [!NOTE] > The shortcut is global; it will work even if the app does > not have the keyboard focus. This module cannot be used before the `ready` > event of the app module is emitted. > Please also note that it is also possible to use Chromium's > `GlobalShortcutsPortal` implementation, which allows apps to bind global > shortcuts when running within a Wayland session. ```js 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() }) ``` > [!TIP] > See also: [A detailed guide on Keyboard Shortcuts](../tutorial/keyboard-shortcuts.md). ## Methods The `globalShortcut` module has the following methods: ### `globalShortcut.register(accelerator, callback)` * `accelerator` string - An [accelerator](../tutorial/keyboard-shortcuts.md#accelerators) shortcut. * `callback` Function Returns `boolean` - Whether or not the shortcut was registered successfully. Registers a global shortcut of `accelerator`. The `callback` is called when the registered shortcut is pressed by the user. When the accelerator is already taken by other applications, this call will silently fail. This behavior is intended by operating systems, since they don't want applications to fight for global shortcuts. The following accelerators will not be registered successfully on macOS 10.14 Mojave unless the app has been authorized as a [trusted accessibility client](https://developer.apple.com/library/archive/documentation/Accessibility/Conceptual/AccessibilityMacOSX/OSXAXTestingApps.html): * "Media Play/Pause" * "Media Next Track" * "Media Previous Track" * "Media Stop" ### `globalShortcut.registerAll(accelerators, callback)` * `accelerators` string[] - An array of [accelerator](../tutorial/keyboard-shortcuts.md#accelerators) shortcuts. * `callback` Function Registers a global shortcut of all `accelerator` items in `accelerators`. 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. This behavior is intended by operating systems, since they don't want applications to fight for global shortcuts. The following accelerators will not be registered successfully on macOS 10.14 Mojave unless the app has been authorized as a [trusted accessibility client](https://developer.apple.com/library/archive/documentation/Accessibility/Conceptual/AccessibilityMacOSX/OSXAXTestingApps.html): * "Media Play/Pause" * "Media Next Track" * "Media Previous Track" * "Media Stop" ### `globalShortcut.isRegistered(accelerator)` * `accelerator` string - An [accelerator](../tutorial/keyboard-shortcuts.md#accelerators) shortcut. Returns `boolean` - Whether this application has registered `accelerator`. When the accelerator is already taken by other applications, this call will still return `false`. This behavior is intended by operating systems, since they don't want applications to fight for global shortcuts. ### `globalShortcut.unregister(accelerator)` * `accelerator` string - An [accelerator](../tutorial/keyboard-shortcuts.md#accelerators) shortcut. Unregisters the global shortcut of `accelerator`. ### `globalShortcut.unregisterAll()` Unregisters all of the global shortcuts. --- # ImageView > A View that displays an image. Process: [Main](../glossary.md#main-process) This module cannot be used until the `ready` event of the `app` module is emitted. Useful for showing splash screens that will be swapped for `WebContentsView`s when the content finishes loading. Note that `ImageView` is experimental and may be changed or removed in the future. ```js const { BaseWindow, ImageView, nativeImage, WebContentsView } = require('electron') const path = require('node:path') const win = new BaseWindow({ width: 800, height: 600 }) // Create a "splash screen" image to display while the WebContentsView loads const splashView = new ImageView() const splashImage = nativeImage.createFromPath(path.join(__dirname, 'loading.png')) splashView.setImage(splashImage) win.setContentView(splashView) const webContentsView = new WebContentsView() webContentsView.webContents.once('did-finish-load', () => { // Now that the WebContentsView has loaded, swap out the "splash screen" ImageView win.setContentView(webContentsView) }) webContentsView.webContents.loadURL('https://electronjs.org') ``` ## Class: ImageView extends `View` > A View that displays an image. Process: [Main](../glossary.md#main-process) `ImageView` inherits from [`View`](view.md). `ImageView` is an [EventEmitter][event-emitter]. > [!WARNING] > Electron's built-in classes cannot be subclassed in user code. > For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules). ### `new ImageView()` _Experimental_ Creates an ImageView. ### Instance Methods The following methods are available on instances of the `ImageView` class, in addition to those inherited from [View](view.md): #### `image.setImage(image)` _Experimental_ * `image` NativeImage Sets the image for this `ImageView`. Note that only image formats supported by `NativeImage` can be used with an `ImageView`. [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter --- # inAppPurchase > In-app purchases on Mac App Store. Process: [Main](../glossary.md#main-process) ## Events The `inAppPurchase` module emits the following events: ### Event: 'transactions-updated' Returns: * `event` Event * `transactions` Transaction[] - Array of [`Transaction`](structures/transaction.md) objects. Emitted when one or more transactions have been updated. ## Methods The `inAppPurchase` module has the following methods: ### `inAppPurchase.purchaseProduct(productID[, opts])` * `productID` string * `opts` Integer | Object (optional) - If specified as an integer, defines the quantity. * `quantity` Integer (optional) - The number of items the user wants to purchase. * `username` string (optional) - The string that associates the transaction with a user account on your service (applicationUsername). Returns `Promise` - Returns `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 you call `purchaseProduct`. ### `inAppPurchase.getProducts(productIDs)` * `productIDs` string[] - The identifiers of the products to get. Returns `Promise` - Resolves with an array of [`Product`](structures/product.md) objects. Retrieves the product descriptions. ### `inAppPurchase.canMakePayments()` Returns `boolean` - whether a user can make a payment. ### `inAppPurchase.restoreCompletedTransactions()` Restores finished transactions. This method can be called either to install purchases on additional devices, or to restore purchases for an application that the user deleted and reinstalled. [The payment queue](https://developer.apple.com/documentation/storekit/skpaymentqueue?language=objc) delivers a new transaction for each previously completed transaction that can be restored. Each transaction includes a copy of the original transaction. ### `inAppPurchase.getReceiptURL()` Returns `string` - the path to the receipt. ### `inAppPurchase.finishAllTransactions()` Completes all pending transactions. ### `inAppPurchase.finishTransactionByDate(date)` * `date` string - The ISO formatted date of the transaction to finish. Completes the pending transactions corresponding to the date. --- ## Class: IncomingMessage > Handle responses to HTTP/HTTPS requests. Process: [Main](../glossary.md#main-process), [Utility](../glossary.md#utility-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ `IncomingMessage` implements the [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams) interface and is therefore an [EventEmitter][event-emitter]. ### Instance Events #### Event: 'data' Returns: * `chunk` Buffer - A chunk of response body's data. The `data` event is the usual method of transferring response data into applicative code. #### Event: 'end' Indicates that response body has ended. Must be placed before 'data' event. #### Event: 'aborted' Emitted when a request has been canceled during an ongoing HTTP transaction. #### Event: 'error' Returns: * `error` Error - Typically holds an error string identifying failure root cause. Emitted when an error was encountered while streaming response data events. For instance, if the server closes the underlying while the response is still streaming, an `error` event will be emitted on the response object and a `close` event will subsequently follow on the request object. ### Instance Properties An `IncomingMessage` instance has the following readable properties: #### `response.statusCode` An `Integer` indicating the HTTP response status code. #### `response.statusMessage` A `string` representing the HTTP status message. #### `response.headers` A `Record` representing the HTTP response headers. The `headers` object is formatted as follows: * All header names are lowercased. * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. * `set-cookie` is always an array. Duplicates are added to the array. * For duplicate `cookie` headers, the values are joined together with '; '. * For all other headers, the values are joined together with ', '. #### `response.httpVersion` A `string` indicating the HTTP protocol version number. Typical values are '1.0' or '1.1'. Additionally `httpVersionMajor` and `httpVersionMinor` are two Integer-valued readable properties that return respectively the HTTP major and minor version numbers. #### `response.httpVersionMajor` An `Integer` indicating the HTTP protocol major version number. #### `response.httpVersionMinor` An `Integer` indicating the HTTP protocol minor version number. [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter #### `response.rawHeaders` A `string[]` containing the raw HTTP response headers exactly as they were received. The keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. Header names are not lowercased, and duplicates are not merged. ```js @ts-type={response:Electron.IncomingMessage} // Prints something like: // // [ 'user-agent', // 'this is invalid because there can be only one', // 'User-Agent', // 'curl/7.22.0', // 'Host', // '127.0.0.1:8000', // 'ACCEPT', // '*/*' ] console.log(response.rawHeaders) ``` --- ## Class: IpcMainServiceWorker > Communicate asynchronously from the main process to service workers. Process: [Main](../glossary.md#main-process) > [!NOTE] > This API is a subtle variation of [`IpcMain`](ipc-main.md)—targeted for > communicating with service workers. For communicating with web frames, > consult the `IpcMain` documentation. > [!WARNING] > Electron's built-in classes cannot be subclassed in user code. > For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules). ### Instance Methods #### `ipcMainServiceWorker.on(channel, listener)` * `channel` string * `listener` Function * `event` [IpcMainServiceWorkerEvent][ipc-main-service-worker-event] * `...args` any[] Listens to `channel`, when a new message arrives `listener` would be called with `listener(event, args...)`. #### `ipcMainServiceWorker.once(channel, listener)` * `channel` string * `listener` Function * `event` [IpcMainServiceWorkerEvent][ipc-main-service-worker-event] * `...args` any[] Adds a one time `listener` function for the event. This `listener` is invoked only the next time a message is sent to `channel`, after which it is removed. #### `ipcMainServiceWorker.removeListener(channel, listener)` * `channel` string * `listener` Function * `...args` any[] Removes the specified `listener` from the listener array for the specified `channel`. #### `ipcMainServiceWorker.removeAllListeners([channel])` * `channel` string (optional) Removes listeners of the specified `channel`. #### `ipcMainServiceWorker.handle(channel, listener)` * `channel` string * `listener` Function\ | any\> * `event` [IpcMainServiceWorkerInvokeEvent][ipc-main-service-worker-invoke-event] * `...args` any[] #### `ipcMainServiceWorker.handleOnce(channel, listener)` * `channel` string * `listener` Function\ | any\> * `event` [IpcMainServiceWorkerInvokeEvent][ipc-main-service-worker-invoke-event] * `...args` any[] Handles a single `invoke`able IPC message, then removes the listener. See `ipcMainServiceWorker.handle(channel, listener)`. #### `ipcMainServiceWorker.removeHandler(channel)` * `channel` string Removes any handler for `channel`, if present. [ipc-main-service-worker-event]:../api/structures/ipc-main-service-worker-event.md [ipc-main-service-worker-invoke-event]:../api/structures/ipc-main-service-worker-invoke-event.md --- --- title: "ipcMain" description: "Communicate asynchronously from the main process to renderer processes." slug: ipc-main hide_title: false --- # ipcMain > Communicate asynchronously from the main process to renderer processes. Process: [Main](../glossary.md#main-process) The `ipcMain` module is an [Event Emitter][event-emitter]. When used in the main process, it handles asynchronous and synchronous messages sent from a renderer process (web page). Messages sent from a renderer will be emitted to this module. For usage examples, check out the [IPC tutorial][]. ## Sending messages It is also possible to send messages from the main process to the renderer process, see [webContents.send][web-contents-send] for more information. * When sending a message, the event name is the `channel`. * To reply to a synchronous message, you need to set `event.returnValue`. * To send an asynchronous message back to the sender, you can use `event.reply(...)`. This helper method will automatically handle messages coming from frames that aren't the main frame (e.g. iframes) whereas `event.sender.send(...)` will always send to the main frame. ## Methods The `ipcMain` module has the following methods to listen for events: ### `ipcMain.on(channel, listener)` * `channel` string * `listener` Function * `event` [IpcMainEvent][ipc-main-event] * `...args` any[] Listens to `channel`, when a new message arrives `listener` would be called with `listener(event, args...)`. ### `ipcMain.off(channel, listener)` * `channel` string * `listener` Function * `event` [IpcMainEvent][ipc-main-event] * `...args` any[] Removes the specified `listener` from the listener array for the specified `channel`. ### `ipcMain.once(channel, listener)` * `channel` string * `listener` Function * `event` [IpcMainEvent][ipc-main-event] * `...args` any[] Adds a one time `listener` function for the event. This `listener` is invoked only the next time a message is sent to `channel`, after which it is removed. ### `ipcMain.addListener(channel, listener)` * `channel` string * `listener` Function * `event` [IpcMainEvent][ipc-main-event] * `...args` any[] Alias for [`ipcMain.on`](#ipcmainonchannel-listener). ### `ipcMain.removeListener(channel, listener)` * `channel` string * `listener` Function * `...args` any[] Alias for [`ipcMain.off`](#ipcmainoffchannel-listener). ### `ipcMain.removeAllListeners([channel])` * `channel` string (optional) Removes all listeners from the specified `channel`. Removes all listeners from all channels if no channel is specified. ### `ipcMain.handle(channel, listener)` * `channel` string * `listener` Function\ | any\> * `event` [IpcMainInvokeEvent][ipc-main-invoke-event] * `...args` any[] Adds a handler for an `invoke`able IPC. This handler will be called whenever a renderer calls `ipcRenderer.invoke(channel, ...args)`. If `listener` returns a Promise, the eventual result of the promise will be returned as a reply to the remote caller. Otherwise, the return value of the listener will be used as the value of the reply. ```js title='Main Process' @ts-type={somePromise:(...args:unknown[])=>Promise} ipcMain.handle('my-invokable-ipc', async (event, ...args) => { const result = await somePromise(...args) return result }) ``` ```js title='Renderer Process' @ts-type={arg1:unknown} @ts-type={arg2:unknown} async () => { const result = await ipcRenderer.invoke('my-invokable-ipc', arg1, arg2) // ... } ``` The `event` that is passed as the first argument to the handler is the same as that passed to a regular event listener. It includes information about which WebContents is the source of the invoke request. Errors thrown through `handle` in the main process are not transparent as they are serialized and only the `message` property from the original error is provided to the renderer process. Please refer to [#24427](https://github.com/electron/electron/issues/24427) for details. ### `ipcMain.handleOnce(channel, listener)` * `channel` string * `listener` Function\ | any\> * `event` [IpcMainInvokeEvent][ipc-main-invoke-event] * `...args` any[] Handles a single `invoke`able IPC message, then removes the listener. See `ipcMain.handle(channel, listener)`. ### `ipcMain.removeHandler(channel)` * `channel` string Removes any handler for `channel`, if present. [IPC tutorial]: ../tutorial/ipc.md [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [web-contents-send]: ../api/web-contents.md#contentssendchannel-args [ipc-main-event]:../api/structures/ipc-main-event.md [ipc-main-invoke-event]:../api/structures/ipc-main-invoke-event.md --- --- title: "ipcRenderer" description: "Communicate asynchronously from a renderer process to the main process." slug: ipc-renderer hide_title: false --- # ipcRenderer > Communicate asynchronously from a renderer process to the main process. Process: [Renderer](../glossary.md#renderer-process) > [!IMPORTANT] > If you want to call this API from a renderer process with context isolation enabled, > place the API call in your preload script and > [expose](../tutorial/context-isolation.md#after-context-isolation-enabled) it using the > [`contextBridge`](context-bridge.md) API. The `ipcRenderer` module is an [EventEmitter][event-emitter]. It provides a few methods so you can send synchronous and asynchronous messages from the render process (web page) to the main process. You can also receive replies from the main process. See [IPC tutorial](../tutorial/ipc.md) for code examples. ## Methods The `ipcRenderer` module has the following method to listen for events and send messages: ### `ipcRenderer.on(channel, listener)` * `channel` string * `listener` Function * `event` [IpcRendererEvent][ipc-renderer-event] * `...args` any[] Listens to `channel`, when a new message arrives `listener` would be called with `listener(event, args...)`. :::warning Do not expose the `event` argument to the renderer for security reasons! Wrap any callback that you receive from the renderer in another function like this: `ipcRenderer.on('my-channel', (event, ...args) => callback(...args))`. Not wrapping the callback in such a function would expose dangerous Electron APIs to the renderer process. See the [security guide](../tutorial/security.md#20-do-not-expose-electron-apis-to-untrusted-web-content) for more info. ::: ### `ipcRenderer.off(channel, listener)` * `channel` string * `listener` Function * `event` [IpcRendererEvent][ipc-renderer-event] * `...args` any[] Removes the specified `listener` from the listener array for the specified `channel`. ### `ipcRenderer.once(channel, listener)` * `channel` string * `listener` Function * `event` [IpcRendererEvent][ipc-renderer-event] * `...args` any[] Adds a one time `listener` function for the event. This `listener` is invoked only the next time a message is sent to `channel`, after which it is removed. ### `ipcRenderer.addListener(channel, listener)` * `channel` string * `listener` Function * `event` [IpcRendererEvent][ipc-renderer-event] * `...args` any[] Alias for [`ipcRenderer.on`](#ipcrendereronchannel-listener). ### `ipcRenderer.removeListener(channel, listener)` * `channel` string * `listener` Function * `event` [IpcRendererEvent][ipc-renderer-event] * `...args` any[] Alias for [`ipcRenderer.off`](#ipcrendereroffchannel-listener). ### `ipcRenderer.removeAllListeners([channel])` * `channel` string (optional) Removes all listeners from the specified `channel`. Removes all listeners from all channels if no channel is specified. ### `ipcRenderer.send(channel, ...args)` * `channel` string * `...args` any[] Send an asynchronous message to the main process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`window.postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE:** Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. > > Since the main process does not have support for DOM objects such as > `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over > Electron's IPC to the main process, as the main process would have no way to decode > them. Attempting to send such objects over IPC will result in an error. The main process handles it by listening for `channel` with the [`ipcMain`](./ipc-main.md) module. If you need to transfer a [`MessagePort`][] to the main process, use [`ipcRenderer.postMessage`](#ipcrendererpostmessagechannel-message-transfer). If you want to receive a single response from the main process, like the result of a method call, consider using [`ipcRenderer.invoke`](#ipcrendererinvokechannel-args). ### `ipcRenderer.invoke(channel, ...args)` * `channel` string * `...args` any[] Returns `Promise` - Resolves with the response from the main process. Send a message to the main process via `channel` and expect a result asynchronously. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`window.postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. The main process should listen for `channel` with [`ipcMain.handle()`](./ipc-main.md#ipcmainhandlechannel-listener). For example: ```js @ts-type={someArgument:unknown} @ts-type={doSomeWork:(arg:unknown)=>Promise} // Renderer process ipcRenderer.invoke('some-name', someArgument).then((result) => { // ... }) // Main process ipcMain.handle('some-name', async (event, someArgument) => { const result = await doSomeWork(someArgument) return result }) ``` If you need to transfer a [`MessagePort`][] to the main process, use [`ipcRenderer.postMessage`](#ipcrendererpostmessagechannel-message-transfer). If you do not need a response to the message, consider using [`ipcRenderer.send`](#ipcrenderersendchannel-args). > [!NOTE] > Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. > > Since the main process does not have support for DOM objects such as > `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over > Electron's IPC to the main process, as the main process would have no way to decode > them. Attempting to send such objects over IPC will result in an error. > [!NOTE] > If the handler in the main process throws an error, > the promise returned by `invoke` will reject. > However, the `Error` object in the renderer process > will not be the same as the one thrown in the main process. ### `ipcRenderer.sendSync(channel, ...args)` * `channel` string * `...args` any[] Returns `any` - The value sent back by the [`ipcMain`](./ipc-main.md) handler. Send a message to the main process via `channel` and expect a result synchronously. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`window.postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE:** Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. > > Since the main process does not have support for DOM objects such as > `ImageBitmap`, `File`, `DOMMatrix` and so on, such objects cannot be sent over > Electron's IPC to the main process, as the main process would have no way to decode > them. Attempting to send such objects over IPC will result in an error. The main process handles it by listening for `channel` with [`ipcMain`](./ipc-main.md) module, and replies by setting `event.returnValue`. > [!WARNING] > Sending a synchronous message will block the whole > renderer process until the reply is received, so use this method only as a > last resort. It's much better to use the asynchronous version, > [`invoke()`](./ipc-renderer.md#ipcrendererinvokechannel-args). ### `ipcRenderer.postMessage(channel, message, [transfer])` * `channel` string * `message` any * `transfer` MessagePort[] (optional) Send a message to the main process, optionally transferring ownership of zero or more [`MessagePort`][] objects. The transferred `MessagePort` objects will be available in the main process as [`MessagePortMain`](./message-port-main.md) objects by accessing the `ports` property of the emitted event. For example: ```js // Renderer process const { port1, port2 } = new MessageChannel() ipcRenderer.postMessage('port', { message: 'hello' }, [port1]) // Main process ipcMain.on('port', (e, msg) => { const [port] = e.ports // ... }) ``` For more information on using `MessagePort` and `MessageChannel`, see the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel). ### `ipcRenderer.sendToHost(channel, ...args)` * `channel` string * `...args` any[] Like `ipcRenderer.send` but the event will be sent to the `` element in the host page instead of the main process. [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`window.postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage [`MessagePort`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort [ipc-renderer-event]: ./structures/ipc-renderer-event.md --- # MenuItem ## Class: MenuItem > Add items to native application menus and context menus. Process: [Main](../glossary.md#main-process) See [`Menu`](menu.md) for examples. > [!WARNING] > Electron's built-in classes cannot be subclassed in user code. > For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules). ### `new MenuItem(options)` * `options` Object * `click` Function (optional) - Will be called with `click(menuItem, window, event)` when the menu item is clicked. * `menuItem` MenuItem * `window` [BaseWindow](base-window.md) | undefined - This will not be defined if no window is open. * `event` [KeyboardEvent](structures/keyboard-event.md) * `role` string (optional) - Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `toggleSpellChecker`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `showSubstitutions`, `toggleSmartQuotes`, `toggleSmartDashes`, `toggleTextReplacement`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `shareMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `showAllTabs`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu` - Define the action of the menu item, when specified the `click` property will be ignored. See [roles](../tutorial/menus.md#roles). * `type` string (optional) * `normal` * `separator` * `submenu` * `checkbox` * `radio` * `header` - Only available on macOS 14 and up. * `palette` - Only available on macOS 14 and up. * `label` string (optional) * `sublabel` string (optional) _macOS_ - Available in macOS >= 14.4 * `toolTip` string (optional) _macOS_ - Hover text for this menu item. * `accelerator` string (optional) - An [Accelerator](../tutorial/keyboard-shortcuts.md#accelerators) string. * `icon` ([NativeImage](native-image.md) | string) (optional) - Can be a [NativeImage](native-image.md) or the file path of an icon. * `enabled` boolean (optional) - If false, the menu item will be greyed out and unclickable. * `acceleratorWorksWhenHidden` boolean (optional) _macOS_ - default is `true`, and when `false` will prevent the accelerator from triggering the item if the item is not visible. * `visible` boolean (optional) - If false, the menu item will be entirely hidden. * `checked` boolean (optional) - Should only be specified for `checkbox` or `radio` type menu items. * `registerAccelerator` boolean (optional) _Linux_ _Windows_ - If false, the accelerator won't be registered with the system, but it will still be displayed. Defaults to true. * `sharingItem` SharingItem (optional) _macOS_ - The item to share when the `role` is `shareMenu`. * `submenu` (MenuItemConstructorOptions[] | [Menu](menu.md)) (optional) - Should be specified for `submenu` type menu items. If `submenu` is specified, the `type: 'submenu'` can be omitted. If the value is not a [`Menu`](menu.md) then it will be automatically converted to one using `Menu.buildFromTemplate`. * `id` string (optional) - Unique within a single menu. If defined then it can be used as a reference to this item by the position attribute. * `before` string[] (optional) - Inserts this item before the item with the specified id. If the referenced item doesn't exist the item will be inserted at the end of the menu. Also implies that the menu item in question should be placed in the same “group” as the item. * `after` string[] (optional) - Inserts this item after the item with the specified id. If the referenced item doesn't exist the item will be inserted at the end of the menu. * `beforeGroupContaining` string[] (optional) - Provides a means for a single context menu to declare the placement of their containing group before the containing group of the item with the specified id. * `afterGroupContaining` string[] (optional) - Provides a means for a single context menu to declare the placement of their containing group after the containing group of the item with the specified id. > [!NOTE] > `acceleratorWorksWhenHidden` is specified as being macOS-only because accelerators always work when items are hidden on Windows and Linux. The option is exposed to users to give them the option to turn it off, as this is possible in native macOS development. ### Instance Properties The following properties are available on instances of `MenuItem`: #### `menuItem.id` A `string` indicating the item's unique id. This property can be dynamically changed. #### `menuItem.label` A `string` indicating the item's visible label. #### `menuItem.click` A `Function` that is fired when the MenuItem receives a click event. It can be called with `menuItem.click(event, focusedWindow, focusedWebContents)`. * `event` [KeyboardEvent](structures/keyboard-event.md) * `focusedWindow` [BaseWindow](browser-window.md) * `focusedWebContents` [WebContents](web-contents.md) #### `menuItem.submenu` A `Menu` (optional) containing the menu item's submenu, if present. #### `menuItem.type` A `string` indicating the type of the item. Can be `normal`, `separator`, `submenu`, `checkbox`, `radio`, `header` or `palette`. > [!NOTE] > `header` and `palette` are only available on macOS 14 and up. #### `menuItem.role` A `string` (optional) indicating the item's role, if set. Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `toggleSpellChecker`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `shareMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `showAllTabs`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu` #### `menuItem.accelerator` An `Accelerator` (optional) indicating the item's accelerator, if set. #### `menuItem.userAccelerator` _Readonly_ _macOS_ An `Accelerator | null` indicating the item's [user-assigned accelerator](https://developer.apple.com/documentation/appkit/nsmenuitem/1514850-userkeyequivalent?language=objc) for the menu item. > [!NOTE] > This property is only initialized after the `MenuItem` has been added to a `Menu`. Either via `Menu.buildFromTemplate` or via `Menu.append()/insert()`. Accessing before initialization will just return `null`. #### `menuItem.icon` A `NativeImage | string` (optional) indicating the item's icon, if set. #### `menuItem.sublabel` A `string` indicating the item's sublabel. #### `menuItem.toolTip` _macOS_ A `string` indicating the item's hover text. #### `menuItem.enabled` A `boolean` indicating whether the item is enabled. This property can be dynamically changed. #### `menuItem.visible` A `boolean` indicating whether the item is visible. This property can be dynamically changed. #### `menuItem.checked` A `boolean` indicating whether the item is checked. This property can be dynamically changed. A `checkbox` menu item will toggle the `checked` property on and off when selected. A `radio` menu item will turn on its `checked` property when clicked, and will turn off that property for all adjacent items in the same menu. You can add a `click` function for additional behavior. #### `menuItem.registerAccelerator` A `boolean` indicating if the accelerator should be registered with the system or just displayed. This property can be dynamically changed. #### `menuItem.sharingItem` _macOS_ A `SharingItem` indicating the item to share when the `role` is `shareMenu`. This property can be dynamically changed. #### `menuItem.commandId` A `number` indicating an item's sequential unique id. #### `menuItem.menu` A `Menu` that the item is a part of. --- # Menu ## Class: Menu > Create application menus and context menus. Process: [Main](../glossary.md#main-process) The presentation of menus varies depending on the operating system: - Under Windows and Linux, menus are visually similar to Chromium. - Under macOS, these will be native menus. > [!TIP] > See also: [A detailed guide about how to implement menus in your application](../tutorial/menus.md). > [!WARNING] > Electron's built-in classes cannot be subclassed in user code. > For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules). ### `new Menu()` Creates a new menu. ### Static Methods The `Menu` class has the following static methods: #### `Menu.setApplicationMenu(menu)` - `menu` Menu | null Sets `menu` as the application menu on macOS. On Windows and Linux, the `menu` will be set as each window's top menu. Also on Windows and Linux, you can use a `&` in the top-level item name to indicate which letter should get a generated accelerator. For example, using `&File` for the file menu would result in a generated `Alt-F` accelerator that opens the associated menu. The indicated character in the button label then gets an underline, and the `&` character is not displayed on the button label. In order to escape the `&` character in an item name, add a proceeding `&`. For example, `&&File` would result in `&File` displayed on the button label. Passing `null` will suppress the default menu. On Windows and Linux, this has the additional effect of removing the menu bar from the window. > [!NOTE] > The default menu will be created automatically if the app does not set one. > It contains standard items such as `File`, `Edit`, `View`, `Window` and `Help`. #### `Menu.getApplicationMenu()` Returns `Menu | null` - The application menu, if set, or `null`, if not set. > [!NOTE] > The returned `Menu` instance doesn't support dynamic addition or > removal of menu items. [Instance properties](#instance-properties) can still > be dynamically modified. #### `Menu.sendActionToFirstResponder(action)` _macOS_ - `action` string Sends the `action` to the first responder of application. This is used for emulating default macOS menu behaviors. Usually you would use the [`role`](../tutorial/menus.md#roles) property of a [`MenuItem`](menu-item.md). See the [macOS Cocoa Event Handling Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW7) for more information on macOS' native actions. #### `Menu.buildFromTemplate(template)` - `template` (MenuItemConstructorOptions | MenuItem)[] Returns `Menu` Generally, the `template` is an array of `options` for constructing a [MenuItem](menu-item.md). The usage can be referenced above. You can also attach other fields to the element of the `template` and they will become properties of the constructed menu items. ### Instance Methods The `menu` object has the following instance methods: #### `menu.popup([options])` - `options` Object (optional) - `window` [BaseWindow](base-window.md) (optional) - Default is the focused window. - `frame` [WebFrameMain](web-frame-main.md) (optional) - Provide the relevant frame if you want certain OS-level features such as Writing Tools on macOS to function correctly. Typically, this should be `params.frame` from the [`context-menu` event](web-contents.md#event-context-menu) on a WebContents, or the [`focusedFrame` property](web-contents.md#contentsfocusedframe-readonly) of a WebContents. - `x` number (optional) - Default is the current mouse cursor position. Must be declared if `y` is declared. - `y` number (optional) - Default is the current mouse cursor position. Must be declared if `x` is declared. - `positioningItem` number (optional) _macOS_ - The index of the menu item to be positioned under the mouse cursor at the specified coordinates. Default is -1. - `sourceType` string (optional) _Windows_ _Linux_ - This should map to the `menuSourceType` provided by the `context-menu` event. It is not recommended to set this value manually, only provide values you receive from other APIs or leave it `undefined`. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. - `callback` Function (optional) - Called when menu is closed. Pops up this menu as a context menu in the [`BaseWindow`](base-window.md). > [!TIP] > For more details, see the [Context Menu](../tutorial/context-menu.md) guide. #### `menu.closePopup([window])` - `window` [BaseWindow](base-window.md) (optional) - Default is the focused window. Closes the context menu in the `window`. #### `menu.append(menuItem)` - `menuItem` [MenuItem](menu-item.md) Appends the `menuItem` to the menu. #### `menu.getMenuItemById(id)` - `id` string Returns `MenuItem | null` the item with the specified `id` #### `menu.insert(pos, menuItem)` - `pos` Integer - `menuItem` [MenuItem](menu-item.md) Inserts the `menuItem` to the `pos` position of the menu. ### Instance Events Objects created with `new Menu` or returned by `Menu.buildFromTemplate` emit the following events: > [!NOTE] > Some events are only available on specific operating systems and are > labeled as such. #### Event: 'menu-will-show' Returns: - `event` Event Emitted when `menu.popup()` is called. #### Event: 'menu-will-close' Returns: - `event` Event Emitted when a popup is closed either manually or with `menu.closePopup()`. ### Instance Properties `menu` objects also have the following properties: #### `menu.items` A `MenuItem[]` array containing the menu's items. Each `Menu` consists of multiple [`MenuItem`](menu-item.md) instances and each `MenuItem` can nest a `Menu` into its `submenu` property. --- # MessageChannelMain `MessageChannelMain` is the main-process-side equivalent of the DOM [`MessageChannel`][] object. Its singular function is to create a pair of connected [`MessagePortMain`](message-port-main.md) objects. See the [Channel Messaging API][] documentation for more information on using channel messaging. ## Class: MessageChannelMain > Channel interface for channel messaging in the main process. Process: [Main](../glossary.md#main-process) Example: ```js // Main process const { BrowserWindow, MessageChannelMain } = require('electron') const w = new BrowserWindow() const { port1, port2 } = new MessageChannelMain() w.webContents.postMessage('port', null, [port2]) port1.postMessage({ some: 'message' }) // Renderer process const { ipcRenderer } = require('electron') ipcRenderer.on('port', (e) => { // e.ports is a list of ports sent along with this message e.ports[0].onmessage = (messageEvent) => { console.log(messageEvent.data) } }) ``` > [!WARNING] > Electron's built-in classes cannot be subclassed in user code. > For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules). ### Instance Properties #### `channel.port1` A [`MessagePortMain`](message-port-main.md) property. #### `channel.port2` A [`MessagePortMain`](message-port-main.md) property. [`MessageChannel`]: https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel [Channel Messaging API]: https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API --- # MessagePortMain `MessagePortMain` is the main-process-side equivalent of the DOM [`MessagePort`][] object. It behaves similarly to the DOM version, with the exception that it uses the Node.js `EventEmitter` event system, instead of the DOM `EventTarget` system. This means you should use `port.on('message', ...)` to listen for events, instead of `port.onmessage = ...` or `port.addEventListener('message', ...)` See the [Channel Messaging API][] documentation for more information on using channel messaging. `MessagePortMain` is an [EventEmitter][event-emitter]. ## Class: MessagePortMain > Port interface for channel messaging in the main process. Process: [Main](../glossary.md#main-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ ### Instance Methods #### `port.postMessage(message, [transfer])` * `message` any * `transfer` MessagePortMain[] (optional) Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts. #### `port.start()` Starts the sending of messages queued on the port. Messages will be queued until this method is called. #### `port.close()` Disconnects the port, so it is no longer active. ### Instance Events #### Event: 'message' Returns: * `messageEvent` Object * `data` any * `ports` MessagePortMain[] Emitted when a MessagePortMain object receives a message. #### Event: 'close' Emitted when the remote end of a MessagePortMain object becomes disconnected. [`MessagePort`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort [Channel Messaging API]: https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter --- # nativeImage > Create tray, dock, and application icons using PNG or JPG files. Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) > [!IMPORTANT] > If you want to call this API from a renderer process with context isolation enabled, > place the API call in your preload script and > [expose](../tutorial/context-isolation.md#after-context-isolation-enabled) it using the > [`contextBridge`](context-bridge.md) API. The `nativeImage` module provides a unified interface for manipulating system images. These can be handy if you want to provide multiple scaled versions of the same icon or take advantage of macOS [template images][template-image]. Electron APIs that take image files accept either file paths or `NativeImage` instances. An empty and transparent image will be used when `null` is passed. For example, when creating a [Tray](../api/tray.md) or setting a [BrowserWindow](../api/browser-window.md)'s icon, you can either pass an image file path as a string: ```js title='Main Process' const { BrowserWindow, Tray } = require('electron') const tray = new Tray('/Users/somebody/images/icon.png') const win = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }) ``` or generate a `NativeImage` instance from the same file: ```js title='Main Process' const { BrowserWindow, nativeImage, Tray } = require('electron') const trayIcon = nativeImage.createFromPath('/Users/somebody/images/icon.png') const appIcon = nativeImage.createFromPath('/Users/somebody/images/window.png') const tray = new Tray(trayIcon) const win = new BrowserWindow({ icon: appIcon }) ``` ## Supported Formats Currently, `PNG` and `JPEG` image formats are supported across all platforms. `PNG` is recommended because of its support for transparency and lossless compression. On Windows, you can also load `ICO` icons from file paths. For best visual quality, we recommend including at least the following sizes: * Small icon * 16x16 (100% DPI scale) * 20x20 (125% DPI scale) * 24x24 (150% DPI scale) * 32x32 (200% DPI scale) * Large icon * 32x32 (100% DPI scale) * 40x40 (125% DPI scale) * 48x48 (150% DPI scale) * 64x64 (200% DPI scale) * 256x256 Check the _Icon Scaling_ section in the Windows [App Icon Construction][icons] reference. [icons]: https://learn.microsoft.com/en-us/windows/apps/design/style/iconography/app-icon-construction#icon-scaling :::note EXIF metadata is currently not supported and will not be taken into account during image encoding and decoding. ::: ## High Resolution Image On platforms that support high pixel density displays (such as Apple Retina), you can append `@2x` after image's base filename to mark it as a 2x scale high resolution image. For example, if `icon.png` is a normal image that has standard resolution, then `icon@2x.png` will be treated as a high resolution image that has double Dots per Inch (DPI) density. If you want to support displays with different DPI densities at the same time, you can put images with different sizes in the same folder and use the filename without DPI suffixes within Electron. For example: ```plaintext images/ ├── icon.png ├── icon@2x.png └── icon@3x.png ``` ```js title='Main Process' const { Tray } = require('electron') const appTray = new Tray('/Users/somebody/images/icon.png') ``` The following suffixes for DPI are also supported: * `@1x` * `@1.25x` * `@1.33x` * `@1.4x` * `@1.5x` * `@1.8x` * `@2x` * `@2.5x` * `@3x` * `@4x` * `@5x` ## Template Image _macOS_ On macOS, [template images][template-image] consist of black and an alpha channel. Template images are not intended to be used as standalone images and are usually mixed with other content to create the desired final appearance. The most common case is to use template images for a menu bar (Tray) icon, so it can adapt to both light and dark menu bars. To mark an image as a template image, its base filename should end with the word `Template` (e.g. `xxxTemplate.png`). You can also specify template images at different DPI densities (e.g. `xxxTemplate@2x.png`). ## Methods The `nativeImage` module has the following methods, all of which return an instance of the [`NativeImage`](#class-nativeimage) class: ### `nativeImage.createEmpty()` Returns `NativeImage` Creates an empty `NativeImage` instance. ### `nativeImage.createThumbnailFromPath(path, size)` _macOS_ _Windows_ * `path` string - path to a file that we intend to construct a thumbnail out of. * `size` [Size](structures/size.md) - the desired width and height (positive numbers) of the thumbnail. Returns `Promise` - fulfilled with the file's thumbnail preview image, which is a [NativeImage](native-image.md). > [!NOTE] > Windows implementation will ignore `size.height` and scale the height according to `size.width`. ### `nativeImage.createFromPath(path)` * `path` string - path to a file that we intend to construct an image out of. Returns `NativeImage` Creates a new `NativeImage` instance from an image file (e.g., PNG or JPEG) located at `path`. This method returns an empty image if the `path` does not exist, cannot be read, or is not a valid image. ```js const { nativeImage } = require('electron') const image = nativeImage.createFromPath('/Users/somebody/images/icon.png') console.log(image) ``` ### `nativeImage.createFromBitmap(buffer, options)` * `buffer` [Buffer][buffer] * `options` Object * `width` Integer * `height` Integer * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `NativeImage` Creates a new `NativeImage` instance from `buffer` that contains the raw bitmap pixel data returned by `toBitmap()`. The specific format is platform-dependent. ### `nativeImage.createFromBuffer(buffer[, options])` * `buffer` [Buffer][buffer] * `options` Object (optional) * `width` Integer (optional) - Required for bitmap buffers. * `height` Integer (optional) - Required for bitmap buffers. * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `NativeImage` Creates a new `NativeImage` instance from `buffer`. Tries to decode as PNG or JPEG first. ### `nativeImage.createFromDataURL(dataURL)` * `dataURL` string Returns `NativeImage` Creates a new `NativeImage` instance from `dataUrl`, a base 64 encoded [Data URL][data-url] string. ### `nativeImage.createFromNamedImage(imageName[, hslShift])` _macOS_ * `imageName` string * `hslShift` number[] (optional) Returns `NativeImage` Creates a new `NativeImage` instance from the `NSImage` that maps to the given image name. See Apple's [`NSImageName`](https://developer.apple.com/documentation/appkit/nsimagename#2901388) documentation and [SF Symbols](https://developer.apple.com/sf-symbols/) for a list of possible values. The `hslShift` is applied to the image with the following rules: * `hsl_shift[0]` (hue): The absolute hue value for the image - 0 and 1 map to 0 and 360 on the hue color wheel (red). * `hsl_shift[1]` (saturation): A saturation shift for the image, with the following key values: 0 = remove all color. 0.5 = leave unchanged. 1 = fully saturate the image. * `hsl_shift[2]` (lightness): A lightness shift for the image, with the following key values: 0 = remove all lightness (make all pixels black). 0.5 = leave unchanged. 1 = full lightness (make all pixels white). This means that `[-1, 0, 1]` will make the image completely white and `[-1, 1, 0]` will make the image completely black. In some cases, the `NSImageName` doesn't match its string representation; one example of this is `NSFolderImageName`, whose string representation would actually be `NSFolder`. Therefore, you'll need to determine the correct string representation for your image before passing it in. This can be done with the following: ```sh echo -e '#import \nint main() { NSLog(@"%@", SYSTEM_IMAGE_NAME); }' | clang -otest -x objective-c -framework Cocoa - && ./test ``` where `SYSTEM_IMAGE_NAME` should be replaced with any value from [this list](https://developer.apple.com/documentation/appkit/nsimagename?language=objc). For SF Symbols, usage looks as follows: ```js const image = nativeImage.createFromNamedImage('square.and.pencil') ``` where `'square.and.pencil'` is the symbol name from the [SF Symbols app](https://developer.apple.com/sf-symbols/). ## Class: NativeImage > Natively wrap images such as tray, dock, and application icons. Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ ### Instance Methods The following methods are available on instances of the `NativeImage` class: #### `image.toPNG([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains the image's `PNG` encoded data. #### `image.toJPEG(quality)` * `quality` Integer - Between 0 - 100. Returns `Buffer` - A [Buffer][buffer] that contains the image's `JPEG` encoded data. #### `image.toBitmap([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Buffer` - A [Buffer][buffer] that contains a copy of the image's raw bitmap pixel data. #### `image.toDataURL([options])` * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `string` - The [Data URL][data-url] of the image. #### `image.getBitmap([options])` _Deprecated_ * `options` Object (optional) * `scaleFactor` Number (optional) - Defaults to 1.0. Legacy alias for `image.toBitmap()`. #### `image.getNativeHandle()` _macOS_ Returns `Buffer` - A [Buffer][buffer] that stores C pointer to underlying native handle of the image. On macOS, a pointer to `NSImage` instance is returned. Notice that the returned pointer is a weak pointer to the underlying native image instead of a copy, so you _must_ ensure that the associated `nativeImage` instance is kept around. #### `image.isEmpty()` Returns `boolean` - Whether the image is empty. #### `image.getSize([scaleFactor])` * `scaleFactor` Number (optional) - Defaults to 1.0. Returns [`Size`](structures/size.md). If `scaleFactor` is passed, this will return the size corresponding to the image representation most closely matching the passed value. #### `image.setTemplateImage(option)` * `option` boolean Marks the image as a macOS [template image][template-image]. #### `image.isTemplateImage()` Returns `boolean` - Whether the image is a macOS [template image][template-image]. #### `image.crop(rect)` * `rect` [Rectangle](structures/rectangle.md) - The area of the image to crop. Returns `NativeImage` - The cropped image. #### `image.resize(options)` * `options` Object * `width` Integer (optional) - Defaults to the image's width. * `height` Integer (optional) - Defaults to the image's height. * `quality` string (optional) - The desired quality of the resize image. Possible values include `good`, `better`, or `best`. The default is `best`. These values express a desired quality/speed tradeoff. They are translated into an algorithm-specific method that depends on the capabilities (CPU, GPU) of the underlying platform. It is possible for all three methods to be mapped to the same algorithm on a given platform. Returns `NativeImage` - The resized image. If only the `height` or the `width` are specified then the current aspect ratio will be preserved in the resized image. #### `image.getAspectRatio([scaleFactor])` * `scaleFactor` Number (optional) - Defaults to 1.0. Returns `Number` - The image's aspect ratio (width divided by height). If `scaleFactor` is passed, this will return the aspect ratio corresponding to the image representation most closely matching the passed value. #### `image.getScaleFactors()` Returns `Number[]` - An array of all scale factors corresponding to representations for a given `NativeImage`. #### `image.addRepresentation(options)` * `options` Object * `scaleFactor` Number (optional) - The scale factor to add the image representation for. * `width` Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as `buffer`. * `height` Integer (optional) - Defaults to 0. Required if a bitmap buffer is specified as `buffer`. * `buffer` Buffer (optional) - The buffer containing the raw image data. * `dataURL` string (optional) - The data URL containing either a base 64 encoded PNG or JPEG image. Add an image representation for a specific scale factor. This can be used to programmatically add different scale factor representations to an image. This can be called on empty images. ### Instance Properties #### `nativeImage.isMacTemplateImage` _macOS_ A `boolean` property that determines whether the image is considered a [template image][template-image]. Please note that this property only has an effect on macOS. [buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer [data-url]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs [template-image]: https://developer.apple.com/documentation/appkit/nsimage/1520017-template --- # nativeTheme > Read and respond to changes in Chromium's native color theme. Process: [Main](../glossary.md#main-process) ## Events The `nativeTheme` module emits the following events: ### Event: 'updated' Emitted when something in the underlying NativeTheme has changed. This normally means that either the value of `shouldUseDarkColors`, `shouldUseHighContrastColors` or `shouldUseInvertedColorScheme` has changed. You will have to check them to determine which one has changed. ## Properties The `nativeTheme` module has the following properties: ### `nativeTheme.shouldUseDarkColors` _Readonly_ A `boolean` for if the OS / Chromium currently has a dark mode enabled or is being instructed to show a dark-style UI. If you want to modify this value you should use `themeSource` below. ### `nativeTheme.themeSource` A `string` property that can be `system`, `light` or `dark`. It is used to override and supersede the value that Chromium has chosen to use internally. Setting this property to `system` will remove the override and everything will be reset to the OS default. By default `themeSource` is `system`. Settings this property to `dark` will have the following effects: * `nativeTheme.shouldUseDarkColors` will be `true` when accessed * Any UI Electron renders on Linux and Windows including context menus, devtools, etc. will use the dark UI. * Any UI the OS renders on macOS including menus, window frames, etc. will use the dark UI. * The [`prefers-color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) CSS query will match `dark` mode. * The `updated` event will be emitted Settings this property to `light` will have the following effects: * `nativeTheme.shouldUseDarkColors` will be `false` when accessed * Any UI Electron renders on Linux and Windows including context menus, devtools, etc. will use the light UI. * Any UI the OS renders on macOS including menus, window frames, etc. will use the light UI. * The [`prefers-color-scheme`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) CSS query will match `light` mode. * The `updated` event will be emitted The usage of this property should align with a classic "dark mode" state machine in your application where the user has three options. * `Follow OS` --> `themeSource = 'system'` * `Dark Mode` --> `themeSource = 'dark'` * `Light Mode` --> `themeSource = 'light'` Your application should then always use `shouldUseDarkColors` to determine what CSS to apply. ### `nativeTheme.shouldUseHighContrastColors` _macOS_ _Windows_ _Readonly_ A `boolean` for if the OS / Chromium currently has high-contrast mode enabled or is being instructed to show a high-contrast UI. ### `nativeTheme.shouldUseDarkColorsForSystemIntegratedUI` _macOS_ _Windows_ _Readonly_ A `boolean` property indicating whether or not the system theme has been set to dark or light. On Windows this property distinguishes between system and app light/dark theme, returning `true` if the system theme is set to dark theme and `false` otherwise. On macOS the return value will be the same as `nativeTheme.shouldUseDarkColors`. ### `nativeTheme.shouldUseInvertedColorScheme` _macOS_ _Windows_ _Readonly_ A `boolean` for if the OS / Chromium currently has an inverted color scheme or is being instructed to use an inverted color scheme. ### `nativeTheme.inForcedColorsMode` _Windows_ _Readonly_ A `boolean` indicating whether Chromium is in forced colors mode, controlled by system accessibility settings. Currently, Windows high contrast is the only system setting that triggers forced colors mode. ### `nativeTheme.prefersReducedTransparency` _Readonly_ A `boolean` that indicates the whether the user has chosen via system accessibility settings to reduce transparency at the OS level. --- ## Class: NavigationHistory > Manage a list of navigation entries, representing the user's browsing history within the application. Process: [Main](../glossary.md#main-process)
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ Each [NavigationEntry](./structures/navigation-entry.md) corresponds to a specific visited page. The indexing system follows a sequential order, where the entry for the earliest visited page is at index 0 and the entry for the most recent visited page is at index N. Some APIs in this class also accept an _offset_, which is an integer representing the relative position of an index from the current entry according to the above indexing system (i.e. an offset value of `1` would represent going forward in history by one page). Maintaining this ordered list of navigation entries enables seamless navigation both backward and forward through the user's browsing history. ### Instance Methods #### `navigationHistory.canGoBack()` Returns `boolean` - Whether the browser can go back to previous web page. #### `navigationHistory.canGoForward()` Returns `boolean` - Whether the browser can go forward to next web page. #### `navigationHistory.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the web page can go to the specified relative `offset` from the current entry. #### `navigationHistory.clear()` Clears the navigation history. #### `navigationHistory.getActiveIndex()` Returns `Integer` - The index of the current page, from which we would go back/forward or reload. #### `navigationHistory.getEntryAtIndex(index)` * `index` Integer Returns [`NavigationEntry`](structures/navigation-entry.md) - Navigation entry at the given index. If index is out of bounds (greater than history length or less than 0), null will be returned. #### `navigationHistory.goBack()` Makes the browser go back a web page. #### `navigationHistory.goForward()` Makes the browser go forward a web page. #### `navigationHistory.goToIndex(index)` * `index` Integer Navigates browser to the specified absolute web page index. #### `navigationHistory.goToOffset(offset)` * `offset` Integer Navigates to the specified relative offset from the current entry. #### `navigationHistory.length()` Returns `Integer` - History length. #### `navigationHistory.removeEntryAtIndex(index)` * `index` Integer Removes the navigation entry at the given index. Can't remove entry at the "current active index". Returns `boolean` - Whether the navigation entry was removed from the webContents history. #### `navigationHistory.getAllEntries()` Returns [`NavigationEntry[]`](structures/navigation-entry.md) - WebContents complete history. #### `navigationHistory.restore(options)` Restores navigation history and loads the given entry in the in stack. Will make a best effort to restore not just the navigation stack but also the state of the individual pages - for instance including HTML form values or the scroll position. It's recommended to call this API before any navigation entries are created, so ideally before you call `loadURL()` or `loadFile()` on the `webContents` object. This API allows you to create common flows that aim to restore, recreate, or clone other webContents. * `options` Object * `entries` [NavigationEntry[]](structures/navigation-entry.md) - Result of a prior `getAllEntries()` call * `index` Integer (optional) - Index of the stack that should be loaded. If you set it to `0`, the webContents will load the first (oldest) entry. If you leave it undefined, Electron will automatically load the last (newest) entry. Returns `Promise` - the promise will resolve when the page has finished loading the selected navigation entry (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors. --- # netLog > Logging network events for a session. Process: [Main](../glossary.md#main-process) ```js 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) }) ``` See [`--log-net-log`](command-line-switches.md#--log-net-logpath) to log network events throughout the app's lifecycle. > [!NOTE] > All methods unless specified can only be used after the `ready` event > of the `app` module gets emitted. ## Methods ### `netLog.startLogging(path[, options])` * `path` string - File path to record network logs. * `options` Object (optional) * `captureMode` string (optional) - What kinds of data should be captured. By default, only metadata about requests will be captured. Setting this to `includeSensitive` will include cookies and authentication data. Setting it to `everything` will include all bytes transferred on sockets. Can be `default`, `includeSensitive` or `everything`. * `maxFileSize` number (optional) - When the log grows beyond this size, logging will automatically stop. Defaults to unlimited. Returns `Promise` - resolves when the net log has begun recording. Starts recording network events to `path`. ### `netLog.stopLogging()` Returns `Promise` - resolves when the net log has been flushed to disk. Stops recording network events. If not called, net logging will automatically end when app quits. ## Properties ### `netLog.currentlyLogging` _Readonly_ A `boolean` property that indicates whether network logs are currently being recorded. --- # net > Issue HTTP/HTTPS requests using Chromium's native networking library Process: [Main](../glossary.md#main-process), [Utility](../glossary.md#utility-process) The `net` module is a client-side API for issuing HTTP(S) requests. It is similar to the [HTTP](https://nodejs.org/api/http.html) and [HTTPS](https://nodejs.org/api/https.html) modules of Node.js but uses Chromium's native networking library instead of the Node.js implementation, offering better support for web proxies. It also supports checking network status. The following is a non-exhaustive list of why you may consider using the `net` module instead of the native Node.js modules: * Automatic management of system proxy configuration, support of the wpad protocol and proxy pac configuration files. * Automatic tunneling of HTTPS requests. * Support for authenticating proxies using basic, digest, NTLM, Kerberos or negotiate authentication schemes. * Support for traffic monitoring proxies: Fiddler-like proxies used for access control and monitoring. The API components (including classes, methods, properties and event names) are similar to those used in Node.js. Example usage: ```js 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() }) ``` 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. ## Methods The `net` module has the following methods: ### `net.request(options)` * `options` ([ClientRequestConstructorOptions](client-request.md#new-clientrequestoptions) | string) - The `ClientRequest` constructor options. Returns [`ClientRequest`](./client-request.md) Creates a [`ClientRequest`](./client-request.md) instance using the provided `options` which are directly forwarded to the `ClientRequest` constructor. The `net.request` method would be used to issue both secure and insecure HTTP requests according to the specified protocol scheme in the `options` object. ### `net.fetch(input[, init])` * `input` string | [GlobalRequest](https://nodejs.org/api/globals.html#request) * `init` [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) & \{ bypassCustomProtocolHandlers?: boolean \} (optional) Returns `Promise` - see [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). Sends a request, similarly to how `fetch()` works in the renderer, using Chrome's network stack. This differs from Node's `fetch()`, which uses Node.js's HTTP stack. Example: ```js async function example () { const response = await net.fetch('https://my.app') if (response.ok) { const body = await response.json() // ... use the result. } } ``` This method will issue requests from the [default session](session.md#sessiondefaultsession). To send a `fetch` request from another session, use [ses.fetch()](session.md#sesfetchinput-init). See the MDN documentation for [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for more details. 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. By default, requests made with `net.fetch` can be made to [custom protocols](protocol.md) as well as `file:`, and will trigger [webRequest](web-request.md) handlers if present. When the non-standard `bypassCustomProtocolHandlers` option is set in RequestInit, custom protocol handlers will not be called for this request. This allows forwarding an intercepted request to the built-in handler. [webRequest](web-request.md) handlers will still be triggered when bypassing custom protocols. ```js protocol.handle('https', (req) => { if (req.url === 'https://my-app.com') { return new Response('my app') } else { return net.fetch(req, { bypassCustomProtocolHandlers: true }) } }) ``` > [!NOTE] > In the [utility process](../glossary.md#utility-process), custom protocols > are not supported. ### `net.isOnline()` Returns `boolean` - Whether there is currently internet connection. A return value of `false` is a pretty 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.resolveHost(host, [options])` * `host` string - Hostname to resolve. * `options` Object (optional) * `queryType` string (optional) - Requested DNS query type. If unspecified, resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings: * `A` - Fetch only A records * `AAAA` - Fetch only AAAA records. * `source` string (optional) - The source to use for resolved addresses. Default allows the resolver to pick an appropriate source. Only affects use of big external sources (e.g. calling the system for resolution or using DNS). Even if a source is specified, results can still come from cache, resolving "localhost" or IP literals, etc. One of the following values: * `any` (default) - Resolver will pick an appropriate source. Results could come from DNS, MulticastDNS, HOSTS file, etc * `system` - Results will only be retrieved from the system or OS, e.g. via the `getaddrinfo()` system call * `dns` - Results will only come from DNS queries * `mdns` - Results will only come from Multicast DNS queries * `localOnly` - No external sources will be used. Results will only come from fast local sources that are available no matter the source setting, e.g. cache, hosts file, IP literal resolution, etc. * `cacheUsage` string (optional) - Indicates what DNS cache entries, if any, can be used to provide a response. One of the following values: * `allowed` (default) - Results may come from the host cache if non-stale * `staleAllowed` - Results may come from the host cache even if stale (by expiration or network changes) * `disallowed` - Results will not come from the host cache. * `secureDnsPolicy` string (optional) - Controls the resolver's Secure DNS behavior for this request. One of the following values: * `allow` (default) * `disable` Returns [`Promise`](structures/resolved-host.md) - Resolves with the resolved IP addresses for the `host`. This method will resolve hosts from the [default session](session.md#sessiondefaultsession). To resolve a host from another session, use [ses.resolveHost()](session.md#sesresolvehosthost-options). ## Properties ### `net.online` _Readonly_ A `boolean` property. Whether there is currently internet connection. A return value of `false` is a pretty 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. --- # Notification > Create OS desktop notifications Process: [Main](../glossary.md#main-process) > [!NOTE] > If you want to show notifications from a renderer process you should use the > [web Notifications API](../tutorial/notifications.md) ## Class: Notification > Create OS desktop notifications Process: [Main](../glossary.md#main-process) `Notification` is an [EventEmitter][event-emitter]. It creates a new `Notification` with native properties as set by the `options`. > [!WARNING] > Electron's built-in classes cannot be subclassed in user code. > For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules). ### Static Methods The `Notification` class has the following static methods: #### `Notification.isSupported()` Returns `boolean` - Whether or not desktop notifications are supported on the current system ### `new Notification([options])` * `options` Object (optional) * `title` string (optional) - A title for the notification, which will be displayed at the top of the notification window when it is shown. * `subtitle` string (optional) _macOS_ - A subtitle for the notification, which will be displayed below the title. * `body` string (optional) - The body text of the notification, which will be displayed below the title or subtitle. * `silent` boolean (optional) - Whether or not to suppress the OS notification noise when showing the notification. * `icon` (string | [NativeImage](native-image.md)) (optional) - An icon to use in the notification. If a string is passed, it must be a valid path to a local icon file. * `hasReply` boolean (optional) _macOS_ - Whether or not to add an inline reply option to the notification. * `timeoutType` string (optional) _Linux_ _Windows_ - The timeout duration of the notification. Can be 'default' or 'never'. * `replyPlaceholder` string (optional) _macOS_ - The placeholder to write in the inline reply input field. * `sound` string (optional) _macOS_ - The name of the sound file to play when the notification is shown. * `urgency` string (optional) _Linux_ - The urgency level of the notification. Can be 'normal', 'critical', or 'low'. * `actions` [NotificationAction[]](structures/notification-action.md) (optional) _macOS_ - Actions to add to the notification. Please read the available actions and limitations in the `NotificationAction` documentation. * `closeButtonText` string (optional) _macOS_ - A custom title for the close button of an alert. An empty string will cause the default localized text to be used. * `toastXml` string (optional) _Windows_ - A custom description of the Notification on Windows superseding all properties above. Provides full customization of design and behavior of the notification. ### Instance Events Objects created with `new Notification` emit the following events: :::info Some events are only available on specific operating systems and are labeled as such. ::: #### Event: 'show' Returns: * `event` Event Emitted when the notification is shown to the user. Note that this event can be fired multiple times as a notification can be shown multiple times through the `show()` method. #### Event: 'click' Returns: * `event` Event Emitted when the notification is clicked by the user. #### Event: 'close' Returns: * `event` Event Emitted when the notification is closed by manual intervention from the user. This event is not guaranteed to be emitted in all cases where the notification is closed. On Windows, the `close` event can be emitted in one of three ways: programmatic dismissal with `notification.close()`, by the user closing the notification, or via system timeout. If a notification is in the Action Center after the initial `close` event is emitted, a call to `notification.close()` will remove the notification from the action center but the `close` event will not be emitted again. #### Event: 'reply' _macOS_ Returns: * `event` Event * `reply` string - The string the user entered into the inline reply field. Emitted when the user clicks the "Reply" button on a notification with `hasReply: true`. #### Event: 'action' _macOS_ Returns: * `event` Event * `index` number - The index of the action that was activated. #### Event: 'failed' _Windows_ Returns: * `event` Event * `error` string - The error encountered during execution of the `show()` method. Emitted when an error is encountered while creating and showing the native notification. ### Instance Methods Objects created with the `new Notification()` constructor have the following instance methods: #### `notification.show()` Immediately shows the notification to the user. Unlike the web notification API, instantiating a `new Notification()` does not immediately show it to the user. Instead, you need to call this method before the OS will display it. If the notification has been shown before, this method will dismiss the previously shown notification and create a new one with identical properties. #### `notification.close()` Dismisses the notification. On Windows, calling `notification.close()` while the notification is visible on screen will dismiss the notification and remove it from the Action Center. If `notification.close()` is called after the notification is no longer visible on screen, calling `notification.close()` will try remove it from the Action Center. ### Instance Properties #### `notification.title` A `string` property representing the title of the notification. #### `notification.subtitle` A `string` property representing the subtitle of the notification. #### `notification.body` A `string` property representing the body of the notification. #### `notification.replyPlaceholder` A `string` property representing the reply placeholder of the notification. #### `notification.sound` A `string` property representing the sound of the notification. #### `notification.closeButtonText` A `string` property representing the close button text of the notification. #### `notification.silent` A `boolean` property representing whether the notification is silent. #### `notification.hasReply` A `boolean` property representing whether the notification has a reply action. #### `notification.urgency` _Linux_ A `string` property representing the urgency level of the notification. Can be 'normal', 'critical', or 'low'. Default is 'low' - see [NotifyUrgency](https://developer-old.gnome.org/notification-spec/#urgency-levels) for more information. #### `notification.timeoutType` _Linux_ _Windows_ A `string` property representing the type of timeout duration for the notification. Can be 'default' or 'never'. If `timeoutType` is set to 'never', the notification never expires. It stays open until closed by the calling API or the user. #### `notification.actions` A [`NotificationAction[]`](structures/notification-action.md) property representing the actions of the notification. #### `notification.toastXml` _Windows_ A `string` property representing the custom Toast XML of the notification. ### Playing Sounds On macOS, you can specify the name of the sound you'd like to play when the notification is shown. Any of the default sounds (under System Preferences > Sound) can be used, in addition to custom sound files. Be sure that the sound file is copied under the app bundle (e.g., `YourApp.app/Contents/Resources`), or one of the following locations: * `~/Library/Sounds` * `/Library/Sounds` * `/Network/Library/Sounds` * `/System/Library/Sounds` See the [`NSSound`](https://developer.apple.com/documentation/appkit/nssound) docs for more information. [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter --- # parentPort > Interface for communication with parent process. Process: [Utility](../glossary.md#utility-process) `parentPort` is an [EventEmitter][event-emitter]. _This object is not exported from the `'electron'` module. It is only available as a property of the process object in the Electron API._ ```js // Main process const child = utilityProcess.fork(path.join(__dirname, 'test.js')) child.postMessage({ message: 'hello' }) child.on('message', (data) => { console.log(data) // hello world! }) // Child process process.parentPort.on('message', (e) => { process.parentPort.postMessage(`${e.data} world!`) }) ``` ## Events The `parentPort` object emits the following events: ### Event: 'message' Returns: * `messageEvent` Object * `data` any * `ports` MessagePortMain[] Emitted when the process receives a message. Messages received on this port will be queued up until a handler is registered for this event. ## Methods ### `parentPort.postMessage(message)` * `message` any Sends a message from the process to its parent. [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter --- # powerMonitor > Monitor power state changes. Process: [Main](../glossary.md#main-process) ## Events The `powerMonitor` module emits the following events: ### Event: 'suspend' Emitted when the system is suspending. ### Event: 'resume' Emitted when system is resuming. ### Event: 'on-ac' _macOS_ _Windows_ Emitted when the system changes to AC power. ### Event: 'on-battery' _macOS_ _Windows_ Emitted when system changes to battery power. ### Event: 'thermal-state-change' _macOS_ Returns: * `details` Event\<\> * `state` string - The system's new thermal state. Can be `unknown`, `nominal`, `fair`, `serious`, `critical`. Emitted when the thermal state of the system changes. Notification of a change in the thermal status of the system, such as entering a critical temperature range. Depending on the severity, the system might take steps to reduce said temperature, for example, throttling the CPU or switching on the fans if available. Apps may react to the new state by reducing expensive computing tasks (e.g. video encoding), or notifying the user. The same state might be received repeatedly. See https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/RespondToThermalStateChanges.html ### Event: 'speed-limit-change' _macOS_ _Windows_ Returns: * `details` Event\<\> * `limit` number - The operating system's advertised speed limit for CPUs, in percent. Notification of a change in the operating system's advertised speed limit for CPUs, in percent. Values below 100 indicate that the system is impairing processing power due to thermal management. ### Event: 'shutdown' _Linux_ _macOS_ Emitted when the system is about to reboot or shut down. If the event handler invokes `e.preventDefault()`, Electron will attempt to delay system shutdown in order for the app to exit cleanly. If `e.preventDefault()` is called, the app should exit as soon as possible by calling something like `app.quit()`. ### Event: 'lock-screen' _macOS_ _Windows_ Emitted when the system is about to lock the screen. ### Event: 'unlock-screen' _macOS_ _Windows_ Emitted as soon as the systems screen is unlocked. ### Event: 'user-did-become-active' _macOS_ Emitted when a login session is activated. See [documentation](https://developer.apple.com/documentation/appkit/nsworkspacesessiondidbecomeactivenotification?language=objc) for more information. ### Event: 'user-did-resign-active' _macOS_ Emitted when a login session is deactivated. See [documentation](https://developer.apple.com/documentation/appkit/nsworkspacesessiondidresignactivenotification?language=objc) for more information. ## Methods The `powerMonitor` module has the following methods: ### `powerMonitor.getSystemIdleState(idleThreshold)` * `idleThreshold` Integer Returns `string` - The system's current idle state. Can be `active`, `idle`, `locked` or `unknown`. Calculate the system idle state. `idleThreshold` is the amount of time (in seconds) before considered idle. `locked` is available on supported systems only. ### `powerMonitor.getSystemIdleTime()` Returns `Integer` - Idle time in seconds Calculate system idle time in seconds. ### `powerMonitor.getCurrentThermalState()` _macOS_ Returns `string` - The system's current thermal state. Can be `unknown`, `nominal`, `fair`, `serious`, or `critical`. ### `powerMonitor.isOnBatteryPower()` Returns `boolean` - Whether the system is on battery power. To monitor for changes in this property, use the `on-battery` and `on-ac` events. ## Properties ### `powerMonitor.onBatteryPower` A `boolean` property. True if the system is on battery power. See [`powerMonitor.isOnBatteryPower()`](#powermonitorisonbatterypower). --- # powerSaveBlocker > Block the system from entering low-power (sleep) mode. Process: [Main](../glossary.md#main-process) For example: ```js const { powerSaveBlocker } = require('electron') const id = powerSaveBlocker.start('prevent-display-sleep') console.log(powerSaveBlocker.isStarted(id)) powerSaveBlocker.stop(id) ``` ## Methods The `powerSaveBlocker` module has the following methods: ### `powerSaveBlocker.start(type)` * `type` string - Power save blocker type. * `prevent-app-suspension` - Prevent the application from being suspended. Keeps system active but allows screen to be turned off. Example use cases: downloading a file or playing audio. * `prevent-display-sleep` - Prevent the display from going to sleep. Keeps system and screen active. Example use case: playing video. Returns `Integer` - The blocker ID that is assigned to this power blocker. Starts preventing the system from entering lower-power mode. Returns an integer identifying the power save blocker. > [!NOTE] > `prevent-display-sleep` has higher precedence over > `prevent-app-suspension`. Only the highest precedence type takes effect. In > other words, `prevent-display-sleep` always takes precedence over > `prevent-app-suspension`. For example, an API calling A requests for `prevent-app-suspension`, and another calling B requests for `prevent-display-sleep`. `prevent-display-sleep` will be used until B stops its request. After that, `prevent-app-suspension` is used. ### `powerSaveBlocker.stop(id)` * `id` Integer - The power save blocker id returned by `powerSaveBlocker.start`. Stops the specified power save blocker. Returns `boolean` - Whether the specified `powerSaveBlocker` has been stopped. ### `powerSaveBlocker.isStarted(id)` * `id` Integer - The power save blocker id returned by `powerSaveBlocker.start`. Returns `boolean` - Whether the corresponding `powerSaveBlocker` has started. --- # process > Extensions to process object. Process: [Main](../glossary.md#main-process), [Renderer](../glossary.md#renderer-process) Electron's `process` object is extended from the [Node.js `process` object](https://nodejs.org/api/process.html). It adds the following events, properties, and methods: ## Sandbox In sandboxed renderers the `process` object contains only a subset of the APIs: * `crash()` * `hang()` * `getCreationTime()` * `getHeapStatistics()` * `getBlinkMemoryInfo()` * `getProcessMemoryInfo()` * `getSystemMemoryInfo()` * `getSystemVersion()` * `getCPUUsage()` * `uptime()` * `argv` * `execPath` * `env` * `pid` * `arch` * `platform` * `sandboxed` * `contextIsolated` * `type` * `version` * `versions` * `mas` * `windowsStore` * `contextId` ## Events ### Event: 'loaded' Emitted when Electron has loaded its internal initialization script and is beginning to load the web page or the main script. ## Properties ### `process.defaultApp` _Readonly_ A `boolean`. When the app is started by being passed as parameter to the default Electron executable, this property is `true` in the main process, otherwise it is `undefined`. For example when running the app with `electron .`, it is `true`, even if the app is packaged ([`isPackaged`](app.md#appispackaged-readonly)) is `true`. This can be useful to determine how many arguments will need to be sliced off from `process.argv`. ### `process.isMainFrame` _Readonly_ A `boolean`, `true` when the current renderer context is the "main" renderer frame. If you want the ID of the current frame you should use `webFrame.routingId`. ### `process.mas` _Readonly_ A `boolean`. For Mac App Store build, this property is `true`, for other builds it is `undefined`. ### `process.noAsar` A `boolean` that controls ASAR support inside your application. Setting this to `true` will disable the support for `asar` archives in Node's built-in modules. ### `process.noDeprecation` A `boolean` that controls whether or not deprecation warnings are printed to `stderr`. Setting this to `true` will silence deprecation warnings. This property is used instead of the `--no-deprecation` command line flag. ### `process.resourcesPath` _Readonly_ A `string` representing the path to the resources directory. ### `process.sandboxed` _Readonly_ A `boolean`. When the renderer process is sandboxed, this property is `true`, otherwise it is `undefined`. ### `process.contextIsolated` _Readonly_ A `boolean` that indicates whether the current renderer context has `contextIsolation` enabled. It is `undefined` in the main process. ### `process.throwDeprecation` A `boolean` that controls whether or not deprecation warnings will be thrown as exceptions. Setting this to `true` will throw errors for deprecations. This property is used instead of the `--throw-deprecation` command line flag. ### `process.traceDeprecation` A `boolean` that controls whether or not deprecations printed to `stderr` include their stack trace. Setting this to `true` will print stack traces for deprecations. This property is instead of the `--trace-deprecation` command line flag. ### `process.traceProcessWarnings` A `boolean` that controls whether or not process warnings printed to `stderr` include their stack trace. Setting this to `true` will print stack traces for process warnings (including deprecations). This property is instead of the `--trace-warnings` command line flag. ### `process.type` _Readonly_ A `string` representing the current process's type, can be: * `browser` - The main process * `renderer` - A renderer process * `service-worker` - In a service worker * `worker` - In a web worker * `utility` - In a node process launched as a service ### `process.versions.chrome` _Readonly_ A `string` representing Chrome's version string. ### `process.versions.electron` _Readonly_ A `string` representing Electron's version string. ### `process.windowsStore` _Readonly_ A `boolean`. If the app is running as a Windows Store app (appx), this property is `true`, for otherwise it is `undefined`. ### `process.contextId` _Readonly_ A `string` (optional) representing a globally unique ID of the current JavaScript context. Each frame has its own JavaScript context. When contextIsolation is enabled, the isolated world also has a separate JavaScript context. This property is only available in the renderer process. ### `process.parentPort` A [`Electron.ParentPort`](parent-port.md) property if this is a [`UtilityProcess`](utility-process.md) (or `null` otherwise) allowing communication with the parent process. ## Methods The `process` object has the following methods: ### `process.crash()` Causes the main thread of the current process crash. ### `process.getCreationTime()` Returns `number | null` - The number of milliseconds since epoch, or `null` if the information is unavailable Indicates the creation time of the application. The time is represented as number of milliseconds since epoch. It returns null if it is unable to get the process creation time. ### `process.getCPUUsage()` Returns [`CPUUsage`](structures/cpu-usage.md) ### `process.getHeapStatistics()` Returns `Object`: * `totalHeapSize` Integer * `totalHeapSizeExecutable` Integer * `totalPhysicalSize` Integer * `totalAvailableSize` Integer * `usedHeapSize` Integer * `heapSizeLimit` Integer * `mallocedMemory` Integer * `peakMallocedMemory` Integer * `doesZapGarbage` boolean Returns an object with V8 heap statistics. Note that all statistics are reported in Kilobytes. ### `process.getBlinkMemoryInfo()` Returns `Object`: * `allocated` Integer - Size of all allocated objects in Kilobytes. * `total` Integer - Total allocated space in Kilobytes. Returns an object with Blink memory information. It can be useful for debugging rendering / DOM related memory issues. Note that all values are reported in Kilobytes. ### `process.getProcessMemoryInfo()` Returns `Promise` - Resolves with a [ProcessMemoryInfo](structures/process-memory-info.md) Returns an object giving memory usage statistics about the current process. Note that all statistics are reported in Kilobytes. This api should be called after app ready. Chromium does not provide `residentSet` value for macOS. This is because macOS performs in-memory compression of pages that haven't been recently used. As a result the resident set size value is not what one would expect. `private` memory is more representative of the actual pre-compression memory usage of the process on macOS. ### `process.getSystemMemoryInfo()` Returns `Object`: * `total` Integer - The total amount of physical memory in Kilobytes available to the system. * `free` Integer - The total amount of memory not being used by applications or disk cache. * `fileBacked` Integer _macOS_ - The amount of memory that currently has been paged out to storage. Includes memory for file caches, network buffers, and other system services. * `purgeable` Integer _macOS_ - The amount of memory that is marked as "purgeable". The system can reclaim it if memory pressure increases. * `swapTotal` Integer _Windows_ _Linux_ - The total amount of swap memory in Kilobytes available to the system. * `swapFree` Integer _Windows_ _Linux_ - The free amount of swap memory in Kilobytes available to the system. Returns an object giving memory usage statistics about the entire system. Note that all statistics are reported in Kilobytes. ### `process.getSystemVersion()` Returns `string` - The version of the host operating system. Example: ```js const version = process.getSystemVersion() console.log(version) // On macOS -> '10.13.6' // On Windows -> '10.0.17763' // On Linux -> '4.15.0-45-generic' ``` > [!NOTE] > It returns the actual operating system version instead of kernel version on macOS unlike `os.release()`. ### `process.takeHeapSnapshot(filePath)` * `filePath` string - Path to the output file. Returns `boolean` - Indicates whether the snapshot has been created successfully. Takes a V8 heap snapshot and saves it to `filePath`. ### `process.hang()` Causes the main thread of the current process hang. ### `process.setFdLimit(maxDescriptors)` _macOS_ _Linux_ * `maxDescriptors` Integer Sets the file descriptor soft limit to `maxDescriptors` or the OS hard limit, whichever is lower for the current process. --- # protocol > Register a custom protocol and intercept existing protocol requests. Process: [Main](../glossary.md#main-process) An example of implementing a protocol that has the same effect as the `file://` protocol: ```js const { app, protocol, net } = require('electron') const path = require('node:path') const url = require('node:url') app.whenReady().then(() => { protocol.handle('atom', (request) => { const filePath = request.url.slice('atom://'.length) return net.fetch(url.pathToFileURL(path.join(__dirname, filePath)).toString()) }) }) ``` > [!NOTE] > All methods unless specified can only be used after the `ready` event > of the `app` module gets emitted. ## Using `protocol` with a custom `partition` or `session` A protocol is registered to a specific Electron [`session`](./session.md) object. If you don't specify a session, then your `protocol` will be applied to the default session that Electron uses. However, if you define a `partition` or `session` on your `browserWindow`'s `webPreferences`, then that window will use a different session and your custom protocol will not work if you just use `electron.protocol.XXX`. To have your custom protocol work in combination with a custom session, you need to register it to that session explicitly. ```js const { app, BrowserWindow, net, protocol, session } = require('electron') const path = require('node:path') const url = require('node:url') app.whenReady().then(() => { const partition = 'persist:example' const ses = session.fromPartition(partition) ses.protocol.handle('atom', (request) => { const filePath = request.url.slice('atom://'.length) return net.fetch(url.pathToFileURL(path.resolve(__dirname, filePath)).toString()) }) const mainWindow = new BrowserWindow({ webPreferences: { partition } }) }) ``` ## Methods The `protocol` module has the following methods: ### `protocol.registerSchemesAsPrivileged(customSchemes)` * `customSchemes` [CustomScheme[]](structures/custom-scheme.md) > [!NOTE] > This method can only be used before the `ready` event of the `app` > module gets emitted and can be called only once. Registers the `scheme` as standard, secure, bypasses content security policy for resources, allows registering ServiceWorker, supports fetch API, streaming video/audio, and V8 code cache. Specify a privilege with the value of `true` to enable the capability. An example of registering a privileged scheme, that bypasses Content Security Policy: ```js const { protocol } = require('electron') protocol.registerSchemesAsPrivileged([ { scheme: 'foo', privileges: { bypassCSP: true } } ]) ``` A standard scheme adheres to what RFC 3986 calls [generic URI syntax](https://tools.ietf.org/html/rfc3986#section-3). For example `http` and `https` are standard schemes, while `file` is not. Registering a scheme as standard allows relative and absolute resources to be resolved correctly when served. Otherwise the scheme will behave like the `file` protocol, but without the ability to resolve relative URLs. For example when you load following page with custom protocol without registering it as standard scheme, the image will not be loaded because non-standard schemes can not recognize relative URLs: ```html ``` Registering a scheme as standard will allow access to files through the [FileSystem API][file-system-api]. Otherwise the renderer will throw a security error for the scheme. By default web storage apis (localStorage, sessionStorage, webSQL, indexedDB, cookies) are disabled for non standard schemes. So in general if you want to register a custom protocol to replace the `http` protocol, you have to register it as a standard scheme. Protocols that use streams (http and stream protocols) should set `stream: true`. The `