Author: saqibkhan

  • protocol

    Register a custom protocol and intercept existing protocol requests.

    Process: Main

    An 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 session

    A 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('url')

    app.whenReady().then(() => {
    const partition = 'persist:example'
    const ses = session.fromPartition(partition)

    ses.protocol.handle('atom', (request) => {
    const filePath = request.url.slice('atom://'.length)
    return net.fetch(url.pathToFileURL(path.resolve(__dirname, filePath)).toString())
    })

    const mainWindow = new BrowserWindow({ webPreferences: { partition } })
    })

    Methods

    The protocol module has the following methods:

    protocol.registerSchemesAsPrivileged(customSchemes)

    Note: This method can only be used before the ready event of the app module gets emitted and can be called only once.

    Registers the scheme as standard, secure, bypasses content security policy for resources, allows registering ServiceWorker, supports fetch API, streaming video/audio, and V8 code cache. Specify a privilege with the value of true to enable the capability.

    An example of registering a privileged scheme, that bypasses Content Security Policy:

    const { protocol } = require('electron')
    protocol.registerSchemesAsPrivileged([
    { scheme: 'foo', privileges: { bypassCSP: true } }
    ])

    A standard scheme adheres to what RFC 3986 calls generic URI syntax. For example http and https are standard schemes, while file is not.

    Registering a scheme as standard allows relative and absolute resources to be resolved correctly when served. Otherwise the scheme will behave like the file protocol, but without the ability to resolve relative URLs.

    For example when you load following page with custom protocol without registering it as standard scheme, the image will not be loaded because non-standard schemes can not recognize relative URLs:

    <body>
    <img src='test.png'>
    </body>

    Registering a scheme as standard will allow access to files through the FileSystem API. Otherwise the renderer will throw a security error for the scheme.

    By default web storage apis (localStorage, sessionStorage, webSQL, indexedDB, cookies) are disabled for non standard schemes. So in general if you want to register a custom protocol to replace the http protocol, you have to register it as a standard scheme.

    Protocols that use streams (http and stream protocols) should set stream: true. The <video> and <audio> HTML elements expect protocols to buffer their responses by default. The stream flag configures those elements to correctly expect streaming responses.

    protocol.handle(scheme, handler)

    • scheme string – scheme to handle, for example https or my-app. This is the bit before the : in a URL.
    • handler Function<GlobalResponse | Promise>

    Register a protocol handler for scheme. Requests made to URLs with this scheme will delegate to this handler to determine what response should be sent.

    Either a Response or a Promise<Response> can be returned.

    Example:

    const { app, net, protocol } = require('electron')
    const path = require('node:path')
    const { pathToFileURL } = require('url')

    protocol.registerSchemesAsPrivileged([
    {
    scheme: 'app',
    privileges: {
    standard: true,
    secure: true,
    supportFetchAPI: true
    }
    }
    ])

    app.whenReady().then(() => {
    protocol.handle('app', (req) => {
    const { host, pathname } = new URL(req.url)
    if (host === 'bundle') {
    if (pathname === '/') {
    return new Response('<h1>hello, world</h1>', {
    headers: { 'content-type': 'text/html' }
    })
    }
    // NB, this checks for paths that escape the bundle, e.g.
    // app://bundle/../../secret_file.txt
    const pathToServe = path.resolve(__dirname, pathname)
    const relativePath = path.relative(__dirname, pathToServe)
    const isSafe = relativePath && !relativePath.startsWith('..') && !path.isAbsolute(relativePath)
    if (!isSafe) {
    return new Response('bad', {
    status: 400,
    headers: { 'content-type': 'text/html' }
    })
    }

    return net.fetch(pathToFileURL(pathToServe).toString())
    } else if (host === 'api') {
    return net.fetch('https://api.my-server.com/' + pathname, {
    method: req.method,
    headers: req.headers,
    body: req.body
    })
    }
    })
    })

    See the MDN docs for Request and Response for more details.

    protocol.unhandle(scheme)

    • scheme string – scheme for which to remove the handler.

    Removes a protocol handler registered with protocol.handle.

    protocol.isProtocolHandled(scheme)

    • scheme string

    Returns boolean – Whether scheme is already handled.

    protocol.registerFileProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully registered

    Registers a protocol of scheme that will send a file as the response. The handler will be called with request and callback where request is an incoming request for the scheme.

    To handle the request, the callback should be called with either the file’s path or an object that has a path property, e.g. callback(filePath) or callback({ path: filePath }). The filePath must be an absolute path.

    By default the scheme is treated like http:, which is parsed differently from protocols that follow the “generic URI syntax” like file:.

    protocol.registerBufferProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully registered

    Registers a protocol of scheme that will send a Buffer as a response.

    The usage is the same with registerFileProtocol, except that the callback should be called with either a Buffer object or an object that has the data property.

    Example:

    protocol.registerBufferProtocol('atom', (request, callback) => {
    callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
    })

    protocol.registerStringProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully registered

    Registers a protocol of scheme that will send a string as a response.

    The usage is the same with registerFileProtocol, except that the callback should be called with either a string or an object that has the data property.

    protocol.registerHttpProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully registered

    Registers a protocol of scheme that will send an HTTP request as a response.

    The usage is the same with registerFileProtocol, except that the callback should be called with an object that has the url property.

    protocol.registerStreamProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully registered

    Registers a protocol of scheme that will send a stream as a response.

    The usage is the same with registerFileProtocol, except that the callback should be called with either a ReadableStream object or an object that has the data property.

    Example:

    const { protocol } = require('electron')
    const { PassThrough } = require('stream')

    function createStream (text) {
    const rv = new PassThrough() // PassThrough is also a Readable stream
    rv.push(text)
    rv.push(null)
    return rv
    }

    protocol.registerStreamProtocol('atom', (request, callback) => {
    callback({
    statusCode: 200,
    headers: {
    'content-type': 'text/html'
    },
    data: createStream('<h5>Response</h5>')
    })
    })

    It is possible to pass any object that implements the readable stream API (emits data/end/error events). For example, here’s how a file could be returned:

    protocol.registerStreamProtocol('atom', (request, callback) => {
    callback(fs.createReadStream('index.html'))
    })

    protocol.unregisterProtocol(scheme) Deprecated

    • scheme string

    Returns boolean – Whether the protocol was successfully unregistered

    Unregisters the custom protocol of scheme.

    protocol.isProtocolRegistered(scheme) Deprecated

    • scheme string

    Returns boolean – Whether scheme is already registered.

    protocol.interceptFileProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully intercepted

    Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a file as a response.

    protocol.interceptStringProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully intercepted

    Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a string as a response.

    protocol.interceptBufferProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully intercepted

    Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a Buffer as a response.

    protocol.interceptHttpProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully intercepted

    Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a new HTTP request as a response.

    protocol.interceptStreamProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully intercepted

    Same as protocol.registerStreamProtocol, except that it replaces an existing protocol handler.

    protocol.uninterceptProtocol(scheme) Deprecated

    • scheme string

    Returns boolean – Whether the protocol was successfully unintercepted

    Remove the interceptor installed for scheme and restore its original handler.

    protocol.isProtocolIntercepted(scheme) Deprecated

    • scheme string

    Returns boolean – Whether scheme is already intercepted.

  • protocol

    Register a custom protocol and intercept existing protocol requests.

    Process: Main

    An 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 session

    A 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('url')

    app.whenReady().then(() => {
    const partition = 'persist:example'
    const ses = session.fromPartition(partition)

    ses.protocol.handle('atom', (request) => {
    const filePath = request.url.slice('atom://'.length)
    return net.fetch(url.pathToFileURL(path.resolve(__dirname, filePath)).toString())
    })

    const mainWindow = new BrowserWindow({ webPreferences: { partition } })
    })

    Methods

    The protocol module has the following methods:

    protocol.registerSchemesAsPrivileged(customSchemes)

    Note: This method can only be used before the ready event of the app module gets emitted and can be called only once.

    Registers the scheme as standard, secure, bypasses content security policy for resources, allows registering ServiceWorker, supports fetch API, streaming video/audio, and V8 code cache. Specify a privilege with the value of true to enable the capability.

    An example of registering a privileged scheme, that bypasses Content Security Policy:

    const { protocol } = require('electron')
    protocol.registerSchemesAsPrivileged([
    { scheme: 'foo', privileges: { bypassCSP: true } }
    ])

    A standard scheme adheres to what RFC 3986 calls generic URI syntax. For example http and https are standard schemes, while file is not.

    Registering a scheme as standard allows relative and absolute resources to be resolved correctly when served. Otherwise the scheme will behave like the file protocol, but without the ability to resolve relative URLs.

    For example when you load following page with custom protocol without registering it as standard scheme, the image will not be loaded because non-standard schemes can not recognize relative URLs:

    <body>
    <img src='test.png'>
    </body>

    Registering a scheme as standard will allow access to files through the FileSystem API. Otherwise the renderer will throw a security error for the scheme.

    By default web storage apis (localStorage, sessionStorage, webSQL, indexedDB, cookies) are disabled for non standard schemes. So in general if you want to register a custom protocol to replace the http protocol, you have to register it as a standard scheme.

    Protocols that use streams (http and stream protocols) should set stream: true. The <video> and <audio> HTML elements expect protocols to buffer their responses by default. The stream flag configures those elements to correctly expect streaming responses.

    protocol.handle(scheme, handler)

    • scheme string – scheme to handle, for example https or my-app. This is the bit before the : in a URL.
    • handler Function<GlobalResponse | Promise>

    Register a protocol handler for scheme. Requests made to URLs with this scheme will delegate to this handler to determine what response should be sent.

    Either a Response or a Promise<Response> can be returned.

    Example:

    const { app, net, protocol } = require('electron')
    const path = require('node:path')
    const { pathToFileURL } = require('url')

    protocol.registerSchemesAsPrivileged([
    {
    scheme: 'app',
    privileges: {
    standard: true,
    secure: true,
    supportFetchAPI: true
    }
    }
    ])

    app.whenReady().then(() => {
    protocol.handle('app', (req) => {
    const { host, pathname } = new URL(req.url)
    if (host === 'bundle') {
    if (pathname === '/') {
    return new Response('<h1>hello, world</h1>', {
    headers: { 'content-type': 'text/html' }
    })
    }
    // NB, this checks for paths that escape the bundle, e.g.
    // app://bundle/../../secret_file.txt
    const pathToServe = path.resolve(__dirname, pathname)
    const relativePath = path.relative(__dirname, pathToServe)
    const isSafe = relativePath && !relativePath.startsWith('..') && !path.isAbsolute(relativePath)
    if (!isSafe) {
    return new Response('bad', {
    status: 400,
    headers: { 'content-type': 'text/html' }
    })
    }

    return net.fetch(pathToFileURL(pathToServe).toString())
    } else if (host === 'api') {
    return net.fetch('https://api.my-server.com/' + pathname, {
    method: req.method,
    headers: req.headers,
    body: req.body
    })
    }
    })
    })

    See the MDN docs for Request and Response for more details.

    protocol.unhandle(scheme)

    • scheme string – scheme for which to remove the handler.

    Removes a protocol handler registered with protocol.handle.

    protocol.isProtocolHandled(scheme)

    • scheme string

    Returns boolean – Whether scheme is already handled.

    protocol.registerFileProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully registered

    Registers a protocol of scheme that will send a file as the response. The handler will be called with request and callback where request is an incoming request for the scheme.

    To handle the request, the callback should be called with either the file’s path or an object that has a path property, e.g. callback(filePath) or callback({ path: filePath }). The filePath must be an absolute path.

    By default the scheme is treated like http:, which is parsed differently from protocols that follow the “generic URI syntax” like file:.

    protocol.registerBufferProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully registered

    Registers a protocol of scheme that will send a Buffer as a response.

    The usage is the same with registerFileProtocol, except that the callback should be called with either a Buffer object or an object that has the data property.

    Example:

    protocol.registerBufferProtocol('atom', (request, callback) => {
    callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
    })

    protocol.registerStringProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully registered

    Registers a protocol of scheme that will send a string as a response.

    The usage is the same with registerFileProtocol, except that the callback should be called with either a string or an object that has the data property.

    protocol.registerHttpProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully registered

    Registers a protocol of scheme that will send an HTTP request as a response.

    The usage is the same with registerFileProtocol, except that the callback should be called with an object that has the url property.

    protocol.registerStreamProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully registered

    Registers a protocol of scheme that will send a stream as a response.

    The usage is the same with registerFileProtocol, except that the callback should be called with either a ReadableStream object or an object that has the data property.

    Example:

    const { protocol } = require('electron')
    const { PassThrough } = require('stream')

    function createStream (text) {
    const rv = new PassThrough() // PassThrough is also a Readable stream
    rv.push(text)
    rv.push(null)
    return rv
    }

    protocol.registerStreamProtocol('atom', (request, callback) => {
    callback({
    statusCode: 200,
    headers: {
    'content-type': 'text/html'
    },
    data: createStream('<h5>Response</h5>')
    })
    })

    It is possible to pass any object that implements the readable stream API (emits data/end/error events). For example, here’s how a file could be returned:

    protocol.registerStreamProtocol('atom', (request, callback) => {
    callback(fs.createReadStream('index.html'))
    })

    protocol.unregisterProtocol(scheme) Deprecated

    • scheme string

    Returns boolean – Whether the protocol was successfully unregistered

    Unregisters the custom protocol of scheme.

    protocol.isProtocolRegistered(scheme) Deprecated

    • scheme string

    Returns boolean – Whether scheme is already registered.

    protocol.interceptFileProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully intercepted

    Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a file as a response.

    protocol.interceptStringProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully intercepted

    Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a string as a response.

    protocol.interceptBufferProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully intercepted

    Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a Buffer as a response.

    protocol.interceptHttpProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully intercepted

    Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a new HTTP request as a response.

    protocol.interceptStreamProtocol(scheme, handler) Deprecated

    Returns boolean – Whether the protocol was successfully intercepted

    Same as protocol.registerStreamProtocol, except that it replaces an existing protocol handler.

    protocol.uninterceptProtocol(scheme) Deprecated

    • scheme string

    Returns boolean – Whether the protocol was successfully unintercepted

    Remove the interceptor installed for scheme and restore its original handler.

    protocol.isProtocolIntercepted(scheme) Deprecated

    • scheme string

    Returns boolean – Whether scheme is already intercepted.

  • process

    Extensions to process object.

    Process: MainRenderer

    Electron’s process object is extended from the Node.js process object. It adds the following events, properties, and methods:

    Sandbox

    In sandboxed renderers the process object contains only a subset of the APIs:

    • crash()
    • hang()
    • getCreationTime()
    • getHeapStatistics()
    • getBlinkMemoryInfo()
    • getProcessMemoryInfo()
    • getSystemMemoryInfo()
    • getSystemVersion()
    • getCPUUsage()
    • uptime()
    • argv
    • execPath
    • env
    • pid
    • arch
    • platform
    • sandboxed
    • contextIsolated
    • type
    • version
    • versions
    • mas
    • windowsStore
    • contextId

    Events

    Event: ‘loaded’

    Emitted when Electron has loaded its internal initialization script and is beginning to load the web page or the main script.

    Properties

    process.defaultApp Readonly

    boolean. When the app is started by being passed as parameter to the default Electron executable, this property is true in the main process, otherwise it is undefined. For example when running the app with electron ., it is true, even if the app is packaged (isPackaged) is true. This can be useful to determine how many arguments will need to be sliced off from process.argv.

    process.isMainFrame Readonly

    booleantrue when the current renderer context is the “main” renderer frame. If you want the ID of the current frame you should use webFrame.routingId.

    process.mas Readonly

    boolean. For Mac App Store build, this property is true, for other builds it is undefined.

    process.noAsar

    boolean that controls ASAR support inside your application. Setting this to true will disable the support for asar archives in Node’s built-in modules.

    process.noDeprecation

    boolean that controls whether or not deprecation warnings are printed to stderr. Setting this to true will silence deprecation warnings. This property is used instead of the --no-deprecation command line flag.

    process.resourcesPath Readonly

    string representing the path to the resources directory.

    process.sandboxed Readonly

    boolean. When the renderer process is sandboxed, this property is true, otherwise it is undefined.

    process.contextIsolated Readonly

    boolean that indicates whether the current renderer context has contextIsolation enabled. It is undefined in the main process.

    process.throwDeprecation

    boolean that controls whether or not deprecation warnings will be thrown as exceptions. Setting this to true will throw errors for deprecations. This property is used instead of the --throw-deprecation command line flag.

    process.traceDeprecation

    boolean that controls whether or not deprecations printed to stderr include their stack trace. Setting this to true will print stack traces for deprecations. This property is instead of the --trace-deprecation command line flag.

    process.traceProcessWarnings

    boolean that controls whether or not process warnings printed to stderr include their stack trace. Setting this to true will print stack traces for process warnings (including deprecations). This property is instead of the --trace-warnings command line flag.

    process.type Readonly

    string representing the current process’s type, can be:

    • browser – The main process
    • renderer – A renderer process
    • worker – In a web worker
    • utility – In a node process launched as a service

    process.versions.chrome Readonly

    string representing Chrome’s version string.

    process.versions.electron Readonly

    string representing Electron’s version string.

    process.windowsStore Readonly

    boolean. If the app is running as a Windows Store app (appx), this property is true, for otherwise it is undefined.

    process.contextId Readonly

    string (optional) representing a globally unique ID of the current JavaScript context. Each frame has its own JavaScript context. When contextIsolation is enabled, the isolated world also has a separate JavaScript context. This property is only available in the renderer process.

    process.parentPort

    Electron.ParentPort property if this is a UtilityProcess (or null otherwise) allowing communication with the parent process.

    Methods

    The process object has the following methods:

    process.crash()

    Causes the main thread of the current process crash.

    process.getCreationTime()

    Returns number | null – The number of milliseconds since epoch, or null if the information is unavailable

    Indicates the creation time of the application. The time is represented as number of milliseconds since epoch. It returns null if it is unable to get the process creation time.

    process.getCPUUsage()

    Returns CPUUsage

    process.getHeapStatistics()

    Returns Object:

    • totalHeapSize Integer
    • totalHeapSizeExecutable Integer
    • totalPhysicalSize Integer
    • totalAvailableSize Integer
    • usedHeapSize Integer
    • heapSizeLimit Integer
    • mallocedMemory Integer
    • peakMallocedMemory Integer
    • doesZapGarbage boolean

    Returns an object with V8 heap statistics. Note that all statistics are reported in Kilobytes.

    process.getBlinkMemoryInfo()

    Returns Object:

    • allocated Integer – Size of all allocated objects in Kilobytes.
    • total Integer – Total allocated space in Kilobytes.

    Returns an object with Blink memory information. It can be useful for debugging rendering / DOM related memory issues. Note that all values are reported in Kilobytes.

    process.getProcessMemoryInfo()

    Returns Promise<ProcessMemoryInfo> – Resolves with a ProcessMemoryInfo

    Returns an object giving memory usage statistics about the current process. Note that all statistics are reported in Kilobytes. This api should be called after app ready.

    Chromium does not provide residentSet value for macOS. This is because macOS performs in-memory compression of pages that haven’t been recently used. As a result the resident set size value is not what one would expect. private memory is more representative of the actual pre-compression memory usage of the process on macOS.

    process.getSystemMemoryInfo()

    Returns Object:

    • total Integer – The total amount of physical memory in Kilobytes available to the system.
    • free Integer – The total amount of memory not being used by applications or disk cache.
    • swapTotal Integer Windows Linux – The total amount of swap memory in Kilobytes available to the system.
    • swapFree Integer Windows Linux – The free amount of swap memory in Kilobytes available to the system.

    Returns an object giving memory usage statistics about the entire system. Note that all statistics are reported in Kilobytes.

    process.getSystemVersion()

    Returns string – The version of the host operating system.

    Example:

    const version = process.getSystemVersion()
    console.log(version)
    // On macOS -> '10.13.6'
    // On Windows -> '10.0.17763'
    // On Linux -> '4.15.0-45-generic'

    Note: It returns the actual operating system version instead of kernel version on macOS unlike os.release().

    process.takeHeapSnapshot(filePath)

    • filePath string – Path to the output file.

    Returns boolean – Indicates whether the snapshot has been created successfully.

    Takes a V8 heap snapshot and saves it to filePath.

    process.hang()

    Causes the main thread of the current process hang.

    process.setFdLimit(maxDescriptors) macOS Linux

    • maxDescriptors Integer

    Sets the file descriptor soft limit to maxDescriptors or the OS hard limit, whichever is lower for the current process.

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