Author: saqibkhan

  • powerSaveBlocker

    Block the system from entering low-power (sleep) mode.

    Process: Main

    For example:

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

  • powerMonitor

    Monitor power state changes.

    Process: Main

    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

    • state string – The system’s new thermal state. Can be unknownnominalfairseriouscritical.

    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

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

    Event: ‘user-did-resign-active’ macOS

    Emitted when a login session is deactivated. See documentation 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 activeidlelocked 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 unknownnominalfairserious, 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

    boolean property. True if the system is on battery power.

    See powerMonitor.isOnBatteryPower().

  • parentPort

    Interface for communication with parent process.

    Process: Utility

    parentPort is an EventEmitterThis object is not exported from the 'electron' module. It is only available as a property of the process object in the Electron API.

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

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