Author: saqibkhan

  • NativeImage

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

    Process: MainRenderer

    The nativeImage module provides a unified interface for manipulating system images. These can be handy if you want to provide multiple scaled versions of the same icon or take advantage of macOS template images.

    Electron APIs that take image files accept either file paths or NativeImage instances. An empty and transparent image will be used when null is passed.

    For example, when creating a Tray or setting a BrowserWindow‘s icon, you can either pass an image file path as a string:

    Main Process

    const { BrowserWindow, Tray } = require('electron')

    const tray = new Tray('/Users/somebody/images/icon.png')
    const win = new BrowserWindow({ icon: '/Users/somebody/images/window.png' })

    or generate a NativeImage instance from the same file:

    Main Process

    const { BrowserWindow, nativeImage, Tray } = require('electron')

    const trayIcon = nativeImage.createFromPath('/Users/somebody/images/icon.png')
    const appIcon = nativeImage.createFromPath('/Users/somebody/images/window.png')
    const tray = new Tray(trayIcon)
    const win = new BrowserWindow({ icon: appIcon })

    Supported Formats

    Currently, PNG and JPEG image formats are supported across all platforms. PNG is recommended because of its support for transparency and lossless compression.

    On Windows, you can also load ICO icons from file paths. For best visual quality, we recommend including at least the following sizes:

    • Small icon
      • 16×16 (100% DPI scale)
      • 20×20 (125% DPI scale)
      • 24×24 (150% DPI scale)
      • 32×32 (200% DPI scale)
    • Large icon
      • 32×32 (100% DPI scale)
      • 40×40 (125% DPI scale)
      • 48×48 (150% DPI scale)
      • 64×64 (200% DPI scale)
      • 256×256

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

    NOTE

    EXIF metadata is currently not supported and will not be taken into account during image encoding and decoding.

    High Resolution Image

    On platforms that support high pixel density displays (such as Apple Retina), you can append @2x after image’s base filename to mark it as a 2x scale high resolution image.

    For example, if icon.png is a normal image that has standard resolution, then [email protected] will be treated as a high resolution image that has double Dots per Inch (DPI) density.

    If you want to support displays with different DPI densities at the same time, you can put images with different sizes in the same folder and use the filename without DPI suffixes within Electron. For example:

    images/
    ├── icon.png
    ├── [email protected]
    └── [email protected]

    Main Process

    const { Tray } = require('electron')
    const appTray = new Tray('/Users/somebody/images/icon.png')

    The following suffixes for DPI are also supported:

    • @1x
    • @1.25x
    • @1.33x
    • @1.4x
    • @1.5x
    • @1.8x
    • @2x
    • @2.5x
    • @3x
    • @4x
    • @5x

    Template Image macOS

    On macOS, template images consist of black and an alpha channel. Template images are not intended to be used as standalone images and are usually mixed with other content to create the desired final appearance.

    The most common case is to use template images for a menu bar (Tray) icon, so it can adapt to both light and dark menu bars.

    To mark an image as a template image, its base filename should end with the word Template (e.g. xxxTemplate.png). You can also specify template images at different DPI densities (e.g. [email protected]).

    Methods

    The nativeImage module has the following methods, all of which return an instance of the NativeImage class:

    nativeImage.createEmpty()

    Returns NativeImage

    Creates an empty NativeImage instance.

    nativeImage.createThumbnailFromPath(path, size) macOS Windows

    • path string – path to a file that we intend to construct a thumbnail out of.
    • size Size – the desired width and height (positive numbers) of the thumbnail.

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

    Note: The Windows implementation will ignore size.height and scale the height according to size.width.

    nativeImage.createFromPath(path)

    • path string – path to a file that we intend to construct an image out of.

    Returns NativeImage

    Creates a new NativeImage instance from a file located at path. This method returns an empty image if the path does not exist, cannot be read, or is not a valid image.

    const { nativeImage } = require('electron')

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

    nativeImage.createFromBitmap(buffer, options)

    • buffer Buffer
    • options Object
      • width Integer
      • height Integer
      • scaleFactor Number (optional) – Defaults to 1.0.

    Returns NativeImage

    Creates a new NativeImage instance from buffer that contains the raw bitmap pixel data returned by toBitmap(). The specific format is platform-dependent.

    nativeImage.createFromBuffer(buffer[, options])

    • buffer Buffer
    • options Object (optional)
      • width Integer (optional) – Required for bitmap buffers.
      • height Integer (optional) – Required for bitmap buffers.
      • scaleFactor Number (optional) – Defaults to 1.0.

    Returns NativeImage

    Creates a new NativeImage instance from buffer. Tries to decode as PNG or JPEG first.

    nativeImage.createFromDataURL(dataURL)

    • dataURL string

    Returns NativeImage

    Creates a new NativeImage instance from dataUrl, a base 64 encoded Data URL string.

    nativeImage.createFromNamedImage(imageName[, hslShift]) macOS

    • imageName string
    • hslShift number[] (optional)

    Returns NativeImage

    Creates a new NativeImage instance from the NSImage that maps to the given image name. See Apple’s NSImageName documentation for a list of possible values.

    The hslShift is applied to the image with the following rules:

    • hsl_shift[0] (hue): The absolute hue value for the image – 0 and 1 map to 0 and 360 on the hue color wheel (red).
    • hsl_shift[1] (saturation): A saturation shift for the image, with the following key values: 0 = remove all color. 0.5 = leave unchanged. 1 = fully saturate the image.
    • hsl_shift[2] (lightness): A lightness shift for the image, with the following key values: 0 = remove all lightness (make all pixels black). 0.5 = leave unchanged. 1 = full lightness (make all pixels white).

    This means that [-1, 0, 1] will make the image completely white and [-1, 1, 0] will make the image completely black.

    In some cases, the NSImageName doesn’t match its string representation; one example of this is NSFolderImageName, whose string representation would actually be NSFolder. Therefore, you’ll need to determine the correct string representation for your image before passing it in. This can be done with the following:

    echo -e '#import <Cocoa/Cocoa.h>\nint main() { NSLog(@"%@", SYSTEM_IMAGE_NAME); }' | clang -otest -x objective-c -framework Cocoa - && ./test

    where SYSTEM_IMAGE_NAME should be replaced with any value from this list.

    Class: NativeImage

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

    Process: MainRenderer
    This class is not exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.

    Instance Methods

    The following methods are available on instances of the NativeImage class:

    image.toPNG([options])

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

    Returns Buffer – A Buffer that contains the image’s PNG encoded data.

    image.toJPEG(quality)

    • quality Integer – Between 0 – 100.

    Returns Buffer – A Buffer that contains the image’s JPEG encoded data.

    image.toBitmap([options])

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

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

    image.toDataURL([options])

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

    Returns string – The Data URL of the image.

    image.getBitmap([options])

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

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

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

    image.getNativeHandle() macOS

    Returns Buffer – A Buffer that stores C pointer to underlying native handle of the image. On macOS, a pointer to NSImage instance is returned.

    Notice that the returned pointer is a weak pointer to the underlying native image instead of a copy, so you must ensure that the associated nativeImage instance is kept around.

    image.isEmpty()

    Returns boolean – Whether the image is empty.

    image.getSize([scaleFactor])

    • scaleFactor Number (optional) – Defaults to 1.0.

    Returns Size.

    If scaleFactor is passed, this will return the size corresponding to the image representation most closely matching the passed value.

    image.setTemplateImage(option)

    • option boolean

    Marks the image as a macOS template image.

    image.isTemplateImage()

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

    image.crop(rect)

    • rect Rectangle – The area of the image to crop.

    Returns NativeImage – The cropped image.

    image.resize(options)

    • options Object
      • width Integer (optional) – Defaults to the image’s width.
      • height Integer (optional) – Defaults to the image’s height.
      • quality string (optional) – The desired quality of the resize image. Possible values include goodbetter, or best. The default is best. These values express a desired quality/speed tradeoff. They are translated into an algorithm-specific method that depends on the capabilities (CPU, GPU) of the underlying platform. It is possible for all three methods to be mapped to the same algorithm on a given platform.

    Returns NativeImage – The resized image.

    If only the height or the width are specified then the current aspect ratio will be preserved in the resized image.

    image.getAspectRatio([scaleFactor])

    • scaleFactor Number (optional) – Defaults to 1.0.

    Returns Number – The image’s aspect ratio (width divided by height).

    If scaleFactor is passed, this will return the aspect ratio corresponding to the image representation most closely matching the passed value.

    image.getScaleFactors()

    Returns Number[] – An array of all scale factors corresponding to representations for a given NativeImage.

    image.addRepresentation(options)

    • options Object
      • scaleFactor Number (optional) – The scale factor to add the image representation for.
      • width Integer (optional) – Defaults to 0. Required if a bitmap buffer is specified as buffer.
      • height Integer (optional) – Defaults to 0. Required if a bitmap buffer is specified as buffer.
      • buffer Buffer (optional) – The buffer containing the raw image data.
      • dataURL string (optional) – The data URL containing either a base 64 encoded PNG or JPEG image.

    Add an image representation for a specific scale factor. This can be used to programmatically add different scale factor representations to an image. This can be called on empty images.

    Instance Properties

    nativeImage.isMacTemplateImage macOS

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

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

  • MessagePortMain

    MessagePortMain is the main-process-side equivalent of the DOM MessagePort object. It behaves similarly to the DOM version, with the exception that it uses the Node.js EventEmitter event system, instead of the DOM EventTarget system. This means you should use port.on('message', ...) to listen for events, instead of port.onmessage = ... or port.addEventListener('message', ...)

    See the Channel Messaging API documentation for more information on using channel messaging.

    MessagePortMain is an EventEmitter.

    Class: MessagePortMain

    Port interface for channel messaging in the main process.

    Process: Main
    This class is not exported from the 'electron' module. It is only available as a return value of other methods in the Electron API.

    Instance Methods

    port.postMessage(message, [transfer])

    • message any
    • transfer MessagePortMain[] (optional)

    Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.

    port.start()

    Starts the sending of messages queued on the port. Messages will be queued until this method is called.

    port.close()

    Disconnects the port, so it is no longer active.

    Instance Events

    Event: ‘message’

    Returns:

    • messageEvent Object
      • data any
      • ports MessagePortMain[]

    Emitted when a MessagePortMain object receives a message.

    Event: ‘close’

    Emitted when the remote end of a MessagePortMain object becomes disconnected.

  • MessageChannelMain

    MessageChannelMain is the main-process-side equivalent of the DOM MessageChannel object. Its singular function is to create a pair of connected MessagePortMain objects.

    See the Channel Messaging API documentation for more information on using channel messaging.

    Class: MessageChannelMain

    Channel interface for channel messaging in the main process.

    Process: Main

    Example:

    // Main process
    const { BrowserWindow, MessageChannelMain } = require('electron')
    const w = new BrowserWindow()
    const { port1, port2 } = new MessageChannelMain()
    w.webContents.postMessage('port', null, [port2])
    port1.postMessage({ some: 'message' })

    // Renderer process
    const { ipcRenderer } = require('electron')
    ipcRenderer.on('port', (e) => {
    // e.ports is a list of ports sent along with this message
    e.ports[0].onmessage = (messageEvent) => {
    console.log(messageEvent.data)
    }
    })

    Instance Properties

    channel.port1

    MessagePortMain property.

    channel.port2

    MessagePortMain property.

  • Menu

    Class: Menu

    Create native application menus and context menus.

    Process: Main

    new Menu()

    Creates a new menu.

    Static Methods

    The Menu class has the following static methods:

    • menu Menu | null

    Sets menu as the application menu on macOS. On Windows and Linux, the menu will be set as each window’s top menu.

    Also on Windows and Linux, you can use a & in the top-level item name to indicate which letter should get a generated accelerator. For example, using &File for the file menu would result in a generated Alt-F accelerator that opens the associated menu. The indicated character in the button label then gets an underline, and the & character is not displayed on the button label.

    In order to escape the & character in an item name, add a proceeding &. For example, &&File would result in &File displayed on the button label.

    Passing null will suppress the default menu. On Windows and Linux, this has the additional effect of removing the menu bar from the window.

    Note: The default menu will be created automatically if the app does not set one. It contains standard items such as FileEditViewWindow and Help.

    Returns Menu | null – The application menu, if set, or null, if not set.

    Note: The returned Menu instance doesn’t support dynamic addition or removal of menu items. Instance properties can still be dynamically modified.

    • action string

    Sends the action to the first responder of application. This is used for emulating default macOS menu behaviors. Usually you would use the role property of a MenuItem.

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

    • template (MenuItemConstructorOptions | MenuItem)[]

    Returns Menu

    Generally, the template is an array of options for constructing a MenuItem. The usage can be referenced above.

    You can also attach other fields to the element of the template and they will become properties of the constructed menu items.

    Instance Methods

    The menu object has the following instance methods:

    • options Object (optional)
      • window BrowserWindow (optional) – Default is the focused window.
      • x number (optional) – Default is the current mouse cursor position. Must be declared if y is declared.
      • y number (optional) – Default is the current mouse cursor position. Must be declared if x is declared.
      • positioningItem number (optional) macOS – The index of the menu item to be positioned under the mouse cursor at the specified coordinates. Default is -1.
      • sourceType string (optional) Windows Linux – This should map to the menuSourceType provided by the context-menu event. It is not recommended to set this value manually, only provide values you receive from other APIs or leave it undefined. Can be nonemousekeyboardtouchtouchMenulongPresslongTaptouchHandlestylusadjustSelection, or adjustSelectionReset.
      • callback Function (optional) – Called when menu is closed.

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

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

    Closes the context menu in the browserWindow.

    Appends the menuItem to the menu.

    • id string

    Returns MenuItem | null the item with the specified id

    Inserts the menuItem to the pos position of the menu.

    Instance Events

    Objects created with new Menu or returned by Menu.buildFromTemplate emit the following events:

    Note: Some events are only available on specific operating systems and are labeled as such.

    Event: ‘menu-will-show’

    Returns:

    • event Event

    Emitted when menu.popup() is called.

    Event: ‘menu-will-close’

    Returns:

    • event Event

    Emitted when a popup is closed either manually or with menu.closePopup().

    Instance Properties

    menu objects also have the following properties:

    MenuItem[] array containing the menu’s items.

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

    Examples

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

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

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

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

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

    Render process

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

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

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

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

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

    Notes on macOS Application Menu

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

    Standard Menus

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

    • window
    • help
    • services

    Standard Menu Item Actions

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

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

    Setting Menu for Specific Browser Window (Linux Windows)

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

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

    • before – Inserts this item before the item with the specified id. If the referenced item doesn’t exist the item will be inserted at the end of the menu. Also implies that the menu item in question should be placed in the same “group” as the item.
    • after – Inserts this item after the item with the specified id. If the referenced item doesn’t exist the item will be inserted at the end of the menu. Also implies that the menu item in question should be placed in the same “group” as the item.
    • beforeGroupContaining – Provides a means for a single context menu to declare the placement of their containing group before the containing group of the item with the specified id.
    • afterGroupContaining – Provides a means for a single context menu to declare the placement of their containing group after the containing group of the item with the specified id.

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

    Examples

    Template:

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

    Menu:

    - 1
    - 2
    - 3
    - 4

    Template:

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

    Menu:

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

    Template:

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

    Menu:

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

    Communicate asynchronously from the main process to renderer processes.

    Process: Main

    The ipcMain module is an Event Emitter. When used in the main process, it handles asynchronous and synchronous messages sent from a renderer process (web page). Messages sent from a renderer will be emitted to this module.

    For usage examples, check out the IPC tutorial.

    Sending messages

    It is also possible to send messages from the main process to the renderer process, see webContents.send for more information.

    • When sending a message, the event name is the channel.
    • To reply to a synchronous message, you need to set event.returnValue.
    • To send an asynchronous message back to the sender, you can use event.reply(...). This helper method will automatically handle messages coming from frames that aren’t the main frame (e.g. iframes) whereas event.sender.send(...) will always send to the main frame.

    Methods

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

    ipcMain.on(channel, listener)

    • channel string
    • listener Function

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

    ipcMain.once(channel, listener)

    • channel string
    • listener Function

    Adds a one time listener function for the event. This listener is invoked only the next time a message is sent to channel, after which it is removed.

    ipcMain.removeListener(channel, listener)

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

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

    ipcMain.removeAllListeners([channel])

    • channel string (optional)

    Removes listeners of the specified channel.

    ipcMain.handle(channel, listener)

    Adds a handler for an invokeable IPC. This handler will be called whenever a renderer calls ipcRenderer.invoke(channel, ...args).

    If listener returns a Promise, the eventual result of the promise will be returned as a reply to the remote caller. Otherwise, the return value of the listener will be used as the value of the reply.

    Main Process

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

    Renderer Process

    async () => {
    const result = await ipcRenderer.invoke('my-invokable-ipc', arg1, arg2)
    // ...
    }

    The event that is passed as the first argument to the handler is the same as that passed to a regular event listener. It includes information about which WebContents is the source of the invoke request.

    Errors thrown through handle in the main process are not transparent as they are serialized and only the message property from the original error is provided to the renderer process. Please refer to #24427 for details.

    ipcMain.handleOnce(channel, listener)

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

    ipcMain.removeHandler(channel)

    • channel string

    Removes any handler for channel, if present.

  • InAppPurchase

    In-app purchases on Mac App Store.

    Process: Main

    Events

    The inAppPurchase module emits the following events:

    Event: ‘transactions-updated’

    Emitted when one or more transactions have been updated.

    Returns:

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

    Methods

    The inAppPurchase module has the following methods:

    inAppPurchase.purchaseProduct(productID[, opts])

    • productID string
    • opts Integer | Object (optional) – If specified as an integer, defines the quantity.
      • quantity Integer (optional) – The number of items the user wants to purchase.
      • username string (optional) – The string that associates the transaction with a user account on your service (applicationUsername).

    Returns Promise<boolean> – Returns true if the product is valid and added to the payment queue.

    You should listen for the transactions-updated event as soon as possible and certainly before you call purchaseProduct.

    inAppPurchase.getProducts(productIDs)

    • productIDs string[] – The identifiers of the products to get.

    Returns Promise<Product[]> – Resolves with an array of Product objects.

    Retrieves the product descriptions.

    inAppPurchase.canMakePayments()

    Returns boolean – whether a user can make a payment.

    inAppPurchase.restoreCompletedTransactions()

    Restores finished transactions. This method can be called either to install purchases on additional devices, or to restore purchases for an application that the user deleted and reinstalled.

    The payment queue delivers a new transaction for each previously completed transaction that can be restored. Each transaction includes a copy of the original transaction.

    inAppPurchase.getReceiptURL()

    Returns string – the path to the receipt.

    inAppPurchase.finishAllTransactions()

    Completes all pending transactions.

    inAppPurchase.finishTransactionByDate(date)

    • date string – The ISO formatted date of the transaction to finish.

    Completes the pending transactions corresponding to the date.

  • GlobalShortcut

    Detect keyboard events when the application does not have keyboard focus.

    Process: Main

    The globalShortcut module can register/unregister a global keyboard shortcut with the operating system so that you can customize the operations for various shortcuts.

    Note: The shortcut is global; it will work even if the app does not have the keyboard focus. This module cannot be used before the ready event of the app module is emitted.

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

    app.whenReady().then(() => {
    // Register a 'CommandOrControl+X' shortcut listener.
    const ret = globalShortcut.register('CommandOrControl+X', () => {
    console.log('CommandOrControl+X is pressed')
    })

    if (!ret) {
    console.log('registration failed')
    }

    // Check whether a shortcut is registered.
    console.log(globalShortcut.isRegistered('CommandOrControl+X'))
    })

    app.on('will-quit', () => {
    // Unregister a shortcut.
    globalShortcut.unregister('CommandOrControl+X')

    // Unregister all shortcuts.
    globalShortcut.unregisterAll()
    })

    Methods

    The globalShortcut module has the following methods:

    globalShortcut.register(accelerator, callback)

    Returns boolean – Whether or not the shortcut was registered successfully.

    Registers a global shortcut of accelerator. The callback is called when the registered shortcut is pressed by the user.

    When the accelerator is already taken by other applications, this call will silently fail. This behavior is intended by operating systems, since they don’t want applications to fight for global shortcuts.

    The following accelerators will not be registered successfully on macOS 10.14 Mojave unless the app has been authorized as a trusted accessibility client:

    • “Media Play/Pause”
    • “Media Next Track”
    • “Media Previous Track”
    • “Media Stop”

    globalShortcut.registerAll(accelerators, callback)

    Registers a global shortcut of all accelerator items in accelerators. The callback is called when any of the registered shortcuts are pressed by the user.

    When a given accelerator is already taken by other applications, this call will silently fail. This behavior is intended by operating systems, since they don’t want applications to fight for global shortcuts.

    The following accelerators will not be registered successfully on macOS 10.14 Mojave unless the app has been authorized as a trusted accessibility client:

    • “Media Play/Pause”
    • “Media Next Track”
    • “Media Previous Track”
    • “Media Stop”

    globalShortcut.isRegistered(accelerator)

    Returns boolean – Whether this application has registered accelerator.

    When the accelerator is already taken by other applications, this call will still return false. This behavior is intended by operating systems, since they don’t want applications to fight for global shortcuts.

    globalShortcut.unregister(accelerator)

    Unregisters the global shortcut of accelerator.

    globalShortcut.unregisterAll()

    Unregisters all of the global shortcuts.

  • Dialog

    Display native system dialogs for opening and saving files, alerting, etc.

    Process: Main

    An example of showing a dialog to select multiple files:

    const { dialog } = require('electron')
    console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))

    Methods

    The dialog module has the following methods:

    dialog.showOpenDialogSync([browserWindow, ]options)

    • browserWindow BrowserWindow (optional)
    • options Object
      • title string (optional)
      • defaultPath string (optional)
      • buttonLabel string (optional) – Custom label for the confirmation button, when left empty the default label will be used.
      • filters FileFilter[] (optional)
      • properties string[] (optional) – Contains which features the dialog should use. The following values are supported:
        • openFile – Allow files to be selected.
        • openDirectory – Allow directories to be selected.
        • multiSelections – Allow multiple paths to be selected.
        • showHiddenFiles – Show hidden files in dialog.
        • createDirectory macOS – Allow creating new directories from dialog.
        • promptToCreate Windows – Prompt for creation if the file path entered in the dialog does not exist. This does not actually create the file at the path but allows non-existent paths to be returned that should be created by the application.
        • noResolveAliases macOS – Disable the automatic alias (symlink) path resolution. Selected aliases will now return the alias path instead of their target path.
        • treatPackageAsDirectory macOS – Treat packages, such as .app folders, as a directory instead of a file.
        • dontAddToRecent Windows – Do not add the item being opened to the recent documents list.
      • message string (optional) macOS – Message to display above input boxes.
      • securityScopedBookmarks boolean (optional) macOS MAS – Create security scoped bookmarks when packaged for the Mac App Store.

    Returns string[] | undefined, the file paths chosen by the user; if the dialog is cancelled it returns undefined.

    The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.

    The filters specifies an array of file types that can be displayed or selected when you want to limit the user to a specific type. For example:

    {
    filters: [
    { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
    { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
    { name: 'Custom File Type', extensions: ['as'] },
    { name: 'All Files', extensions: ['*'] }
    ]
    }

    The extensions array should contain extensions without wildcards or dots (e.g. 'png' is good but '.png' and '*.png' are bad). To show all files, use the '*' wildcard (no other wildcard is supported).

    Note: On Windows and Linux an open dialog can not be both a file selector and a directory selector, so if you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown.

    dialog.showOpenDialogSync(mainWindow, {
    properties: ['openFile', 'openDirectory']
    })

    dialog.showOpenDialog([browserWindow, ]options)

    • browserWindow BrowserWindow (optional)
    • options Object
      • title string (optional)
      • defaultPath string (optional)
      • buttonLabel string (optional) – Custom label for the confirmation button, when left empty the default label will be used.
      • filters FileFilter[] (optional)
      • properties string[] (optional) – Contains which features the dialog should use. The following values are supported:
        • openFile – Allow files to be selected.
        • openDirectory – Allow directories to be selected.
        • multiSelections – Allow multiple paths to be selected.
        • showHiddenFiles – Show hidden files in dialog.
        • createDirectory macOS – Allow creating new directories from dialog.
        • promptToCreate Windows – Prompt for creation if the file path entered in the dialog does not exist. This does not actually create the file at the path but allows non-existent paths to be returned that should be created by the application.
        • noResolveAliases macOS – Disable the automatic alias (symlink) path resolution. Selected aliases will now return the alias path instead of their target path.
        • treatPackageAsDirectory macOS – Treat packages, such as .app folders, as a directory instead of a file.
        • dontAddToRecent Windows – Do not add the item being opened to the recent documents list.
      • message string (optional) macOS – Message to display above input boxes.
      • securityScopedBookmarks boolean (optional) macOS MAS – Create security scoped bookmarks when packaged for the Mac App Store.

    Returns Promise<Object> – Resolve with an object containing the following:

    • canceled boolean – whether or not the dialog was canceled.
    • filePaths string[] – An array of file paths chosen by the user. If the dialog is cancelled this will be an empty array.
    • bookmarks string[] (optional) macOS MAS – An array matching the filePaths array of base64 encoded strings which contains security scoped bookmark data. securityScopedBookmarks must be enabled for this to be populated. (For return values, see table here.)

    The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.

    The filters specifies an array of file types that can be displayed or selected when you want to limit the user to a specific type. For example:

    {
    filters: [
    { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
    { name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] },
    { name: 'Custom File Type', extensions: ['as'] },
    { name: 'All Files', extensions: ['*'] }
    ]
    }

    The extensions array should contain extensions without wildcards or dots (e.g. 'png' is good but '.png' and '*.png' are bad). To show all files, use the '*' wildcard (no other wildcard is supported).

    Note: On Windows and Linux an open dialog can not be both a file selector and a directory selector, so if you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown.

    dialog.showOpenDialog(mainWindow, {
    properties: ['openFile', 'openDirectory']
    }).then(result => {
    console.log(result.canceled)
    console.log(result.filePaths)
    }).catch(err => {
    console.log(err)
    })

    dialog.showSaveDialogSync([browserWindow, ]options)

    • browserWindow BrowserWindow (optional)
    • options Object
      • title string (optional) – The dialog title. Cannot be displayed on some Linux desktop environments.
      • defaultPath string (optional) – Absolute directory path, absolute file path, or file name to use by default.
      • buttonLabel string (optional) – Custom label for the confirmation button, when left empty the default label will be used.
      • filters FileFilter[] (optional)
      • message string (optional) macOS – Message to display above text fields.
      • nameFieldLabel string (optional) macOS – Custom label for the text displayed in front of the filename text field.
      • showsTagField boolean (optional) macOS – Show the tags input box, defaults to true.
      • properties string[] (optional)
        • showHiddenFiles – Show hidden files in dialog.
        • createDirectory macOS – Allow creating new directories from dialog.
        • treatPackageAsDirectory macOS – Treat packages, such as .app folders, as a directory instead of a file.
        • showOverwriteConfirmation Linux – Sets whether the user will be presented a confirmation dialog if the user types a file name that already exists.
        • dontAddToRecent Windows – Do not add the item being saved to the recent documents list.
      • securityScopedBookmarks boolean (optional) macOS MAS – Create a security scoped bookmark when packaged for the Mac App Store. If this option is enabled and the file doesn’t already exist a blank file will be created at the chosen path.

    Returns string, the path of the file chosen by the user; if the dialog is cancelled it returns an empty string.

    The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.

    The filters specifies an array of file types that can be displayed, see dialog.showOpenDialog for an example.

    dialog.showSaveDialog([browserWindow, ]options)

    • browserWindow BrowserWindow (optional)
    • options Object
      • title string (optional) – The dialog title. Cannot be displayed on some Linux desktop environments.
      • defaultPath string (optional) – Absolute directory path, absolute file path, or file name to use by default.
      • buttonLabel string (optional) – Custom label for the confirmation button, when left empty the default label will be used.
      • filters FileFilter[] (optional)
      • message string (optional) macOS – Message to display above text fields.
      • nameFieldLabel string (optional) macOS – Custom label for the text displayed in front of the filename text field.
      • showsTagField boolean (optional) macOS – Show the tags input box, defaults to true.
      • properties string[] (optional)
        • showHiddenFiles – Show hidden files in dialog.
        • createDirectory macOS – Allow creating new directories from dialog.
        • treatPackageAsDirectory macOS – Treat packages, such as .app folders, as a directory instead of a file.
        • showOverwriteConfirmation Linux – Sets whether the user will be presented a confirmation dialog if the user types a file name that already exists.
        • dontAddToRecent Windows – Do not add the item being saved to the recent documents list.
      • securityScopedBookmarks boolean (optional) macOS MAS – Create a security scoped bookmark when packaged for the Mac App Store. If this option is enabled and the file doesn’t already exist a blank file will be created at the chosen path.

    Returns Promise<Object> – Resolve with an object containing the following:

    • canceled boolean – whether or not the dialog was canceled.
    • filePath string – If the dialog is canceled, this will be an empty string.
    • bookmark string (optional) macOS MAS – Base64 encoded string which contains the security scoped bookmark data for the saved file. securityScopedBookmarks must be enabled for this to be present. (For return values, see table here.)

    The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.

    The filters specifies an array of file types that can be displayed, see dialog.showOpenDialog for an example.

    Note: On macOS, using the asynchronous version is recommended to avoid issues when expanding and collapsing the dialog.

    dialog.showMessageBoxSync([browserWindow, ]options)

    • browserWindow BrowserWindow (optional)
    • options Object
      • message string – Content of the message box.
      • type string (optional) – Can be noneinfoerrorquestion or warning. On Windows, question displays the same icon as info, unless you set an icon using the icon option. On macOS, both warning and error display the same warning icon.
      • buttons string[] (optional) – Array of texts for buttons. On Windows, an empty array will result in one button labeled “OK”.
      • defaultId Integer (optional) – Index of the button in the buttons array which will be selected by default when the message box opens.
      • title string (optional) – Title of the message box, some platforms will not show it.
      • detail string (optional) – Extra information of the message.
      • icon (NativeImage | string) (optional)
      • textWidth Integer (optional) macOS – Custom width of the text in the message box.
      • cancelId Integer (optional) – The index of the button to be used to cancel the dialog, via the Esc key. By default this is assigned to the first button with “cancel” or “no” as the label. If no such labeled buttons exist and this option is not set, 0 will be used as the return value.
      • noLink boolean (optional) – On Windows Electron will try to figure out which one of the buttons are common buttons (like “Cancel” or “Yes”), and show the others as command links in the dialog. This can make the dialog appear in the style of modern Windows apps. If you don’t like this behavior, you can set noLink to true.
      • normalizeAccessKeys boolean (optional) – Normalize the keyboard access keys across platforms. Default is false. Enabling this assumes & is used in the button labels for the placement of the keyboard shortcut access key and labels will be converted so they work correctly on each platform, & characters are removed on macOS, converted to _ on Linux, and left untouched on Windows. For example, a button label of Vie&w will be converted to Vie_w on Linux and View on macOS and can be selected via Alt-W on Windows and Linux.

    Returns Integer – the index of the clicked button.

    Shows a message box, it will block the process until the message box is closed. It returns the index of the clicked button.

    The browserWindow argument allows the dialog to attach itself to a parent window, making it modal. If browserWindow is not shown dialog will not be attached to it. In such case it will be displayed as an independent window.

    dialog.showMessageBox([browserWindow, ]options)

    • browserWindow BrowserWindow (optional)
    • options Object
      • message string – Content of the message box.
      • type string (optional) – Can be noneinfoerrorquestion or warning. On Windows, question displays the same icon as info, unless you set an icon using the icon option. On macOS, both warning and error display the same warning icon.
      • buttons string[] (optional) – Array of texts for buttons. On Windows, an empty array will result in one button labeled “OK”.
      • defaultId Integer (optional) – Index of the button in the buttons array which will be selected by default when the message box opens.
      • signal AbortSignal (optional) – Pass an instance of AbortSignal to optionally close the message box, the message box will behave as if it was cancelled by the user. On macOS, signal does not work with message boxes that do not have a parent window, since those message boxes run synchronously due to platform limitations.
      • title string (optional) – Title of the message box, some platforms will not show it.
      • detail string (optional) – Extra information of the message.
      • checkboxLabel string (optional) – If provided, the message box will include a checkbox with the given label.
      • checkboxChecked boolean (optional) – Initial checked state of the checkbox. false by default.
      • icon (NativeImage | string) (optional)
      • textWidth Integer (optional) macOS – Custom width of the text in the message box.
      • cancelId Integer (optional) – The index of the button to be used to cancel the dialog, via the Esc key. By default this is assigned to the first button with “cancel” or “no” as the label. If no such labeled buttons exist and this option is not set, 0 will be used as the return value.
      • noLink boolean (optional) – On Windows Electron will try to figure out which one of the buttons are common buttons (like “Cancel” or “Yes”), and show the others as command links in the dialog. This can make the dialog appear in the style of modern Windows apps. If you don’t like this behavior, you can set noLink to true.
      • normalizeAccessKeys boolean (optional) – Normalize the keyboard access keys across platforms. Default is false. Enabling this assumes & is used in the button labels for the placement of the keyboard shortcut access key and labels will be converted so they work correctly on each platform, & characters are removed on macOS, converted to _ on Linux, and left untouched on Windows. For example, a button label of Vie&w will be converted to Vie_w on Linux and View on macOS and can be selected via Alt-W on Windows and Linux.

    Returns Promise<Object> – resolves with a promise containing the following properties:

    • response number – The index of the clicked button.
    • checkboxChecked boolean – The checked state of the checkbox if checkboxLabel was set. Otherwise false.

    Shows a message box.

    The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.

    dialog.showErrorBox(title, content)

    • title string – The title to display in the error box.
    • content string – The text content to display in the error box.

    Displays a modal dialog that shows an error message.

    This API can be called safely before the ready event the app module emits, it is usually used to report errors in early stage of startup. If called before the app readyevent on Linux, the message will be emitted to stderr, and no GUI dialog will appear.

    dialog.showCertificateTrustDialog([browserWindow, ]options) macOS Windows

    • browserWindow BrowserWindow (optional)
    • options Object
      • certificate Certificate – The certificate to trust/import.
      • message string – The message to display to the user.

    Returns Promise<void> – resolves when the certificate trust dialog is shown.

    On macOS, this displays a modal dialog that shows a message and certificate information, and gives the user the option of trusting/importing the certificate. If you provide a browserWindow argument the dialog will be attached to the parent window, making it modal.

    On Windows the options are more limited, due to the Win32 APIs used:

    • The message argument is not used, as the OS provides its own confirmation dialog.
    • The browserWindow argument is ignored since it is not possible to make this confirmation dialog modal.

    Bookmarks array

    showOpenDialogshowOpenDialogSyncshowSaveDialog, and showSaveDialogSync will return a bookmarks array.

    Build TypesecurityScopedBookmarks booleanReturn TypeReturn Value
    macOS masTrueSuccess['LONGBOOKMARKSTRING']
    macOS masTrueError[''] (array of empty string)
    macOS masFalseNA[] (empty array)
    non masanyNA[] (empty array)

    Sheets

    On macOS, dialogs are presented as sheets attached to a window if you provide a BrowserWindow reference in the browserWindow parameter, or modals if no window is provided.

    You can call BrowserWindow.getCurrentWindow().setSheetOffset(offset) to change the offset from the window frame where sheets are attached.

  • DesktopCapturer

    Access information about media sources that can be used to capture audio and video from the desktop using the navigator.mediaDevices.getUserMedia API.

    Process: Main

    The following example shows how to capture video from a desktop window whose title is Electron:

    // main.js
    const { app, BrowserWindow, desktopCapturer, session } = require('electron')

    app.whenReady().then(() => {
    const mainWindow = new BrowserWindow()

    session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
    desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
    // Grant access to the first screen found.
    callback({ video: sources[0], audio: 'loopback' })
    })
    })

    mainWindow.loadFile('index.html')
    })
    // renderer.js
    const startButton = document.getElementById('startButton')
    const stopButton = document.getElementById('stopButton')
    const video = document.querySelector('video')

    startButton.addEventListener('click', () => {
    navigator.mediaDevices.getDisplayMedia({
    audio: true,
    video: {
    width: 320,
    height: 240,
    frameRate: 30
    }
    }).then(stream => {
    video.srcObject = stream
    video.onloadedmetadata = (e) => video.play()
    }).catch(e => console.log(e))
    })

    stopButton.addEventListener('click', () => {
    video.pause()
    })
    <!-- index.html -->
    <html>
    <meta http-equiv="content-security-policy" content="script-src 'self' 'unsafe-inline'" />
    <body>
    <button id="startButton" class="button">Start</button>
    <button id="stopButton" class="button">Stop</button>
    <video width="320" height="240" autoplay></video>
    <script src="renderer.js"></script>
    </body>
    </html>

    See navigator.mediaDevices.getDisplayMedia for more information.

    Note: navigator.mediaDevices.getDisplayMedia does not permit the use of deviceId for selection of a source – see specification.

    Methods

    The desktopCapturer module has the following methods:

    desktopCapturer.getSources(options)

    • options Object
      • types string[] – An array of strings that lists the types of desktop sources to be captured, available types can be screen and window.
      • thumbnailSize Size (optional) – The size that the media source thumbnail should be scaled to. Default is 150 x 150. Set width or height to 0 when you do not need the thumbnails. This will save the processing time required for capturing the content of each window and screen.
      • fetchWindowIcons boolean (optional) – Set to true to enable fetching window icons. The default value is false. When false the appIcon property of the sources return null. Same if a source has the type screen.

    Returns Promise<DesktopCapturerSource[]> – Resolves with an array of DesktopCapturerSource objects, each DesktopCapturerSource represents a screen or an individual window that can be captured.

    Note Capturing the screen contents requires user consent on macOS 10.15 Catalina or higher, which can detected by systemPreferences.getMediaAccessStatus.

    Caveats

    navigator.mediaDevices.getUserMedia does not work on macOS for audio capture due to a fundamental limitation whereby apps that want to access the system’s audio require a signed kernel extension. Chromium, and by extension Electron, does not provide this.

    It is possible to circumvent this limitation by capturing system audio with another macOS app like Soundflower and passing it through a virtual audio input device. This virtual device can then be queried with navigator.mediaDevices.getUserMedia.

  • CrashReporter

    Submit crash reports to a remote server.

    Process: MainRenderer

    The following is an example of setting up Electron to automatically submit crash reports to a remote server:

    const { crashReporter } = require('electron')

    crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' })

    For setting up a server to accept and process crash reports, you can use following projects:

    Note: Electron uses Crashpad, not Breakpad, to collect and upload crashes, but for the time being, the upload protocol is the same.

    Or use a 3rd party hosted solution:

    Crash reports are stored temporarily before being uploaded in a directory underneath the app’s user data directory, called ‘Crashpad’. You can override this directory by calling app.setPath('crashDumps', '/path/to/crashes') before starting the crash reporter.

    Electron uses crashpad to monitor and report crashes.

    Methods

    The crashReporter module has the following methods:

    crashReporter.start(options)

    • options Object
      • submitURL string (optional) – URL that crash reports will be sent to as POST. Required unless uploadToServer is false.
      • productName string (optional) – Defaults to app.name.
      • companyName string (optional) Deprecated – Deprecated alias for { globalExtra: { _companyName: ... } }.
      • uploadToServer boolean (optional) – Whether crash reports should be sent to the server. If false, crash reports will be collected and stored in the crashes directory, but not uploaded. Default is true.
      • ignoreSystemCrashHandler boolean (optional) – If true, crashes generated in the main process will not be forwarded to the system crash handler. Default is false.
      • rateLimit boolean (optional) macOS Windows – If true, limit the number of crashes uploaded to 1/hour. Default is false.
      • compress boolean (optional) – If true, crash reports will be compressed and uploaded with Content-Encoding: gzip. Default is true.
      • extra Record<string, string> (optional) – Extra string key/value annotations that will be sent along with crash reports that are generated in the main process. Only string values are supported. Crashes generated in child processes will not contain these extra parameters to crash reports generated from child processes, call addExtraParameter from the child process.
      • globalExtra Record<string, string> (optional) – Extra string key/value annotations that will be sent along with any crash reports generated in any process. These annotations cannot be changed once the crash reporter has been started. If a key is present in both the global extra parameters and the process-specific extra parameters, then the global one will take precedence. By default, productName and the app version are included, as well as the Electron version.

    This method must be called before using any other crashReporter APIs. Once initialized this way, the crashpad handler collects crashes from all subsequently created processes. The crash reporter cannot be disabled once started.

    This method should be called as early as possible in app startup, preferably before app.on('ready'). If the crash reporter is not initialized at the time a renderer process is created, then that renderer process will not be monitored by the crash reporter.

    Note: You can test out the crash reporter by generating a crash using process.crash().

    Note: If you need to send additional/updated extra parameters after your first call start you can call addExtraParameter.

    Note: Parameters passed in extraglobalExtra or set with addExtraParameter have limits on the length of the keys and values. Key names must be at most 39 bytes long, and values must be no longer than 127 bytes. Keys with names longer than the maximum will be silently ignored. Key values longer than the maximum length will be truncated.

    Note: This method is only available in the main process.

    crashReporter.getLastCrashReport()

    Returns CrashReport | null – The date and ID of the last crash report. Only crash reports that have been uploaded will be returned; even if a crash report is present on disk it will not be returned until it is uploaded. In the case that there are no uploaded reports, null is returned.

    Note: This method is only available in the main process.

    crashReporter.getUploadedReports()

    Returns CrashReport[]:

    Returns all uploaded crash reports. Each report contains the date and uploaded ID.

    Note: This method is only available in the main process.

    crashReporter.getUploadToServer()

    Returns boolean – Whether reports should be submitted to the server. Set through the start method or setUploadToServer.

    Note: This method is only available in the main process.

    crashReporter.setUploadToServer(uploadToServer)

    • uploadToServer boolean – Whether reports should be submitted to the server.

    This would normally be controlled by user preferences. This has no effect if called before start is called.

    Note: This method is only available in the main process.

    crashReporter.addExtraParameter(key, value)

    • key string – Parameter key, must be no longer than 39 bytes.
    • value string – Parameter value, must be no longer than 127 bytes.

    Set an extra parameter to be sent with the crash report. The values specified here will be sent in addition to any values set via the extra option when start was called.

    Parameters added in this fashion (or via the extra parameter to crashReporter.start) are specific to the calling process. Adding extra parameters in the main process will not cause those parameters to be sent along with crashes from renderer or other child processes. Similarly, adding extra parameters in a renderer process will not result in those parameters being sent with crashes that occur in other renderer processes or in the main process.

    Note: Parameters have limits on the length of the keys and values. Key names must be no longer than 39 bytes, and values must be no longer than 20320 bytes. Keys with names longer than the maximum will be silently ignored. Key values longer than the maximum length will be truncated.

    crashReporter.removeExtraParameter(key)

    • key string – Parameter key, must be no longer than 39 bytes.

    Remove an extra parameter from the current set of parameters. Future crashes will not include this parameter.

    crashReporter.getParameters()

    Returns Record<string, string> – The current ‘extra’ parameters of the crash reporter.

    In Node child processes

    Since require('electron') is not available in Node child processes, the following APIs are available on the process object in Node child processes.

    process.crashReporter.start(options)

    See crashReporter.start().

    Note that if the crash reporter is started in the main process, it will automatically monitor child processes, so it should not be started in the child process. Only use this method if the main process does not initialize the crash reporter.

    process.crashReporter.getParameters()

    See crashReporter.getParameters().

    process.crashReporter.addExtraParameter(key, value)

    See crashReporter.addExtraParameter(key, value).

    process.crashReporter.removeExtraParameter(key)

    See crashReporter.removeExtraParameter(key).

    Crash Report Payload

    The crash reporter will send the following data to the submitURL as a multipart/form-data POST:

    • ver string – The version of Electron.
    • platform string – e.g. ‘win32’.
    • process_type string – e.g. ‘renderer’.
    • guid string – e.g. ‘5e1286fc-da97-479e-918b-6bfb0c3d1c72’.
    • _version string – The version in package.json.
    • _productName string – The product name in the crashReporter options object.
    • prod string – Name of the underlying product. In this case Electron.
    • _companyName string – The company name in the crashReporter options object.
    • upload_file_minidump File – The crash report in the format of minidump.
    • All level one properties of the extra object in the crashReporter options object.