Category: Electron Api

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT8eTR7hsmNYHvXpuO5UVCuQaOp6xf8uVlUrA&s

  • Notification

    Create OS desktop notifications

    Process: Main

    RENDERER PROCESS NOTIFICATIONS

    If you want to show notifications from a renderer process you should use the web Notifications API

    Class: Notification

    Create OS desktop notifications

    Process: Main

    Notification is an EventEmitter.

    It creates a new Notification with native properties as set by the options.

    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) (optional) – An icon to use in the notification.
      • 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[] (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

    string property representing the title of the notification.

    notification.subtitle

    string property representing the subtitle of the notification.

    notification.body

    string property representing the body of the notification.

    notification.replyPlaceholder

    string property representing the reply placeholder of the notification.

    notification.sound

    string property representing the sound of the notification.

    notification.closeButtonText

    string property representing the close button text of the notification.

    notification.silent

    boolean property representing whether the notification is silent.

    notification.hasReply

    boolean property representing whether the notification has a reply action.

    notification.urgency Linux

    string property representing the urgency level of the notification. Can be ‘normal’, ‘critical’, or ‘low’.

    Default is ‘low’ – see NotifyUrgency for more information.

    notification.timeoutType Linux Windows

    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

    NotificationAction[] property representing the actions of the notification.

    notification.toastXml Windows

    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 docs for more information.

  • NetLog

    Logging network events for a session.

    Process: Main

    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 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 defaultincludeSensitive or everything.
      • maxFileSize number (optional) – When the log grows beyond this size, logging will automatically stop. Defaults to unlimited.

    Returns Promise<void> – resolves when the net log has begun recording.

    Starts recording network events to path.

    netLog.stopLogging()

    Returns Promise<void> – 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

    boolean property that indicates whether network logs are currently being recorded.

    Edit this page

  • Net

    Issue HTTP/HTTPS requests using Chromium’s native networking library

    Process: MainUtility

    The 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.

    Methods

    The net module has the following methods:

    net.request(options)

    Returns ClientRequest

    Creates a ClientRequest 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])

    Returns Promise<GlobalResponse> – see 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:

    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. To send a fetch request from another session, use ses.fetch().

    See the MDN documentation for 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 as well as file:, and will trigger webRequest handlers if present. When the non-standard bypassCustomProtocolHandlers option is set in RequestInit, custom protocol handlers will not be called for this request. This allows forwarding an intercepted request to the built-in handler. webRequest handlers will still be triggered when bypassing custom protocols.

    protocol.handle('https', (req) => {
    if (req.url === 'https://my-app.com') {
    return new Response('<body>my app</body>')
    } else {
    return net.fetch(req, { bypassCustomProtocolHandlers: true })
    }
    })

    Note: in the 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<ResolvedHost> – Resolves with the resolved IP addresses for the host.

    This method will resolve hosts from the default session. To resolve a host from another session, use ses.resolveHost().

    Properties

    net.online Readonly

    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.

  • NativeTheme

    Read and respond to changes in Chromium’s native color theme.

    Process: Main

    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 shouldUseDarkColorsshouldUseHighContrastColors 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

    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

    string property that can be systemlight 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 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 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

    boolean for if the OS / Chromium currently has high-contrast mode enabled or is being instructed to show a high-contrast UI.

    nativeTheme.shouldUseInvertedColorScheme macOS Windows Readonly

    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

    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

    boolean that indicates the whether the user has chosen via system accessibility settings to reduce transparency at the OS level.

  • NativeImage

    Create tray, dock, and application icons using PNG or JPG files.

    Process: MainRenderer

    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:

    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:

    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
      • 16×16 (100% DPI scale)
      • 20×20 (125% DPI scale)
      • 24×24 (150% DPI scale)
      • 32×32 (200% DPI scale)
    • Large icon
      • 32×32 (100% DPI scale)
      • 40×40 (125% DPI scale)
      • 48×48 (150% DPI scale)
      • 64×64 (200% DPI scale)
      • 256×256

    Check the Icon Scaling section in the Windows App Icon Construction reference.

    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 [email protected] 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
    ├── [email protected]
    └── [email protected]

    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 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. [email protected]).

    Methods

    The nativeImage module has the following methods, all of which return an instance of the 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 – the desired width and height (positive numbers) of the thumbnail.

    Returns Promise<NativeImage> – fulfilled with the file’s thumbnail preview image, which is a NativeImage.

    Note: The 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 a file located at path. This method returns an empty image if the path does not exist, cannot be read, or is not a valid image.

    const { nativeImage } = require('electron')

    const image = nativeImage.createFromPath('/Users/somebody/images/icon.png')
    console.log(image)

    nativeImage.createFromBitmap(buffer, options)

    • 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
    • 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 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 documentation 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:

    echo -e '#import <Cocoa/Cocoa.h>\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.

    Class: NativeImage

    Natively wrap images such as tray, dock, and application icons.

    Process: MainRenderer
    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 that contains the image’s PNG encoded data.

    image.toJPEG(quality)

    • quality Integer – Between 0 – 100.

    Returns Buffer – A 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 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 of the image.

    image.getBitmap([options])

    • options Object (optional)
      • scaleFactor Number (optional) – Defaults to 1.0.

    Returns Buffer – A Buffer that contains the image’s raw bitmap pixel data.

    The difference between getBitmap() and toBitmap() is that getBitmap() does not copy the bitmap data, so you have to use the returned Buffer immediately in current event loop tick; otherwise the data might be changed or destroyed.

    image.getNativeHandle() macOS

    Returns Buffer – A 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.

    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.

    image.isTemplateImage()

    Returns boolean – Whether the image is a macOS template image.

    image.crop(rect)

    • rect Rectangle – 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 goodbetter, 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

    boolean property that determines whether the image is considered a template image.

    Please note that this property only has an effect on macOS.

  • 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.

    Class: MessagePortMain

    Port interface for channel messaging in the main process.

    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.

    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.

  • MessageChannelMain

    MessageChannelMain is the main-process-side equivalent of the DOM MessageChannel object. Its singular function is to create a pair of connected MessagePortMain 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

    Example:

    // 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)
    }
    })

    Instance Properties

    channel.port1

    MessagePortMain property.

    channel.port2

    MessagePortMain property.

  • Menu

    Class: Menu

    Create native application menus and context menus.

    Process: Main

    new Menu()

    Creates a new menu.

    Static Methods

    The Menu class has the following static methods:

    • 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 FileEditViewWindow and Help.

    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 can still be dynamically modified.

    • 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 property of a MenuItem.

    See the macOS Cocoa Event Handling Guide for more information on macOS’ native actions.

    • template (MenuItemConstructorOptions | MenuItem)[]

    Returns Menu

    Generally, the template is an array of options for constructing a MenuItem. 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:

    • options Object (optional)
      • window BrowserWindow (optional) – Default is the focused window.
      • 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 nonemousekeyboardtouchtouchMenulongPresslongTaptouchHandlestylusadjustSelection, or adjustSelectionReset.
      • callback Function (optional) – Called when menu is closed.

    Pops up this menu as a context menu in the BrowserWindow.

    • browserWindow BrowserWindow (optional) – Default is the focused window.

    Closes the context menu in the browserWindow.

    Appends the menuItem to the menu.

    • id string

    Returns MenuItem | null the item with the specified id

    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:

    MenuItem[] array containing the menu’s items.

    Each Menu consists of multiple MenuItems and each MenuItem can have a submenu.

    Examples

    An example of creating the application menu with the simple template API:

    const { app, Menu } = require('electron')

    const isMac = process.platform === 'darwin'

    const template = [
    // { role: 'appMenu' }
    ...(isMac
    ? [{
    label: app.name,
    submenu: [
    { role: 'about' },
    { type: 'separator' },
    { role: 'services' },
    { type: 'separator' },
    { role: 'hide' },
    { role: 'hideOthers' },
    { role: 'unhide' },
    { type: 'separator' },
    { role: 'quit' }
    ]
    }]
    : []),
    // { role: 'fileMenu' }
    {
    label: 'File',
    submenu: [
    isMac ? { role: 'close' } : { role: 'quit' }
    ]
    },
    // { role: 'editMenu' }
    {
    label: 'Edit',
    submenu: [
    { role: 'undo' },
    { role: 'redo' },
    { type: 'separator' },
    { role: 'cut' },
    { role: 'copy' },
    { role: 'paste' },
    ...(isMac
    ? [
    { role: 'pasteAndMatchStyle' },
    { role: 'delete' },
    { role: 'selectAll' },
    { type: 'separator' },
    {
    label: 'Speech',
    submenu: [
    { role: 'startSpeaking' },
    { role: 'stopSpeaking' }
    ]
    }
    ]
    : [
    { role: 'delete' },
    { type: 'separator' },
    { role: 'selectAll' }
    ])
    ]
    },
    // { role: 'viewMenu' }
    {
    label: 'View',
    submenu: [
    { role: 'reload' },
    { role: 'forceReload' },
    { role: 'toggleDevTools' },
    { type: 'separator' },
    { role: 'resetZoom' },
    { role: 'zoomIn' },
    { role: 'zoomOut' },
    { type: 'separator' },
    { role: 'togglefullscreen' }
    ]
    },
    // { role: 'windowMenu' }
    {
    label: 'Window',
    submenu: [
    { role: 'minimize' },
    { role: 'zoom' },
    ...(isMac
    ? [
    { type: 'separator' },
    { role: 'front' },
    { type: 'separator' },
    { role: 'window' }
    ]
    : [
    { role: 'close' }
    ])
    ]
    },
    {
    role: 'help',
    submenu: [
    {
    label: 'Learn More',
    click: async () => {
    const { shell } = require('electron')
    await shell.openExternal('https://electronjs.org')
    }
    }
    ]
    }
    ]

    const menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)

    Render process

    To create menus initiated by the renderer process, send the required information to the main process using IPC and have the main process display the menu on behalf of the renderer.

    Below is an example of showing a menu when the user right clicks the page:

    // renderer
    window.addEventListener('contextmenu', (e) => {
    e.preventDefault()
    ipcRenderer.send('show-context-menu')
    })

    ipcRenderer.on('context-menu-command', (e, command) => {
    // ...
    })

    // main
    ipcMain.on('show-context-menu', (event) => {
    const template = [
    {
    label: 'Menu Item 1',
    click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
    },
    { type: 'separator' },
    { label: 'Menu Item 2', type: 'checkbox', checked: true }
    ]
    const menu = Menu.buildFromTemplate(template)
    menu.popup({ window: BrowserWindow.fromWebContents(event.sender) })
    })

    Notes on macOS Application Menu

    macOS has a completely different style of application menu from Windows and Linux. Here are some notes on making your app’s menu more native-like.

    Standard Menus

    On macOS there are many system-defined standard menus, like the Services and Windows menus. To make your menu a standard menu, you should set your menu’s role to one of the following and Electron will recognize them and make them become standard menus:

    • window
    • help
    • services

    Standard Menu Item Actions

    macOS has provided standard actions for some menu items, like About xxxHide xxx, and Hide Others. To set the action of a menu item to a standard action, you should set the role attribute of the menu item.

    On macOS the label of the application menu’s first item is always your app’s name, no matter what label you set. To change it, modify your app bundle’s Info.plist file. See About Information Property List Files for more information.

    Setting Menu for Specific Browser Window (Linux Windows)

    The setMenu method of browser windows can set the menu of certain browser windows.

    You can make use of beforeafterbeforeGroupContainingafterGroupContaining and id to control how the item will be placed when building a menu with Menu.buildFromTemplate.

    • before – 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 – 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. Also implies that the menu item in question should be placed in the same “group” as the item.
    • beforeGroupContaining – 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 – 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.

    By default, items will be inserted in the order they exist in the template unless one of the specified positioning keywords is used.

    Examples

    Template:

    [
    { id: '1', label: 'one' },
    { id: '2', label: 'two' },
    { id: '3', label: 'three' },
    { id: '4', label: 'four' }
    ]

    Menu:

    - 1
    - 2
    - 3
    - 4

    Template:

    [
    { id: '1', label: 'one' },
    { type: 'separator' },
    { id: '3', label: 'three', beforeGroupContaining: ['1'] },
    { id: '4', label: 'four', afterGroupContaining: ['2'] },
    { type: 'separator' },
    { id: '2', label: 'two' }
    ]

    Menu:

    - 3
    - 4
    - ---
    - 1
    - ---
    - 2

    Template:

    [
    { id: '1', label: 'one', after: ['3'] },
    { id: '2', label: 'two', before: ['1'] },
    { id: '3', label: 'three' }
    ]

    Menu:

    - ---
    - 3
    - 2
    - 1
  • IpcMain

    Communicate asynchronously from the main process to renderer processes.

    Process: Main

    The 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 messages

    It 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.

    Methods

    The ipcMain module has the following method to listen for events:

    ipcMain.on(channel, listener)

    • channel string
    • listener Function

    Listens to channel, when a new message arrives listener would be called with listener(event, args...).

    ipcMain.once(channel, listener)

    • channel string
    • listener Function

    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.removeListener(channel, listener)

    • channel string
    • listener Function
      • ...args any[]

    Removes the specified listener from the listener array for the specified channel.

    ipcMain.removeAllListeners([channel])

    • channel string (optional)

    Removes listeners of the specified channel.

    ipcMain.handle(channel, listener)

    Adds a handler for an invokeable 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.

    Main Process

    ipcMain.handle('my-invokable-ipc', async (event, ...args) => {
    const result = await somePromise(...args)
    return result
    })

    Renderer Process

    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 for details.

    ipcMain.handleOnce(channel, listener)

    Handles a single invokeable IPC message, then removes the listener. See ipcMain.handle(channel, listener).

    ipcMain.removeHandler(channel)

    • channel string

    Removes any handler for channel, if present.

  • InAppPurchase

    In-app purchases on Mac App Store.

    Process: Main

    Events

    The inAppPurchase module emits the following events:

    Event: ‘transactions-updated’

    Emitted when one or more transactions have been updated.

    Returns:

    • event Event
    • transactions Transaction[] – Array of Transaction objects.

    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<boolean> – 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<Product[]> – Resolves with an array of Product 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 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.