⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Create and control windows.Process: Main> [!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 class may be a simpler option.This module cannot
be used until the ready event of the app module is emitted.### Parent and child windowsBy using parent option, you
can create child windows: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 windowsA 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: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 managementWhen you add a WebContentsView to a BaseWindow and the BaseWindow is closed, the webContents 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: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, if you don't explicitly close the webContents, you'll encounter memory
leaks.### Class: BaseWindow> Create and control windows.Process: MainBaseWindow is an EventEmitter.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.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
[!NOTE] The BrowserView class is deprecated, and replaced by the new WebContentsView class.A BrowserView can be used to embed
additional web content into a BrowserWindow. 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 class.Process: MainThis 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.### Example// 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')})
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Create and control browser windows.Process: MainThis module cannot be used until the ready event of the app module is
emitted.### Window customizationThe BrowserWindow class exposes various ways to modify the look and behavior of your app's windows. For more
details, see the Window Customization tutorial.### Showing the window gracefullyWhen 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 eventWhile 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: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 propertyFor 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: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: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.### Parent and child windowsBy using parent option, you can create child windows: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 windowsA 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: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 visibilityThe 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: MainBrowserWindow is an EventEmitter.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.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ✔ | Exported ❌
Make HTTP/HTTPS requests.Process: Main, Utility _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 interface and is therefore an EventEmitter.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
A View that displays an image.Process: MainThis module cannot be used until the ready event of the app module
is emitted.Useful for showing splash screens that will be swapped for WebContentsViews when the content finishes loading.Note that ImageView is
experimental and may be changed or removed in the future.### Class: ImageView extends View> A View that displays an image.Process:
MainImageView inherits from View.ImageView is an EventEmitter.> [!WARNING] Electron's built-in classes cannot be subclassed in user code. For more information,
see the FAQ.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔### Class: Menu> Create native application menus and context menus.Process: Main> [!TIP] See also: A detailed guide about how to
implement menus in your application.> [!WARNING] Electron's built-in classes cannot be subclassed in user code. For more information, see the
FAQ.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔### Class: MenuItem> Add items to native application menus and context menus.Process: MainSee Menu for examples.> [!WARNING] Electron's built-in classes
cannot be subclassed in user code. For more information, see the FAQ.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Create OS desktop notificationsProcess: Main> [!NOTE] If you want to show notifications from a renderer process you should use
the web Notifications API### Class: Notification> Create OS desktop notificationsProcess: MainNotification is an EventEmitter.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.### Static MethodsThe Notification class has the following static methods:### Notification.isSupported()Returns boolean - Whether or not desktop notifications are
supported on the current system
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
The ShareMenu class creates Share Menu on macOS, which can be used to share information from the current context to
apps, social media accounts, and other services.For including the share menu as a submenu of other menus, please use the
shareMenu role of MenuItem.### Class: ShareMenu> Create share menu on macOS.Process: Main> [!WARNING] Electron's built-in classes cannot be subclassed in
user code. For more information, see the FAQ.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
[!WARNING] Electron's built-in classes cannot be subclassed in user code. For more information, see the FAQ.### Class: TouchBar> Create
TouchBar layouts for native macOS applicationsProcess: Main
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ❌
Create a button in the touch bar for native macOS applicationsProcess: Main This class is not exported from the
'electron' module. It is only available as a return value of other methods in the Electron API.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ❌
Create a color picker in the touch bar for native macOS applicationsProcess: Main This class is not exported from
the 'electron' module. It is only available as a return value of other methods in the Electron API.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ❌
Create a group in the touch bar for native macOS applicationsProcess: Main This class is not exported from the
'electron' module. It is only available as a return value of other methods in the Electron API.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ❌
Create a label in the touch bar for native macOS applicationsProcess: Main This class is not exported from the
'electron' module. It is only available as a return value of other methods in the Electron API.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ❌
Instantiates a special "other items proxy", which nests TouchBar elements inherited from Chromium at the space indicated by the
proxy. By default, this proxy is added to each TouchBar at the end of the input. For more information, see
the AppKit docs on NSTouchBarItemIdentifierOtherItemsProxy> [!NOTE] Only one instance of this class can be added per TouchBar.Process: Main This class
is not exported from the 'electron' module. It is only available as a return value of other methods in the
Electron API.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ❌
Create a popover in the touch bar for native macOS applicationsProcess: Main This class is not exported from the
'electron' module. It is only available as a return value of other methods in the Electron API.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ❌
Create a scrubber (a scrollable selector)Process: Main This class is not exported from the 'electron' module. It is only
available as a return value of other methods in the Electron API.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ❌
Create a segmented control (a button group) where one button has a selected stateProcess: Main This class is not
exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ❌
Create a slider in the touch bar for native macOS applicationsProcess: Main This class is not exported from the
'electron' module. It is only available as a return value of other methods in the Electron API.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ❌
Create a spacer between two items in the touch bar for native macOS applicationsProcess: Main This class is not
exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔### Class: Tray> Add icons and context menus to the system's notification area.Process: MainTray is an EventEmitter.const { app, Menu,
Tray } = require('electron')let tray = nullapp.whenReady().then(() => { tray = new Tray('/path/to/my/icon') const contextMenu = Menu.buildFromTemplate([
{ label: 'Item1', type: 'radio' }, { label: 'Item2', type: 'radio' },
{ label: 'Item3', type: 'radio', checked: true }, { label: 'Item4', type: 'radio' } ])
tray.setToolTip('This is my application.') tray.setContextMenu(contextMenu)})> [!TIP] See also: A detailed guide about how to implement Tray menus.> [!WARNING] Electron's
built-in classes cannot be subclassed in user code. For more information, see the FAQ.Platform Considerations*Linux Tray icon uses StatusNotifierItem by
default, when it is not available in user's desktop environment the GtkStatusIcon will be used instead. The click event is
emitted when the tray icon receives activation from user, however the StatusNotifierItem spec does not specify which action would cause
an activation, for some environments it is left mouse click, but for some it might be double left mouse click.
In order for changes made to individual MenuItems to take effect, you have to call setContextMenu again. For example:const {
app, Menu, Tray } = require('electron')let appIcon = nullapp.whenReady().then(() => { appIcon = new Tray('/path/to/my/icon') const contextMenu =
Menu.buildFromTemplate([ { label: 'Item1', type: 'radio' }, { label: 'Item2', type: 'radio' }
]) // Make a change to the context menu contextMenu.items[1].checked = false // Call this again for
Linux because we modified the context menu appIcon.setContextMenu(contextMenu)})MacOS* Icons passed to the Tray constructor should be Template Images.* To
make sure your icon isn't grainy on retina monitors, be sure your @2x image is 144dpi.* If you are bundling
your application (e.g., with webpack for development), be sure that the file names are not being mangled or hashed. The
filename needs to end in Template, and the @2x image needs to have the same filename as the standard image,
or MacOS will not magically invert your image's colors or use the high density image.* 16x16 (72dpi) and 32x32@2x (144dpi)
work well for most icons.Windows* It is recommended to use ICO icons to get best visual effects.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Create and layout native views.Process: MainThis module cannot be used until the ready event of the app module is
emitted.### Class: View> A basic native view.Process: MainView is an EventEmitter.> [!WARNING] Electron's built-in classes cannot be subclassed in user
code. For more information, see the FAQ.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
A View that displays a WebContents.Process: MainThis module cannot be used until the ready event of the app module
is emitted.### Class: WebContentsView extends View> A View that displays a WebContents.Process: MainWebContentsView inherits from View.WebContentsView is an EventEmitter.> [!WARNING]
Electron's built-in classes cannot be subclassed in user code. For more information, see the FAQ.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Enable apps to automatically update themselves.Process: Main**See also: A detailed guide about how to implement updates in your application.**autoUpdater
is an EventEmitter.### Platform NoticesCurrently, 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:### macOSOn macOS, the autoUpdater module is built upon Squirrel.Mac, meaning you don't need any special setup to
make it work. For server-side requirements, you can read Server Support. Note that App Transport Security (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.###
WindowsOn 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 or Electron Forge's Squirrel.Windows maker to generate a Windows installer.Apps built with Squirrel.Windows will
trigger custom launch events 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 for
more information).The installer generated with Squirrel.Windows will create a shortcut icon with an Application 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.
⚠ Process Availability: Main ✔ | Renderer ✔ | Utility ❌ | Exported ✔
Perform copy and paste operations on the system clipboard.Process: Main, Renderer (non-sandboxed only)> [!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
it using the contextBridge API.On Linux, there is also a selection clipboard. To manipulate it you need to pass selection
to each method:
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Collect tracing data from Chromium to find performance bottlenecks and slow operations.Process: MainThis 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.
⚠ Process Availability: Main ✔ | Renderer ✔ | Utility ❌ | Exported ✔
Submit crash reports to a remote server.Process: Main, Renderer> [!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 it using the contextBridge
API.The following is an example of setting up Electron to automatically submit crash reports to a remote server: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* 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.Or use a 3rd party hosted solution:* Backtrace* Sentry* BugSplat* BugsnagCrash 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 to monitor and report crashes.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Access information about media sources that can be used to capture audio and video from the desktop using the
navigator.mediaDevices.getUserMedia API.Process: MainThe following example shows how to capture video from a desktop window whose title is Electron:// main.jsconst {
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')})// renderer.jsconst 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()})
See navigator.mediaDevices.getDisplayMedia for more information.> [!NOTE] navigator.mediaDevices.getDisplayMedia does not permit the use of deviceId for selection
of a source - see specification.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Detect keyboard events when the application does not have keyboard focus.Process: MainThe 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.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.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔### ipcMain> Communicate asynchronously from the main process to renderer processes.Process: MainThe ipcMain module is an 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 messagesIt is also possible
to send messages from the main process to the renderer process, see webContents.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.
⚠ Process Availability: Main ✔ | Renderer ✔ | Utility ❌ | Exported ✔
Create tray, dock, and application icons using PNG or JPG files.Process: Main, Renderer> [!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
it using the contextBridge 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.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 or setting a BrowserWindow's icon, you can either pass an image file path
as a string: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:### Supported FormatsCurrently, 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) * 256x256Check the Icon Scaling section in the Windows App Icon Construction reference.:::noteEXIF
metadata is currently not supported and will not be taken into account during image encoding and decoding.:::### High Resolution ImageOn
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:images/├── icon.png├── icon@2x.png└── icon@3x.pngconst { 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 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).
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ✔ | Exported ✔
Issue HTTP/HTTPS requests using Chromium's native networking libraryProcess: Main, UtilityThe net module is a client-side API for issuing HTTP(S)
requests. It is similar to the HTTP and HTTPS 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: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.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Logging network events for a session.Process: Mainconst { 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 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.
⚠ Process Availability: Main ✔ | Renderer ✔ | Utility ❌ | Exported ✔
Extensions to process object.Process: Main, RendererElectron's process object is extended from the Node.js process object. It adds the following
events, properties, and methods:### SandboxIn 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
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Register a custom protocol and intercept existing protocol requests.Process: MainAn example of implementing a protocol that has the same
effect as the file:// protocol: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 sessionA protocol is registered to a specific Electron session 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.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 } })})
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Process: Main> Register for and receive notifications from remote push notification servicesFor example, when registering for push notifications via Apple
push notification services (APNS):
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Allows access to simple encryption and decryption of strings for storage on the local machine.Process: MainThis module adds extra
protection to data being stored on disk by using OS-provided cryptography systems. Current security semantics for each platform are outlined
below.* macOS: Encryption keys are stored for your app in Keychain Access in a way that prevents other applications from
loading them without user override. Therefore, content is protected from other users and other apps running in the same userspace.*
Windows: Encryption keys are generated via DPAPI. As per the Windows documentation: "Typically, only a user with the same logon
credential as the user who encrypted the data can typically decrypt the data". Therefore, content is protected from other users
on the same machine, but not from other apps running in the same userspace.* Linux: Encryption keys are generated and
stored in a secret store that varies depending on your window manager and system setup. Options currently supported are kwallet,
kwallet5, kwallet6 and gnome-libsecret, but more may be available in future versions of Electron. As such, the security semantics of
content protected via the safeStorage API vary between window managers and secret stores. * Note that not all Linux
setups have an available secret store. If no secret store is available, items stored in using the safeStorage API will
be unprotected as they are encrypted via hardcoded plaintext password. You can detect when this happens when safeStorage.getSelectedStorageBackend() returns basic_text.Note
that on Mac, access to the system Keychain is required and these calls can block the current thread to collect
user input. The same is true for Linux, if a password management tool is available.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Retrieve information about screen size, displays, cursor position, etc.Process: MainThis module cannot be used until the ready event of
the app module is emitted.screen is an EventEmitter.> [!NOTE] In the renderer / DevTools, window.screen is a reserved DOM property,
so writing let { screen } = require('electron') will not work.An example of creating a window that fills the whole
screen:// Retrieve information about screen size, displays, cursor position, etc.//// For more info, see:// https://www.electronjs.org/docs/latest/api/screenconst { app, BrowserWindow, screen }
= require('electron/main')let mainWindow = nullapp.whenReady().then(() => { // Create a window that fills the screen's available work area.
const primaryDisplay = screen.getPrimaryDisplay() const { width, height } = primaryDisplay.workAreaSize mainWindow = new BrowserWindow({ width, height })
mainWindow.loadURL('https://electronjs.org')})Another example of creating a window in the external display:const { app, BrowserWindow, screen } = require('electron')let winapp.whenReady().then(() =>
{ const displays = screen.getAllDisplays() const externalDisplay = displays.find((display) => { return display.bounds.x !== 0
|| display.bounds.y !== 0 }) if (externalDisplay) { win = new BrowserWindow({
x: externalDisplay.bounds.x + 50, y: externalDisplay.bounds.y + 50 })
win.loadURL('https://github.com') }})> [!NOTE] Screen coordinates used by this module are Point structures. There are two kinds of
coordinates available to the process:* Physical screen points are raw hardware pixels on a display.* Device-independent pixel (DIP) points are
virtualized screen points scaled based on the DPI (dots per inch) of the display.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Manage browser sessions, cookies, cache, proxy settings, etc.Process: MainThe session module can be used to create new Session objects.You
can also access the session of existing pages by using the session property of WebContents, or from the session module.
⚠ Process Availability: Main ✔ | Renderer ✔ | Utility ❌ | Exported ✔
Manage files and URLs using their default applications.Process: Main, Renderer (non-sandboxed only)The shell module provides functions related to desktop
integration.An example of opening a URL in the user's default browser:const { shell } = require('electron')shell.openExternal('https://github.com')> [!WARNING] While the shell
module can be used in the renderer process, it will not function in a sandboxed renderer.
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔utilityProcess creates a child process with Node.js and Message ports enabled. It provides the equivalent of child_process.fork API from Node.js
but instead uses Services API from Chromium to launch the child process.Process: Main
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Render and control web pages.Process: MainwebContents is an EventEmitter. It is responsible for rendering and controlling a web page
and is a property of the BrowserWindow object. An example of accessing the webContents object:### Navigation EventsSeveral events can be
used to monitor navigations as they occur within a webContents.### Document NavigationsWhen a webContents navigates to another page (as opposed
to an in-page navigation), the following events will be fired.* did-start-navigation* will-frame-navigate* will-navigate (only fired when main frame navigates)* will-redirect
(only fired when a redirect happens during navigation)* did-redirect-navigation (only fired when a redirect happens during navigation)* did-frame-navigate* did-navigate (only
fired when main frame navigates)Subsequent events will not fire if event.preventDefault() is called on any of the cancellable events.### In-page
NavigationIn-page navigations don't cause the page to reload, but instead navigate to a location within the current page. These events
are not cancellable. For an in-page navigations, the following events will fire in this order:* did-start-navigation* did-navigate-in-page### Frame NavigationThe will-navigate
and did-navigate events only fire when the mainFrame navigates. If you want to also observe navigations in
⚠ Process Availability: Main ✔ | Renderer ❌ | Utility ❌ | Exported ✔
Control web pages and iframes.Process: MainThe webFrameMain module can be used to lookup frames across existing WebContents instances. Navigation
events are the common use case.const { BrowserWindow, webFrameMain } = require('electron')const win = new BrowserWindow({ width: 800, height: 1500
})win.loadURL('https://twitter.com')win.webContents.on( 'did-frame-navigate', (event, url, httpResponseCode, httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => { const frame = webFrameMain.fromId(frameProcessId,
frameRoutingId) if (frame) { const code = 'document.body.innerHTML = document.body.innerHTML.replaceAll("heck", "h*ck")'
frame.executeJavaScript(code) } })You can also access frames of existing pages by using
the mainFrame property of WebContents.