Electron Documentation1.6.2

Docs / All

Accelerator

Define keyboard shortcuts.

Accelerators are Strings that can contain multiple modifiers and key codes, combined by the + character, and are used to define keyboard shortcuts throughout your application.

Examples:

Shortcuts are registered with the globalShortcut module using the register method, i.e.

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

app.on('ready', () => {
  // Register a 'CommandOrControl+Y' shortcut listener.
  globalShortcut.register('CommandOrControl+Y', () => {
    // Do stuff when Y and either Command/Control is pressed.
  })
})

Platform notice

On Linux and Windows, the Command key does not have any effect so use CommandOrControl which represents Command on macOS and Control on Linux and Windows to define some accelerators.

Use Alt instead of Option. The Option key only exists on macOS, whereas the Alt key is available on all platforms.

The Super key is mapped to the Windows key on Windows and Linux and Cmd on macOS.

Available modifiers

Available key codes


app

Control your application’s event lifecycle.

Process: Main

The following example shows how to quit the application when the last window is closed:

const {app} = require('electron')
app.on('window-all-closed', () => {
  app.quit()
})

Events

The app object emits the following events:

Event: ‘will-finish-launching’

Emitted when the application has finished basic startup. On Windows and Linux, the will-finish-launching event is the same as the ready event; on macOS, this event represents the applicationWillFinishLaunching notification of NSApplication. You would usually set up listeners for the open-file and open-url events here, and start the crash reporter and auto updater.

In most cases, you should just do everything in the ready event handler.

Event: ‘ready’

Returns:

Emitted when Electron has finished initializing. On macOS, launchInfo holds the userInfo of the NSUserNotification that was used to open the application, if it was launched from Notification Center. You can call app.isReady() to check if this event has already fired.

Event: ‘window-all-closed’

Emitted when all windows have been closed.

If you do not subscribe to this event and all windows are closed, the default behavior is to quit the app; however, if you subscribe, you control whether the app quits or not. If the user pressed Cmd + Q, or the developer called app.quit(), Electron will first try to close all the windows and then emit the will-quit event, and in this case the window-all-closed event would not be emitted.

Event: ‘before-quit’

Returns:

Emitted before the application starts closing its windows. Calling event.preventDefault() will prevent the default behaviour, which is terminating the application.

Note: If application quit was initiated by autoUpdater.quitAndInstall() then before-quit is emitted after emitting close event on all windows and closing them.

Event: ‘will-quit’

Returns:

Emitted when all windows have been closed and the application will quit. Calling event.preventDefault() will prevent the default behaviour, which is terminating the application.

See the description of the window-all-closed event for the differences between the will-quit and window-all-closed events.

Event: ‘quit’

Returns:

Emitted when the application is quitting.

Event: ‘open-file’ macOS

Returns:

Emitted when the user wants to open a file with the application. The open-file event is usually emitted when the application is already open and the OS wants to reuse the application to open the file. open-file is also emitted when a file is dropped onto the dock and the application is not yet running. Make sure to listen for the open-file event very early in your application startup to handle this case (even before the ready event is emitted).

You should call event.preventDefault() if you want to handle this event.

On Windows, you have to parse process.argv (in the main process) to get the filepath.

Event: ‘open-url’ macOS

Returns:

Emitted when the user wants to open a URL with the application. Your application’s Info.plist file must define the url scheme within the CFBundleURLTypes key, and set NSPrincipalClass to AtomApplication.

You should call event.preventDefault() if you want to handle this event.

Event: ‘activate’ macOS

Returns:

Emitted when the application is activated. Various actions can trigger this event, such as launching the application for the first time, attempting to re-launch the application when it’s already running, or clicking on the application’s dock or taskbar icon.

Event: ‘continue-activity’ macOS

Returns:

Emitted during Handoff when an activity from a different device wants to be resumed. You should call event.preventDefault() if you want to handle this event.

A user activity can be continued only in an app that has the same developer Team ID as the activity’s source app and that supports the activity’s type. Supported activity types are specified in the app’s Info.plist under the NSUserActivityTypes key.

Event: ‘browser-window-blur’

Returns:

Emitted when a browserWindow gets blurred.

Event: ‘browser-window-focus’

Returns:

Emitted when a browserWindow gets focused.

Event: ‘browser-window-created’

Returns:

Emitted when a new browserWindow is created.

Event: ‘web-contents-created’

Returns:

Emitted when a new webContents is created.

Event: ‘certificate-error’

Returns:

Emitted when failed to verify the certificate for url, to trust the certificate you should prevent the default behavior with event.preventDefault() and call callback(true).

const {app} = require('electron')

app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  if (url === 'https://github.com') {
    // Verification logic.
    event.preventDefault()
    callback(true)
  } else {
    callback(false)
  }
})

Event: ‘select-client-certificate’

Returns:

Emitted when a client certificate is requested.

The url corresponds to the navigation entry requesting the client certificate and callback can be called with an entry filtered from the list. Using event.preventDefault() prevents the application from using the first certificate from the store.

const {app} = require('electron')

app.on('select-client-certificate', (event, webContents, url, list, callback) => {
  event.preventDefault()
  callback(list[0])
})

Event: ‘login’

Returns:

Emitted when webContents wants to do basic auth.

The default behavior is to cancel all authentications, to override this you should prevent the default behavior with event.preventDefault() and call callback(username, password) with the credentials.

const {app} = require('electron')

app.on('login', (event, webContents, request, authInfo, callback) => {
  event.preventDefault()
  callback('username', 'secret')
})

Event: ‘gpu-process-crashed’

Returns:

Emitted when the gpu process crashes or is killed.

Event: ‘accessibility-support-changed’ macOS Windows

Returns:

Emitted when Chrome’s accessibility support changes. This event fires when assistive technologies, such as screen readers, are enabled or disabled. See https://www.chromium.org/developers/design-documents/accessibility for more details.

Methods

The app object has the following methods:

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

app.quit()

Try to close all windows. The before-quit event will be emitted first. If all windows are successfully closed, the will-quit event will be emitted and by default the application will terminate.

This method guarantees that all beforeunload and unload event handlers are correctly executed. It is possible that a window cancels the quitting by returning false in the beforeunload event handler.

app.exit([exitCode])

Exits immediately with exitCode. exitCode defaults to 0.

All windows will be closed immediately without asking user and the before-quit and will-quit events will not be emitted.

app.relaunch([options])

Relaunches the app when current instance exits.

By default the new instance will use the same working directory and command line arguments with current instance. When args is specified, the args will be passed as command line arguments instead. When execPath is specified, the execPath will be executed for relaunch instead of current app.

Note that this method does not quit the app when executed, you have to call app.quit or app.exit after calling app.relaunch to make the app restart.

When app.relaunch is called for multiple times, multiple instances will be started after current instance exited.

An example of restarting current instance immediately and adding a new command line argument to the new instance:

const {app} = require('electron')

app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])})
app.exit(0)

app.isReady()

Returns Boolean - true if Electron has finished initializing, false otherwise.

app.focus()

On Linux, focuses on the first visible window. On macOS, makes the application the active app. On Windows, focuses on the application’s first window.

app.hide() macOS

Hides all application windows without minimizing them.

app.show() macOS

Shows application windows after they were hidden. Does not automatically focus them.

app.getAppPath()

Returns String - The current application directory.

app.getPath(name)

Returns String - A path to a special directory or file associated with name. On failure an Error is thrown.

You can request the following paths by the name:

app.getFileIcon(path[, options], callback)

Fetches a path’s associated icon.

On Windows, there a 2 kinds of icons:

On Linux and macOS, icons depend on the application associated with file mime type.

app.setPath(name, path)

Overrides the path to a special directory or file associated with name. If the path specifies a directory that does not exist, the directory will be created by this method. On failure an Error is thrown.

You can only override paths of a name defined in app.getPath.

By default, web pages’ cookies and caches will be stored under the userData directory. If you want to change this location, you have to override the userData path before the ready event of the app module is emitted.

app.getVersion()

Returns String - The version of the loaded application. If no version is found in the application’s package.json file, the version of the current bundle or executable is returned.

app.getName()

Returns String - The current application’s name, which is the name in the application’s package.json file.

Usually the name field of package.json is a short lowercased name, according to the npm modules spec. You should usually also specify a productName field, which is your application’s full capitalized name, and which will be preferred over name by Electron.

app.setName(name)

Overrides the current application’s name.

app.getLocale()

Returns String - The current application locale. Possible return values are documented here.

Note: When distributing your packaged app, you have to also ship the locales folder.

Note: On Windows you have to call it after the ready events gets emitted.

app.addRecentDocument(path) macOS Windows

Adds path to the recent documents list.

This list is managed by the OS. On Windows you can visit the list from the task bar, and on macOS you can visit it from dock menu.

app.clearRecentDocuments() macOS Windows

Clears the recent documents list.

app.setAsDefaultProtocolClient(protocol[, path, args]) macOS Windows

Returns Boolean - Whether the call succeeded.

This method sets the current executable as the default handler for a protocol (aka URI scheme). It allows you to integrate your app deeper into the operating system. Once registered, all links with your-protocol:// will be opened with the current executable. The whole link, including protocol, will be passed to your application as a parameter.

On Windows you can provide optional parameters path, the path to your executable, and args, an array of arguments to be passed to your executable when it launches.

Note: On macOS, you can only register protocols that have been added to your app’s info.plist, which can not be modified at runtime. You can however change the file with a simple text editor or script during build time. Please refer to Apple’s documentation for details.

The API uses the Windows Registry and LSSetDefaultHandlerForURLScheme internally.

app.removeAsDefaultProtocolClient(protocol[, path, args]) macOS Windows

Returns Boolean - Whether the call succeeded.

This method checks if the current executable as the default handler for a protocol (aka URI scheme). If so, it will remove the app as the default handler.

app.isDefaultProtocolClient(protocol[, path, args]) macOS Windows

Returns Boolean

This method checks if the current executable is the default handler for a protocol (aka URI scheme). If so, it will return true. Otherwise, it will return false.

Note: On macOS, you can use this method to check if the app has been registered as the default protocol handler for a protocol. You can also verify this by checking ~/Library/Preferences/com.apple.LaunchServices.plist on the macOS machine. Please refer to Apple’s documentation for details.

The API uses the Windows Registry and LSCopyDefaultHandlerForURLScheme internally.

app.setUserTasks(tasks) Windows

Adds tasks to the Tasks category of the JumpList on Windows.

tasks is an array of Task objects.

Returns Boolean - Whether the call succeeded.

Note: If you’d like to customize the Jump List even more use app.setJumpList(categories) instead.

app.getJumpListSettings() Windows

Returns Object:

app.setJumpList(categories) Windows

Sets or removes a custom Jump List for the application, and returns one of the following strings:

If categories is null the previously set custom Jump List (if any) will be replaced by the standard Jump List for the app (managed by Windows).

Note: If a JumpListCategory object has neither the type nor the name property set then its type is assumed to be tasks. If the name property is set but the type property is omitted then the type is assumed to be custom.

Note: Users can remove items from custom categories, and Windows will not allow a removed item to be added back into a custom category until after the next successful call to app.setJumpList(categories). Any attempt to re-add a removed item to a custom category earlier than that will result in the entire custom category being omitted from the Jump List. The list of removed items can be obtained using app.getJumpListSettings().

Here’s a very simple example of creating a custom Jump List:

const {app} = require('electron')

app.setJumpList([
  {
    type: 'custom',
    name: 'Recent Projects',
    items: [
      { type: 'file', path: 'C:\\Projects\\project1.proj' },
      { type: 'file', path: 'C:\\Projects\\project2.proj' }
    ]
  },
  { // has a name so `type` is assumed to be "custom"
    name: 'Tools',
    items: [
      {
        type: 'task',
        title: 'Tool A',
        program: process.execPath,
        args: '--run-tool-a',
        icon: process.execPath,
        iconIndex: 0,
        description: 'Runs Tool A'
      },
      {
        type: 'task',
        title: 'Tool B',
        program: process.execPath,
        args: '--run-tool-b',
        icon: process.execPath,
        iconIndex: 0,
        description: 'Runs Tool B'
      }
    ]
  },
  { type: 'frequent' },
  { // has no name and no type so `type` is assumed to be "tasks"
    items: [
      {
        type: 'task',
        title: 'New Project',
        program: process.execPath,
        args: '--new-project',
        description: 'Create a new project.'
      },
      { type: 'separator' },
      {
        type: 'task',
        title: 'Recover Project',
        program: process.execPath,
        args: '--recover-project',
        description: 'Recover Project'
      }
    ]
  }
])

app.makeSingleInstance(callback)

This method makes your application a Single Instance Application - instead of allowing multiple instances of your app to run, this will ensure that only a single instance of your app is running, and other instances signal this instance and exit.

callback will be called with callback(argv, workingDirectory) when a second instance has been executed. argv is an Array of the second instance’s command line arguments, and workingDirectory is its current working directory. Usually applications respond to this by making their primary window focused and non-minimized.

The callback is guaranteed to be executed after the ready event of app gets emitted.

This method returns false if your process is the primary instance of the application and your app should continue loading. And returns true if your process has sent its parameters to another instance, and you should immediately quit.

On macOS the system enforces single instance automatically when users try to open a second instance of your app in Finder, and the open-file and open-url events will be emitted for that. However when users start your app in command line the system’s single instance mechanism will be bypassed and you have to use this method to ensure single instance.

An example of activating the window of primary instance when a second instance starts:

const {app} = require('electron')
let myWindow = null

const shouldQuit = app.makeSingleInstance((commandLine, workingDirectory) => {
  // Someone tried to run a second instance, we should focus our window.
  if (myWindow) {
    if (myWindow.isMinimized()) myWindow.restore()
    myWindow.focus()
  }
})

if (shouldQuit) {
  app.quit()
}

// Create myWindow, load the rest of the app, etc...
app.on('ready', () => {
})

app.releaseSingleInstance()

Releases all locks that were created by makeSingleInstance. This will allow multiple instances of the application to once again run side by side.

app.setUserActivity(type, userInfo[, webpageURL]) macOS

Creates an NSUserActivity and sets it as the current activity. The activity is eligible for Handoff to another device afterward.

app.getCurrentActivityType() macOS

Returns String - The type of the currently running activity.

app.setAppUserModelId(id) Windows

Changes the Application User Model ID to id.

app.importCertificate(options, callback) LINUX

Imports the certificate in pkcs12 format into the platform certificate store. callback is called with the result of import operation, a value of 0 indicates success while any other value indicates failure according to chromium net_error_list.

app.disableHardwareAcceleration()

Disables hardware acceleration for current app.

This method can only be called before app is ready.

app.setBadgeCount(count) Linux macOS

Returns Boolean - Whether the call succeeded.

Sets the counter badge for current app. Setting the count to 0 will hide the badge.

On macOS it shows on the dock icon. On Linux it only works for Unity launcher,

Note: Unity launcher requires the existence of a .desktop file to work, for more information please read Desktop Environment Integration.

app.getBadgeCount() Linux macOS

Returns Integer - The current value displayed in the counter badge.

app.isUnityRunning() Linux

Returns Boolean - Whether the current desktop environment is Unity launcher.

app.getLoginItemSettings([options]) macOS Windows

If you provided path and args options to app.setLoginItemSettings then you need to pass the same arguments here for openAtLogin to be set correctly.

Returns Object:

Note: This API has no effect on MAS builds.

app.setLoginItemSettings(settings[, path, args]) macOS Windows

Set the app’s login item settings.

To work with Electron’s autoUpdater on Windows, which uses Squirrel, you’ll want to set the launch path to Update.exe, and pass arguments that specify your application name. For example:

const appFolder = path.dirname(process.execPath)
const updateExe = path.resolve(appFolder, '..', 'Update.exe')
const exeName = path.basename(process.execPath)

app.setLoginItemSettings({
  openAtLogin: true,
  path: updateExe,
  args: [
    '--processStart', `"${exeName}"`,
    '--process-start-args', `"--hidden"`
  ]
})

Note: This API has no effect on MAS builds.

app.isAccessibilitySupportEnabled() macOS Windows

Returns Boolean - true if Chrome’s accessibility support is enabled, false otherwise. This API will return true if the use of assistive technologies, such as screen readers, has been detected. See https://www.chromium.org/developers/design-documents/accessibility for more details.

app.setAboutPanelOptions(options) macOS

Set the about panel options. This will override the values defined in the app’s .plist file. See the Apple docs for more details.

app.commandLine.appendSwitch(switch[, value])

Append a switch (with optional value) to Chromium’s command line.

Note: This will not affect process.argv, and is mainly used by developers to control some low-level Chromium behaviors.

app.commandLine.appendArgument(value)

Append an argument to Chromium’s command line. The argument will be quoted correctly.

Note: This will not affect process.argv.

app.dock.bounce([type]) macOS

When critical is passed, the dock icon will bounce until either the application becomes active or the request is canceled.

When informational is passed, the dock icon will bounce for one second. However, the request remains active until either the application becomes active or the request is canceled.

Returns Integer an ID representing the request.

app.dock.cancelBounce(id) macOS

Cancel the bounce of id.

app.dock.downloadFinished(filePath) macOS

Bounces the Downloads stack if the filePath is inside the Downloads folder.

app.dock.setBadge(text) macOS

Sets the string to be displayed in the dock’s badging area.

app.dock.getBadge() macOS

Returns String - The badge string of the dock.

app.dock.hide() macOS

Hides the dock icon.

app.dock.show() macOS

Shows the dock icon.

app.dock.isVisible() macOS

Returns Boolean - Whether the dock icon is visible. The app.dock.show() call is asynchronous so this method might not return true immediately after that call.

app.dock.setMenu(menu) macOS

Sets the application’s dock menu.

app.dock.setIcon(image) macOS

Sets the image associated with this dock icon.


autoUpdater

Enable apps to automatically update themselves.

Process: Main

The autoUpdater module provides an interface for the Squirrel framework.

You can quickly launch a multi-platform release server for distributing your application by using one of these projects:

Platform notices

Though autoUpdater provides a uniform API for different platforms, there are still some subtle differences on each platform.

macOS

On macOS, the autoUpdater module is built upon Squirrel.Mac, meaning you don’t need any special setup to make it work. For server-side requirements, you can read Server Support. Note that App Transport Security (ATS) applies to all requests made as part of the update process. Apps that need to disable ATS can add the NSAllowsArbitraryLoads key to their app’s plist.

Note: Your application must be signed for automatic updates on macOS. This is a requirement of Squirrel.Mac.

Windows

On Windows, you have to install your app into a user’s machine before you can use the autoUpdater, so it is recommended that you use the electron-winstaller, electron-builder or the grunt-electron-installer package to generate a Windows installer.

When using electron-winstaller or electron-builder make sure you do not try to update your app the first time it runs (Also see this issue for more info). It’s also recommended to use electron-squirrel-startup to get desktop shortcuts for your app.

The installer generated with Squirrel will create a shortcut icon with an Application User Model ID in the format of com.squirrel.PACKAGE_ID.YOUR_EXE_WITHOUT_DOT_EXE, examples are com.squirrel.slack.Slack and com.squirrel.code.Code. You have to use the same ID for your app with app.setAppUserModelId API, otherwise Windows will not be able to pin your app properly in task bar.

The server-side setup is also different from macOS. You can read the documents of Squirrel.Windows to get more details.

Linux

There is no built-in support for auto-updater on Linux, so it is recommended to use the distribution’s package manager to update your app.

Events

The autoUpdater object emits the following events:

Event: ‘error’

Returns:

Emitted when there is an error while updating.

Event: ‘checking-for-update’

Emitted when checking if an update has started.

Event: ‘update-available’

Emitted when there is an available update. The update is downloaded automatically.

Event: ‘update-not-available’

Emitted when there is no available update.

Event: ‘update-downloaded’

Returns:

Emitted when an update has been downloaded.

On Windows only releaseName is available.

Methods

The autoUpdater object has the following methods:

autoUpdater.setFeedURL(url[, requestHeaders])

Sets the url and initialize the auto updater.

autoUpdater.getFeedURL()

Returns String - The current update feed URL.

autoUpdater.checkForUpdates()

Asks the server whether there is an update. You must call setFeedURL before using this API.

autoUpdater.quitAndInstall()

Restarts the app and installs the update after it has been downloaded. It should only be called after update-downloaded has been emitted.

Note: autoUpdater.quitAndInstall() will close all application windows first and only emit before-quit event on app after that. This is different from the normal quit event sequence.


Class: BrowserWindowProxy

Manipulate the child browser window

Process: Renderer

The BrowserWindowProxy object is returned from window.open and provides limited functionality with the child window.

Instance Methods

The BrowserWindowProxy object has the following instance methods:

win.blur()

Removes focus from the child window.

win.close()

Forcefully closes the child window without calling its unload event.

win.eval(code)

Evaluates the code in the child window.

win.focus()

Focuses the child window (brings the window to front).

win.print()

Invokes the print dialog on the child window.

win.postMessage(message, targetOrigin)

Sends a message to the child window with the specified origin or * for no origin preference.

In addition to these methods, the child window implements window.opener object with no properties and a single method.

Instance Properties

The BrowserWindowProxy object has the following instance properties:

win.closed

A Boolean that is set to true after the child window gets closed.


BrowserWindow

Create and control browser windows.

Process: Main

// In the main process.
const {BrowserWindow} = require('electron')

// Or use `remote` from the renderer process.
// const {BrowserWindow} = require('electron').remote

let win = new BrowserWindow({width: 800, height: 600})
win.on('closed', () => {
  win = null
})

// Load a remote URL
win.loadURL('https://github.com')

// Or load a local HTML file
win.loadURL(`file://${__dirname}/app/index.html`)

Frameless window

To create a window without chrome, or a transparent window in arbitrary shape, you can use the Frameless Window API.

Showing window gracefully

When loading a page in the window directly, users may see the page load incrementally, which is not a good experience for a native app. To make the window display without visual flash, there are two solutions for different situations.

Using ready-to-show event

While loading the page, the ready-to-show event will be emitted when renderer process has done drawing for the first time, showing window after this event will have no visual flash:

const {BrowserWindow} = require('electron')
let win = new BrowserWindow({show: false})
win.once('ready-to-show', () => {
  win.show()
})

This event is usually emitted after the did-finish-load event, but for pages with many remote resources, it may be emitted before the did-finish-load event.

Setting backgroundColor

For a complex app, the ready-to-show event could be emitted too late, making the app feel slow. In this case, it is recommended to show the window immediately, and use a backgroundColor close to your app’s background:

const {BrowserWindow} = require('electron')

let win = new BrowserWindow({backgroundColor: '#2e2c29'})
win.loadURL('https://github.com')

Note that even for apps that use ready-to-show event, it is still recommended to set backgroundColor to make app feel more native.

Parent and child windows

By using parent option, you can create child windows:

const {BrowserWindow} = require('electron')

let top = new BrowserWindow()
let child = new BrowserWindow({parent: top})
child.show()
top.show()

The child window will always show on top of the top window.

A modal window is a child window that disables parent window, to create a modal window, you have to set both parent and modal options:

const {BrowserWindow} = require('electron')

let child = new BrowserWindow({parent: top, modal: true, show: false})
child.loadURL('https://github.com')
child.once('ready-to-show', () => {
  child.show()
})

Platform notices

Class: BrowserWindow

Create and control browser windows.

Process: Main

BrowserWindow is an EventEmitter.

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

new BrowserWindow([options])

When setting minimum or maximum window size with minWidth/maxWidth/ minHeight/maxHeight, it only constrains the users. It won’t prevent you from passing a size that does not follow size constraints to setBounds/setSize or to the constructor of BrowserWindow.

The possible values and behaviors of the type option are platform dependent. Possible values are:

Instance Events

Objects created with new BrowserWindow emit the following events:

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

Event: ‘page-title-updated’

Returns:

Emitted when the document changed its title, calling event.preventDefault() will prevent the native window’s title from changing.

Event: ‘close’

Returns:

Emitted when the window is going to be closed. It’s emitted before the beforeunload and unload event of the DOM. Calling event.preventDefault() will cancel the close.

Usually you would want to use the beforeunload handler to decide whether the window should be closed, which will also be called when the window is reloaded. In Electron, returning any value other than undefined would cancel the close. For example:

window.onbeforeunload = (e) => {
  console.log('I do not want to be closed')

  // Unlike usual browsers that a message box will be prompted to users, returning
  // a non-void value will silently cancel the close.
  // It is recommended to use the dialog API to let the user confirm closing the
  // application.
  e.returnValue = false
}

Event: ‘closed’

Emitted when the window is closed. After you have received this event you should remove the reference to the window and avoid using it any more.

Event: ‘unresponsive’

Emitted when the web page becomes unresponsive.

Event: ‘responsive’

Emitted when the unresponsive web page becomes responsive again.

Event: ‘blur’

Emitted when the window loses focus.

Event: ‘focus’

Emitted when the window gains focus.

Event: ‘show’

Emitted when the window is shown.

Event: ‘hide’

Emitted when the window is hidden.

Event: ‘ready-to-show’

Emitted when the web page has been rendered and window can be displayed without a visual flash.

Event: ‘maximize’

Emitted when window is maximized.

Event: ‘unmaximize’

Emitted when the window exits from a maximized state.

Event: ‘minimize’

Emitted when the window is minimized.

Event: ‘restore’

Emitted when the window is restored from a minimized state.

Event: ‘resize’

Emitted when the window is being resized.

Event: ‘move’

Emitted when the window is being moved to a new position.

Note: On macOS this event is just an alias of moved.

Event: ‘moved’ macOS

Emitted once when the window is moved to a new position.

Event: ‘enter-full-screen’

Emitted when the window enters a full-screen state.

Event: ‘leave-full-screen’

Emitted when the window leaves a full-screen state.

Event: ‘enter-html-full-screen’

Emitted when the window enters a full-screen state triggered by HTML API.

Event: ‘leave-html-full-screen’

Emitted when the window leaves a full-screen state triggered by HTML API.

Event: ‘app-command’ Windows

Returns:

Emitted when an App Command is invoked. These are typically related to keyboard media keys or browser commands, as well as the “Back” button built into some mice on Windows.

Commands are lowercased, underscores are replaced with hyphens, and the APPCOMMAND_ prefix is stripped off. e.g. APPCOMMAND_BROWSER_BACKWARD is emitted as browser-backward.

const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.on('app-command', (e, cmd) => {
  // Navigate the window back when the user hits their mouse back button
  if (cmd === 'browser-backward' && win.webContents.canGoBack()) {
    win.webContents.goBack()
  }
})

Event: ‘scroll-touch-begin’ macOS

Emitted when scroll wheel event phase has begun.

Event: ‘scroll-touch-end’ macOS

Emitted when scroll wheel event phase has ended.

Event: ‘scroll-touch-edge’ macOS

Emitted when scroll wheel event phase filed upon reaching the edge of element.

Event: ‘swipe’ macOS

Returns:

Emitted on 3-finger swipe. Possible directions are up, right, down, left.

Static Methods

The BrowserWindow class has the following static methods:

BrowserWindow.getAllWindows()

Returns BrowserWindow[] - An array of all opened browser windows.

BrowserWindow.getFocusedWindow()

Returns BrowserWindow - The window that is focused in this application, otherwise returns null.

BrowserWindow.fromWebContents(webContents)

Returns BrowserWindow - The window that owns the given webContents.

BrowserWindow.fromId(id)

Returns BrowserWindow - The window with the given id.

BrowserWindow.addDevToolsExtension(path)

Adds DevTools extension located at path, and returns extension’s name.

The extension will be remembered so you only need to call this API once, this API is not for programming use. If you try to add an extension that has already been loaded, this method will not return and instead log a warning to the console.

The method will also not return if the extension’s manifest is missing or incomplete.

Note: This API cannot be called before the ready event of the app module is emitted.

BrowserWindow.removeDevToolsExtension(name)

Remove a DevTools extension by name.

Note: This API cannot be called before the ready event of the app module is emitted.

BrowserWindow.getDevToolsExtensions()

Returns Object - The keys are the extension names and each value is an Object containing name and version properties.

To check if a DevTools extension is installed you can run the following:

const {BrowserWindow} = require('electron')

let installed = BrowserWindow.getDevToolsExtensions().hasOwnProperty('devtron')
console.log(installed)

Note: This API cannot be called before the ready event of the app module is emitted.

Instance Properties

Objects created with new BrowserWindow have the following properties:

const {BrowserWindow} = require('electron')
// In this example `win` is our instance
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('https://github.com')

win.webContents

A WebContents object this window owns. All web page related events and operations will be done via it.

See the webContents documentation for its methods and events.

win.id

A Integer representing the unique ID of the window.

Instance Methods

Objects created with new BrowserWindow have the following instance methods:

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

win.destroy()

Force closing the window, the unload and beforeunload event won’t be emitted for the web page, and close event will also not be emitted for this window, but it guarantees the closed event will be emitted.

win.close()

Try to close the window. This has the same effect as a user manually clicking the close button of the window. The web page may cancel the close though. See the close event.

win.focus()

Focuses on the window.

win.blur()

Removes focus from the window.

win.isFocused()

Returns Boolean - Whether the window is focused.

win.isDestroyed()

Returns Boolean - Whether the window is destroyed.

win.show()

Shows and gives focus to the window.

win.showInactive()

Shows the window but doesn’t focus on it.

win.hide()

Hides the window.

win.isVisible()

Returns Boolean - Whether the window is visible to the user.

win.isModal()

Returns Boolean - Whether current window is a modal window.

win.maximize()

Maximizes the window.

win.unmaximize()

Unmaximizes the window.

win.isMaximized()

Returns Boolean - Whether the window is maximized.

win.minimize()

Minimizes the window. On some platforms the minimized window will be shown in the Dock.

win.restore()

Restores the window from minimized state to its previous state.

win.isMinimized()

Returns Boolean - Whether the window is minimized.

win.setFullScreen(flag)

Sets whether the window should be in fullscreen mode.

win.isFullScreen()

Returns Boolean - Whether the window is in fullscreen mode.

win.setAspectRatio(aspectRatio[, extraSize]) macOS

This will make a window maintain an aspect ratio. The extra size allows a developer to have space, specified in pixels, not included within the aspect ratio calculations. This API already takes into account the difference between a window’s size and its content size.

Consider a normal window with an HD video player and associated controls. Perhaps there are 15 pixels of controls on the left edge, 25 pixels of controls on the right edge and 50 pixels of controls below the player. In order to maintain a 16:9 aspect ratio (standard aspect ratio for HD @1920x1080) within the player itself we would call this function with arguments of 16/9 and [ 40, 50 ]. The second argument doesn’t care where the extra width and height are within the content view–only that they exist. Just sum any extra width and height areas you have within the overall content view.

win.previewFile(path[, displayName]) macOS

Uses Quick Look to preview a file at a given path.

win.closeFilePreview() macOS

Closes the currently open Quick Look panel.

win.setBounds(bounds[, animate])

Resizes and moves the window to the supplied bounds

win.getBounds()

Returns Rectangle

win.setContentBounds(bounds[, animate])

Resizes and moves the window’s client area (e.g. the web page) to the supplied bounds.

win.getContentBounds()

Returns Rectangle

win.setSize(width, height[, animate])

Resizes the window to width and height.

win.getSize()

Returns Integer[] - Contains the window’s width and height.

win.setContentSize(width, height[, animate])

Resizes the window’s client area (e.g. the web page) to width and height.

win.getContentSize()

Returns Integer[] - Contains the window’s client area’s width and height.

win.setMinimumSize(width, height)

Sets the minimum size of window to width and height.

win.getMinimumSize()

Returns Integer[] - Contains the window’s minimum width and height.

win.setMaximumSize(width, height)

Sets the maximum size of window to width and height.

win.getMaximumSize()

Returns Integer[] - Contains the window’s maximum width and height.

win.setResizable(resizable)

Sets whether the window can be manually resized by user.

win.isResizable()

Returns Boolean - Whether the window can be manually resized by user.

win.setMovable(movable) macOS Windows

Sets whether the window can be moved by user. On Linux does nothing.

win.isMovable() macOS Windows

Returns Boolean - Whether the window can be moved by user.

On Linux always returns true.

win.setMinimizable(minimizable) macOS Windows

Sets whether the window can be manually minimized by user. On Linux does nothing.

win.isMinimizable() macOS Windows

Returns Boolean - Whether the window can be manually minimized by user

On Linux always returns true.

win.setMaximizable(maximizable) macOS Windows

Sets whether the window can be manually maximized by user. On Linux does nothing.

win.isMaximizable() macOS Windows

Returns Boolean - Whether the window can be manually maximized by user.

On Linux always returns true.

win.setFullScreenable(fullscreenable)

Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.

win.isFullScreenable()

Returns Boolean - Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window.

win.setClosable(closable) macOS Windows

Sets whether the window can be manually closed by user. On Linux does nothing.

win.isClosable() macOS Windows

Returns Boolean - Whether the window can be manually closed by user.

On Linux always returns true.

win.setAlwaysOnTop(flag[, level][, relativeLevel])

Sets whether the window should show always on top of other windows. After setting this, the window is still a normal window, not a toolbox window which can not be focused on.

win.isAlwaysOnTop()

Returns Boolean - Whether the window is always on top of other windows.

win.center()

Moves window to the center of the screen.

win.setPosition(x, y[, animate])

Moves window to x and y.

win.getPosition()

Returns Integer[] - Contains the window’s current position.

win.setTitle(title)

Changes the title of native window to title.

win.getTitle()

Returns String - The title of the native window.

Note: The title of web page can be different from the title of the native window.

win.setSheetOffset(offsetY[, offsetX]) macOS

Changes the attachment point for sheets on macOS. By default, sheets are attached just below the window frame, but you may want to display them beneath a HTML-rendered toolbar. For example:

const {BrowserWindow} = require('electron')
let win = new BrowserWindow()

let toolbarRect = document.getElementById('toolbar').getBoundingClientRect()
win.setSheetOffset(toolbarRect.height)

win.flashFrame(flag)

Starts or stops flashing the window to attract user’s attention.

win.setSkipTaskbar(skip)

Makes the window not show in the taskbar.

win.setKiosk(flag)

Enters or leaves the kiosk mode.

win.isKiosk()

Returns Boolean - Whether the window is in kiosk mode.

win.getNativeWindowHandle()

Returns Buffer - The platform-specific handle of the window.

The native type of the handle is HWND on Windows, NSView* on macOS, and Window (unsigned long) on Linux.

win.hookWindowMessage(message, callback) Windows

Hooks a windows message. The callback is called when the message is received in the WndProc.

win.isWindowMessageHooked(message) Windows

Returns Boolean - true or false depending on whether the message is hooked.

win.unhookWindowMessage(message) Windows

Unhook the window message.

win.unhookAllWindowMessages() Windows

Unhooks all of the window messages.

win.setRepresentedFilename(filename) macOS

Sets the pathname of the file the window represents, and the icon of the file will show in window’s title bar.

win.getRepresentedFilename() macOS

Returns String - The pathname of the file the window represents.

win.setDocumentEdited(edited) macOS

Specifies whether the window’s document has been edited, and the icon in title bar will become gray when set to true.

win.isDocumentEdited() macOS

Returns Boolean - Whether the window’s document has been edited.

win.focusOnWebView()

win.blurWebView()

win.capturePage([rect, ]callback)

Same as webContents.capturePage([rect, ]callback).

win.loadURL(url[, options])

Same as webContents.loadURL(url[, options]).

The url can be a remote address (e.g. http://) or a path to a local HTML file using the file:// protocol.

To ensure that file URLs are properly formatted, it is recommended to use Node’s url.format method:

let url = require('url').format({
  protocol: 'file',
  slashes: true,
  pathname: require('path').join(__dirname, 'index.html')
})

win.loadURL(url)

You can load a URL using a POST request with URL-encoded data by doing the following:

win.loadURL('http://localhost:8000/post', {
  postData: [{
    type: 'rawData',
    bytes: Buffer.from('hello=world')
  }],
  extraHeaders: 'Content-Type: application/x-www-form-urlencoded'
})

win.reload()

Same as webContents.reload.

win.setMenu(menu) Linux Windows

Sets the menu as the window’s menu bar, setting it to null will remove the menu bar.

win.setProgressBar(progress[, options])

Sets progress value in progress bar. Valid range is [0, 1.0].

Remove progress bar when progress < 0; Change to indeterminate mode when progress > 1.

On Linux platform, only supports Unity desktop environment, you need to specify the *.desktop file name to desktopName field in package.json. By default, it will assume app.getName().desktop.

On Windows, a mode can be passed. Accepted values are none, normal, indeterminate, error, and paused. If you call setProgressBar without a mode set (but with a value within the valid range), normal will be assumed.

win.setOverlayIcon(overlay, description) Windows

Sets a 16 x 16 pixel overlay onto the current taskbar icon, usually used to convey some sort of application status or to passively notify the user.

win.setHasShadow(hasShadow) macOS

Sets whether the window should have a shadow. On Windows and Linux does nothing.

win.hasShadow() macOS

Returns Boolean - Whether the window has a shadow.

On Windows and Linux always returns true.

win.setThumbarButtons(buttons) Windows

Returns Boolean - Whether the buttons were added successfully

Add a thumbnail toolbar with a specified set of buttons to the thumbnail image of a window in a taskbar button layout. Returns a Boolean object indicates whether the thumbnail has been added successfully.

The number of buttons in thumbnail toolbar should be no greater than 7 due to the limited room. Once you setup the thumbnail toolbar, the toolbar cannot be removed due to the platform’s limitation. But you can call the API with an empty array to clean the buttons.

The buttons is an array of Button objects:

The flags is an array that can include following Strings:

win.setThumbnailClip(region) Windows

Sets the region of the window to show as the thumbnail image displayed when hovering over the window in the taskbar. You can reset the thumbnail to be the entire window by specifying an empty region: {x: 0, y: 0, width: 0, height: 0}.

win.setThumbnailToolTip(toolTip) Windows

Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar.

win.setAppDetails(options) Windows

Sets the properties for the window’s taskbar button.

Note: relaunchCommand and relaunchDisplayName must always be set together. If one of those properties is not set, then neither will be used.

win.showDefinitionForSelection() macOS

Same as webContents.showDefinitionForSelection().

win.setIcon(icon) Windows Linux

Changes window icon.

win.setAutoHideMenuBar(hide)

Sets whether the window menu bar should hide itself automatically. Once set the menu bar will only show when users press the single Alt key.

If the menu bar is already visible, calling setAutoHideMenuBar(true) won’t hide it immediately.

win.isMenuBarAutoHide()

Returns Boolean - Whether menu bar automatically hides itself.

win.setMenuBarVisibility(visible) Windows Linux

Sets whether the menu bar should be visible. If the menu bar is auto-hide, users can still bring up the menu bar by pressing the single Alt key.

win.isMenuBarVisible()

Returns Boolean - Whether the menu bar is visible.

win.setVisibleOnAllWorkspaces(visible)

Sets whether the window should be visible on all workspaces.

Note: This API does nothing on Windows.

win.isVisibleOnAllWorkspaces()

Returns Boolean - Whether the window is visible on all workspaces.

Note: This API always returns false on Windows.

win.setIgnoreMouseEvents(ignore)

Makes the window ignore all mouse events.

All mouse events happened in this window will be passed to the window below this window, but if this window has focus, it will still receive keyboard events.

win.setContentProtection(enable) macOS Windows

Prevents the window contents from being captured by other apps.

On macOS it sets the NSWindow’s sharingType to NSWindowSharingNone. On Windows it calls SetWindowDisplayAffinity with WDA_MONITOR.

win.setFocusable(focusable) Windows

Changes whether the window can be focused.

win.setParentWindow(parent) Linux macOS

Sets parent as current window’s parent window, passing null will turn current window into a top-level window.

win.getParentWindow()

Returns BrowserWindow - The parent window.

win.getChildWindows()

Returns BrowserWindow[] - All child windows.

win.setAutoHideCursor(autoHide) macOS

Controls whether to hide cursor when typing.

win.setVibrancy(type) macOS

Adds a vibrancy effect to the browser window. Passing null or an empty string will remove the vibrancy effect on the window.


Supported Chrome Command Line Switches

Command line switches supported by Electron.

You can use app.commandLine.appendSwitch to append them in your app’s main script before the ready event of the app module is emitted:

const {app} = require('electron')
app.commandLine.appendSwitch('remote-debugging-port', '8315')
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1')

app.on('ready', () => {
  // Your code here
})

–ignore-connections-limit=domains

Ignore the connections limit for domains list separated by ,.

–disable-http-cache

Disables the disk cache for HTTP requests.

–disable-http2

Disable HTTP/2 and SPDY/3.1 protocols.

–debug=port and –debug-brk=port

Debug-related flags, see the Debugging the Main Process guide for details.

–remote-debugging-port=port

Enables remote debugging over HTTP on the specified port.

–js-flags=flags

Specifies the flags passed to the Node JS engine. It has to be passed when starting Electron if you want to enable the flags in the main process.

$ electron --js-flags="--harmony_proxies --harmony_collections" your-app

See the Node documentation or run node --help in your terminal for a list of available flags. Additionally, run node --v8-options to see a list of flags that specifically refer to Node’s V8 JavaScript engine.

–proxy-server=address:port

Use a specified proxy server, which overrides the system setting. This switch only affects requests with HTTP protocol, including HTTPS and WebSocket requests. It is also noteworthy that not all proxy servers support HTTPS and WebSocket requests.

–proxy-bypass-list=hosts

Instructs Electron to bypass the proxy server for the given semi-colon-separated list of hosts. This flag has an effect only if used in tandem with --proxy-server.

For example:

const {app} = require('electron')
app.commandLine.appendSwitch('proxy-bypass-list', '<local>;*.google.com;*foo.com;1.2.3.4:5678')

Will use the proxy server for all hosts except for local addresses (localhost, 127.0.0.1 etc.), google.com subdomains, hosts that contain the suffix foo.com and anything at 1.2.3.4:5678.

–proxy-pac-url=url

Uses the PAC script at the specified url.

–no-proxy-server

Don’t use a proxy server and always make direct connections. Overrides any other proxy server flags that are passed.

–host-rules=rules

A comma-separated list of rules that control how hostnames are mapped.

For example:

These mappings apply to the endpoint host in a net request (the TCP connect and host resolver in a direct connection, and the CONNECT in an HTTP proxy connection, and the endpoint host in a SOCKS proxy connection).

–host-resolver-rules=rules

Like --host-rules but these rules only apply to the host resolver.

–auth-server-whitelist=url

A comma-separated list of servers for which integrated authentication is enabled.

For example:

--auth-server-whitelist='*example.com, *foobar.com, *baz'

then any url ending with example.com, foobar.com, baz will be considered for integrated authentication. Without * prefix the url has to match exactly.

–auth-negotiate-delegate-whitelist=url

A comma-separated list of servers for which delegation of user credentials is required. Without * prefix the url has to match exactly.

–ignore-certificate-errors

Ignores certificate related errors.

–ppapi-flash-path=path

Sets the path of the pepper flash plugin.

–ppapi-flash-version=version

Sets the version of the pepper flash plugin.

–log-net-log=path

Enables net log events to be saved and writes them to path.

–disable-renderer-backgrounding

Prevents Chromium from lowering the priority of invisible pages’ renderer processes.

This flag is global to all renderer processes, if you only want to disable throttling in one window, you can take the hack of playing silent audio.

–enable-logging

Prints Chromium’s logging into console.

This switch can not be used in app.commandLine.appendSwitch since it is parsed earlier than user’s app is loaded, but you can set the ELECTRON_ENABLE_LOGGING environment variable to achieve the same effect.

–v=log_level

Gives the default maximal active V-logging level; 0 is the default. Normally positive values are used for V-logging levels.

This switch only works when --enable-logging is also passed.

–vmodule=pattern

Gives the per-module maximal V-logging levels to override the value given by --v. E.g. my_module=2,foo*=3 would change the logging level for all code in source files my_module.* and foo*.*.

Any pattern containing a forward or backward slash will be tested against the whole pathname and not just the module. E.g. */foo/bar/*=2 would change the logging level for all code in the source files under a foo/bar directory.

This switch only works when --enable-logging is also passed.


Class: ClientRequest

Make HTTP/HTTPS requests.

Process: Main

ClientRequest implements the Writable Stream interface and is therefore an EventEmitter.

new ClientRequest(options)

options properties such as protocol, host, hostname, port and path strictly follow the Node.js model as described in the URL module.

For instance, we could have created the same request to ‘github.com’ as follows:

const request = net.request({
  method: 'GET',
  protocol: 'https:',
  hostname: 'github.com',
  port: 443,
  path: '/'
})

Instance Events

Event: ‘response’

Returns:

Event: ‘login’

Returns:

Emitted when an authenticating proxy is asking for user credentials.

The callback function is expected to be called back with user credentials:

request.on('login', (authInfo, callback) => {
  callback('username', 'password')
})

Providing empty credentials will cancel the request and report an authentication error on the response object:

request.on('response', (response) => {
  console.log(`STATUS: ${response.statusCode}`);
  response.on('error', (error) => {
    console.log(`ERROR: ${JSON.stringify(error)}`)
  })
})
request.on('login', (authInfo, callback) => {
  callback()
})

Event: ‘finish’

Emitted just after the last chunk of the request’s data has been written into the request object.

Event: ‘abort’

Emitted when the request is aborted. The abort event will not be fired if the request is already closed.

Event: ‘error’

Returns:

Emitted when the net module fails to issue a network request. Typically when the request object emits an error event, a close event will subsequently follow and no response object will be provided.

Event: ‘close’

Emitted as the last event in the HTTP request-response transaction. The close event indicates that no more events will be emitted on either the request or response objects.

Instance Properties

request.chunkedEncoding

A Boolean specifying whether the request will use HTTP chunked transfer encoding or not. Defaults to false. The property is readable and writable, however it can be set only before the first write operation as the HTTP headers are not yet put on the wire. Trying to set the chunkedEncoding property after the first write will throw an error.

Using chunked encoding is strongly recommended if you need to send a large request body as data will be streamed in small chunks instead of being internally buffered inside Electron process memory.

Instance Methods

request.setHeader(name, value)

Adds an extra HTTP header. The header name will issued as it is without lowercasing. It can be called only before first write. Calling this method after the first write will throw an error.

request.getHeader(name)

Returns String - The value of a previously set extra header name.

request.removeHeader(name)

Removes a previously set extra header name. This method can be called only before first write. Trying to call it after the first write will throw an error.

request.write(chunk[, encoding][, callback])

callback is essentially a dummy function introduced in the purpose of keeping similarity with the Node.js API. It is called asynchronously in the next tick after chunk content have been delivered to the Chromium networking layer. Contrary to the Node.js implementation, it is not guaranteed that chunk content have been flushed on the wire before callback is called.

Adds a chunk of data to the request body. The first write operation may cause the request headers to be issued on the wire. After the first write operation, it is not allowed to add or remove a custom header.

request.end([chunk][, encoding][, callback])

Sends the last chunk of the request data. Subsequent write or end operations will not be allowed. The finish event is emitted just after the end operation.

request.abort()

Cancels an ongoing HTTP transaction. If the request has already emitted the close event, the abort operation will have no effect. Otherwise an ongoing event will emit abort and close events. Additionally, if there is an ongoing response object,it will emit the aborted event.


clipboard

Perform copy and paste operations on the system clipboard.

Process: Main, Renderer

The following example shows how to write a string to the clipboard:

const {clipboard} = require('electron')
clipboard.writeText('Example String')

On X Window systems, there is also a selection clipboard. To manipulate it you need to pass selection to each method:

const {clipboard} = require('electron')
clipboard.writeText('Example String', 'selection')
console.log(clipboard.readText('selection'))

Methods

The clipboard module has the following methods:

Note: Experimental APIs are marked as such and could be removed in future.

clipboard.readText([type])

Returns String - The content in the clipboard as plain text.

clipboard.writeText(text[, type])

Writes the text into the clipboard as plain text.

clipboard.readHTML([type])

Returns String - The content in the clipboard as markup.

clipboard.writeHTML(markup[, type])

Writes markup to the clipboard.

clipboard.readImage([type])

Returns NativeImage - The image content in the clipboard.

clipboard.writeImage(image[, type])

Writes image to the clipboard.

clipboard.readRTF([type])

Returns String - The content in the clipboard as RTF.

clipboard.writeRTF(text[, type])

Writes the text into the clipboard in RTF.

clipboard.readBookmark() macOS Windows

Returns Object:

Returns an Object containing title and url keys representing the bookmark in the clipboard. The title and url values will be empty strings when the bookmark is unavailable.

clipboard.writeBookmark(title, url[, type]) macOS Windows

Writes the title and url into the clipboard as a bookmark.

Note: Most apps on Windows don’t support pasting bookmarks into them so you can use clipboard.write to write both a bookmark and fallback text to the clipboard.

clipboard.write({
  text: 'http://electron.atom.io',
  bookmark: 'Electron Homepage'
})

clipboard.readFindText() macOS

Returns String - The text on the find pasteboard. This method uses synchronous IPC when called from the renderer process. The cached value is reread from the find pasteboard whenever the application is activated.

clipboard.writeFindText(text) macOS

Writes the text into the find pasteboard as plain text. This method uses synchronous IPC when called from the renderer process.

clipboard.clear([type])

Clears the clipboard content.

clipboard.availableFormats([type])

Returns String[] - An array of supported formats for the clipboard type.

clipboard.has(data[, type]) Experimental

Returns Boolean - Whether the clipboard supports the format of specified data.

const {clipboard} = require('electron')
console.log(clipboard.has('<p>selection</p>'))

clipboard.read(data[, type]) Experimental

Returns String - Reads data from the clipboard.

clipboard.write(data[, type])

const {clipboard} = require('electron')
clipboard.write({text: 'test', html: '<b>test</b>'})

Writes data to the clipboard.


contentTracing

Collect tracing data from Chromium’s content module for finding performance bottlenecks and slow operations.

Process: Main

This module does not include a web interface so you need to open chrome://tracing/ in a Chrome browser and load the generated file to view the result.

Note: You should not use this module until the ready event of the app module is emitted.

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

app.on('ready', () => {
  const options = {
    categoryFilter: '*',
    traceOptions: 'record-until-full,enable-sampling'
  }

  contentTracing.startRecording(options, () => {
    console.log('Tracing started')

    setTimeout(() => {
      contentTracing.stopRecording('', (path) => {
        console.log('Tracing data recorded to ' + path)
      })
    }, 5000)
  })
})

Methods

The contentTracing module has the following methods:

contentTracing.getCategories(callback)

Get a set of category groups. The category groups can change as new code paths are reached.

Once all child processes have acknowledged the getCategories request the callback is invoked with an array of category groups.

contentTracing.startRecording(options, callback)

Start recording on all processes.

Recording begins immediately locally and asynchronously on child processes as soon as they receive the EnableRecording request. The callback will be called once all child processes have acknowledged the startRecording request.

categoryFilter is a filter to control what category groups should be traced. A filter can have an optional - prefix to exclude category groups that contain a matching category. Having both included and excluded category patterns in the same list is not supported.

Examples:

traceOptions controls what kind of tracing is enabled, it is a comma-delimited list. Possible options are:

The first 3 options are trace recording modes and hence mutually exclusive. If more than one trace recording modes appear in the traceOptions string, the last one takes precedence. If none of the trace recording modes are specified, recording mode is record-until-full.

The trace option will first be reset to the default option (record_mode set to record-until-full, enable_sampling and enable_systrace set to false) before options parsed from traceOptions are applied on it.

contentTracing.stopRecording(resultFilePath, callback)

Stop recording on all processes.

Child processes typically cache trace data and only rarely flush and send trace data back to the main process. This helps to minimize the runtime overhead of tracing since sending trace data over IPC can be an expensive operation. So, to end tracing, we must asynchronously ask all child processes to flush any pending trace data.

Once all child processes have acknowledged the stopRecording request, callback will be called with a file that contains the traced data.

Trace data will be written into resultFilePath if it is not empty or into a temporary file. The actual file path will be passed to callback if it’s not null.

contentTracing.startMonitoring(options, callback)

Start monitoring on all processes.

Monitoring begins immediately locally and asynchronously on child processes as soon as they receive the startMonitoring request.

Once all child processes have acknowledged the startMonitoring request the callback will be called.

contentTracing.stopMonitoring(callback)

Stop monitoring on all processes.

Once all child processes have acknowledged the stopMonitoring request the callback is called.

contentTracing.captureMonitoringSnapshot(resultFilePath, callback)

Get the current monitoring traced data.

Child processes typically cache trace data and only rarely flush and send trace data back to the main process. This is because it may be an expensive operation to send the trace data over IPC and we would like to avoid unneeded runtime overhead from tracing. So, to end tracing, we must asynchronously ask all child processes to flush any pending trace data.

Once all child processes have acknowledged the captureMonitoringSnapshot request the callback will be called with a file that contains the traced data.

contentTracing.getTraceBufferUsage(callback)

Get the maximum usage across processes of trace buffer as a percentage of the full state. When the TraceBufferUsage value is determined the callback is called.


Class: Cookies

Query and modify a session’s cookies.

Process: Main

Instances of the Cookies class are accessed by using cookies property of a Session.

For example:

const {session} = require('electron')

// Query all cookies.
session.defaultSession.cookies.get({}, (error, cookies) => {
  console.log(error, cookies)
})

// Query all cookies associated with a specific url.
session.defaultSession.cookies.get({url: 'http://www.github.com'}, (error, cookies) => {
  console.log(error, cookies)
})

// Set a cookie with the given cookie data;
// may overwrite equivalent cookies if they exist.
const cookie = {url: 'http://www.github.com', name: 'dummy_name', value: 'dummy'}
session.defaultSession.cookies.set(cookie, (error) => {
  if (error) console.error(error)
})

Instance Events

The following events are available on instances of Cookies:

Event: ‘changed’

Emitted when a cookie is changed because it was added, edited, removed, or expired.

Instance Methods

The following methods are available on instances of Cookies:

cookies.get(filter, callback)

Sends a request to get all cookies matching details, callback will be called with callback(error, cookies) on complete.

cookies is an Array of cookie objects.

cookies.set(details, callback)

Sets a cookie with details, callback will be called with callback(error) on complete.

cookies.remove(url, name, callback)

Removes the cookies matching url and name, callback will called with callback() on complete.


crashReporter

Submit crash reports to a remote server.

Process: Main, Renderer

The following is an example of automatically submitting a crash report to a remote server:

const {crashReporter} = require('electron')

crashReporter.start({
  productName: 'YourName',
  companyName: 'YourCompany',
  submitURL: 'https://your-domain.com/url-to-submit',
  uploadToServer: true
})

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

Crash reports are saved locally in an application-specific temp directory folder. For a productName of YourName, crash reports will be stored in a folder named YourName Crashes inside the temp directory. You can customize this temp directory location for your app by calling the app.setPath('temp', '/my/custom/temp') API before starting the crash reporter.

Methods

The crashReporter module has the following methods:

crashReporter.start(options)

You are required to call this method before using any other crashReporter APIs and in each process (main/renderer) from which you want to collect crash reports. You can pass different options to crashReporter.start when calling from different processes.

Note Child processes created via the child_process module will not have access to the Electron modules. Therefore, to collect crash reports from them, use process.crashReporter.start instead. Pass the same options as above along with an additional one called crashesDirectory that should point to a directory to store the crash reports temporarily. You can test this out by calling process.crash() to crash the child process.

Note: To collect crash reports from child process in Windows, you need to add this extra code as well. This will start the process that will monitor and send the crash reports. Replace submitURL, productName and crashesDirectory with appropriate values.

Note: If you need send additional/updated extra parameters after your first call start you can call setExtraParameter on macOS or call start again with the new/updated extra parameters on Linux and Windows.

const args = [
   `--reporter-url=${submitURL}`,
   `--application-name=${productName}`,
   `--crashes-directory=${crashesDirectory}`
 ]
 const env = {
   ELECTRON_INTERNAL_CRASH_SERVICE: 1
 }
 spawn(process.execPath, args, {
   env: env,
   detached: true
 })

Note: On macOS, Electron uses a new crashpad client for crash collection and reporting. If you want to enable crash reporting, initializing crashpad from the main process using crashReporter.start is required regardless of which process you want to collect crashes from. Once initialized this way, the crashpad handler collects crashes from all processes. You still have to call crashReporter.start from the renderer or child process, otherwise crashes from them will get reported without companyName, productName or any of the extra information.

crashReporter.getLastCrashReport()

Returns CrashReport:

Returns the date and ID of the last crash report. If no crash reports have been sent or the crash reporter has not been started, null is returned.

crashReporter.getUploadedReports()

Returns CrashReport[]:

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

crashReporter.getUploadToServer() macOS

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

Note: This API can only be called from the main process.

crashReporter.setUploadToServer(uploadToServer) macOS

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

Note: This API can only be called from the main process.

crashReporter.setExtraParameter(key, value) macOS

Set an extra parameter to set 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. This API is only available on macOS, if you need to add/update extra parameters on Linux and Windows after your first call to start you can call start again with the updated extra options.

Crash Report Payload

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


Class: Debugger

An alternate transport for Chrome’s remote debugging protocol.

Process: Main

Chrome Developer Tools has a special binding available at JavaScript runtime that allows interacting with pages and instrumenting them.

const {BrowserWindow} = require('electron')
let win = new BrowserWindow()

try {
  win.webContents.debugger.attach('1.1')
} catch (err) {
  console.log('Debugger attach failed : ', err)
}

win.webContents.debugger.on('detach', (event, reason) => {
  console.log('Debugger detached due to : ', reason)
})

win.webContents.debugger.on('message', (event, method, params) => {
  if (method === 'Network.requestWillBeSent') {
    if (params.request.url === 'https://www.github.com') {
      win.webContents.debugger.detach()
    }
  }
})

win.webContents.debugger.sendCommand('Network.enable')

Instance Methods

debugger.attach([protocolVersion])

Attaches the debugger to the webContents.

debugger.isAttached()

Returns Boolean - Whether a debugger is attached to the webContents.

debugger.detach()

Detaches the debugger from the webContents.

debugger.sendCommand(method[, commandParams, callback])

Send given command to the debugging target.

Instance Events

Event: ‘detach’

Emitted when debugging session is terminated. This happens either when webContents is closed or devtools is invoked for the attached webContents.

Event: ‘message’

Emitted whenever debugging target issues instrumentation event.


desktopCapturer

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

Process: Renderer

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

// In the renderer process.
const {desktopCapturer} = require('electron')

desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
  if (error) throw error
  for (let i = 0; i < sources.length; ++i) {
    if (sources[i].name === 'Electron') {
      navigator.webkitGetUserMedia({
        audio: false,
        video: {
          mandatory: {
            chromeMediaSource: 'desktop',
            chromeMediaSourceId: sources[i].id,
            minWidth: 1280,
            maxWidth: 1280,
            minHeight: 720,
            maxHeight: 720
          }
        }
      }, handleStream, handleError)
      return
    }
  }
})

function handleStream (stream) {
  document.querySelector('video').src = URL.createObjectURL(stream)
}

function handleError (e) {
  console.log(e)
}

To capture video from a source provided by desktopCapturer the constraints passed to navigator.webkitGetUserMedia must include chromeMediaSource: 'desktop', and audio: false.

To capture both audio and video from the entire desktop the constraints passed to navigator.webkitGetUserMedia must include chromeMediaSource: 'screen', and audio: true, but should not include a chromeMediaSourceId constraint.

Methods

The desktopCapturer module has the following methods:

desktopCapturer.getSources(options, callback)

Starts gathering information about all available desktop media sources, and calls callback(error, sources) when finished.

sources is an array of DesktopCapturerSource objects, each DesktopCapturerSource represents a screen or an individual window that can be captured.


dialog

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

Process: Main

An example of showing a dialog to select multiple files and directories:

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

The Dialog is opened from Electron’s main thread. If you want to use the dialog object from a renderer process, remember to access it using the remote:

const {dialog} = require('electron').remote
console.log(dialog)

Methods

The dialog module has the following methods:

dialog.showOpenDialog([browserWindow, ]options[, callback])

Returns String[], an array of file paths chosen by the user, if the callback is provided 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).

If a callback is passed, the API call will be asynchronous and the result will be passed via callback(filenames)

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.showSaveDialog([browserWindow, ]options[, callback])

Returns String, the path of the file chosen by the user, if a callback is provided 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, see dialog.showOpenDialog for an example.

If a callback is passed, the API call will be asynchronous and the result will be passed via callback(filename)

dialog.showMessageBox([browserWindow, ]options[, callback])

Returns Integer, the index of the clicked button, if a callback is provided it returns undefined.

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 a callback is passed, the API call will be asynchronous and the result will be passed via callback(response).

dialog.showErrorBox(title, content)

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.

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.


Class: DownloadItem

Control file downloads from remote sources.

Process: Main

DownloadItem is an EventEmitter that represents a download item in Electron. It is used in will-download event of Session class, and allows users to control the download item.

// In the main process.
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.webContents.session.on('will-download', (event, item, webContents) => {
  // Set the save path, making Electron not to prompt a save dialog.
  item.setSavePath('/tmp/save.pdf')

  item.on('updated', (event, state) => {
    if (state === 'interrupted') {
      console.log('Download is interrupted but can be resumed')
    } else if (state === 'progressing') {
      if (item.isPaused()) {
        console.log('Download is paused')
      } else {
        console.log(`Received bytes: ${item.getReceivedBytes()}`)
      }
    }
  })
  item.once('done', (event, state) => {
    if (state === 'completed') {
      console.log('Download successfully')
    } else {
      console.log(`Download failed: ${state}`)
    }
  })
})

Instance Events

Event: ‘updated’

Returns:

Emitted when the download has been updated and is not done.

The state can be one of following:

Event: ‘done’

Returns:

Emitted when the download is in a terminal state. This includes a completed download, a cancelled download (via downloadItem.cancel()), and interrupted download that can’t be resumed.

The state can be one of following:

Instance Methods

The downloadItem object has the following methods:

downloadItem.setSavePath(path)

The API is only available in session’s will-download callback function. If user doesn’t set the save path via the API, Electron will use the original routine to determine the save path(Usually prompts a save dialog).

downloadItem.getSavePath()

Returns String - The save path of the download item. This will be either the path set via downloadItem.setSavePath(path) or the path selected from the shown save dialog.

downloadItem.pause()

Pauses the download.

downloadItem.isPaused()

Returns Boolean - Whether the download is paused.

downloadItem.resume()

Resumes the download that has been paused.

downloadItem.canResume()

Resumes Boolean - Whether the download can resume.

downloadItem.cancel()

Cancels the download operation.

downloadItem.getURL()

Returns String - The origin url where the item is downloaded from.

downloadItem.getMimeType()

Returns String - The files mime type.

downloadItem.hasUserGesture()

Returns Boolean - Whether the download has user gesture.

downloadItem.getFilename()

Returns String - The file name of the download item.

Note: The file name is not always the same as the actual one saved in local disk. If user changes the file name in a prompted download saving dialog, the actual name of saved file will be different.

downloadItem.getTotalBytes()

Returns Integer - The total size in bytes of the download item.

If the size is unknown, it returns 0.

downloadItem.getReceivedBytes()

Returns Integer - The received bytes of the download item.

downloadItem.getContentDisposition()

Returns String - The Content-Disposition field from the response header.

downloadItem.getState()

Returns String - The current state. Can be progressing, completed, cancelled or interrupted.

Note: The following methods are useful specifically to resume a cancelled item when session is restarted.

downloadItem.getURLChain()

Returns String[] - The complete url chain of the item including any redirects.

downloadItem.getLastModifiedTime()

Returns String - Last-Modified header value.

downloadItem.getETag()

Returns String - ETag header value.

downloadItem.getStartTime()

Returns Double - Number of seconds since the UNIX epoch when the download was started.


Environment Variables

Control application configuration and behavior without changing code.

Certain Electron behaviors are controlled by environment variables because they are initialized earlier than the command line flags and the app’s code.

POSIX shell example:

$ export ELECTRON_ENABLE_LOGGING=true
$ electron

Windows console example:

> set ELECTRON_ENABLE_LOGGING=true
> electron

Production Variables

The following environment variables are intended primarily for use at runtime in packaged Electron applications.

GOOGLE_API_KEY

Electron includes a hardcoded API key for making requests to Google’s geocoding webservice. Because this API key is included in every version of Electron, it often exceeds its usage quota. To work around this, you can supply your own Google API key in the environment. Place the following code in your main process file, before opening any browser windows that will make geocoding requests:

process.env.GOOGLE_API_KEY = 'YOUR_KEY_HERE'

For instructions on how to acquire a Google API key, visit this page.

By default, a newly generated Google API key may not be allowed to make geocoding requests. To enable geocoding requests, visit this page.

ELECTRON_NO_ASAR

Disables ASAR support. This variable is only supported in forked child processes and spawned child processes that set ELECTRON_RUN_AS_NODE.

ELECTRON_RUN_AS_NODE

Starts the process as a normal Node.js process.

ELECTRON_NO_ATTACH_CONSOLE Windows

Don’t attach to the current console session.

ELECTRON_FORCE_WINDOW_MENU_BAR Linux

Don’t use the global menu bar on Linux.

Development Variables

The following environment variables are intended primarily for development and debugging purposes.

ELECTRON_ENABLE_LOGGING

Prints Chrome’s internal logging to the console.

ELECTRON_LOG_ASAR_READS

When Electron reads from an ASAR file, log the read offset and file path to the system tmpdir. The resulting file can be provided to the ASAR module to optimize file ordering.

ELECTRON_ENABLE_STACK_DUMPING

Prints the stack trace to the console when Electron crashes.

This environment variable will not work if the crashReporter is started.

ELECTRON_DEFAULT_ERROR_MODE Windows

Shows the Windows’s crash dialog when Electron crashes.

This environment variable will not work if the crashReporter is started.


File Object

Use the HTML5 File API to work natively with files on the filesystem.

The DOM’s File interface provides abstraction around native files in order to let users work on native files directly with the HTML5 file API. Electron has added a path attribute to the File interface which exposes the file’s real path on filesystem.

Example of getting a real path from a dragged-onto-the-app file:

<div id="holder">
  Drag your file here
</div>

<script>
  const holder = document.getElementById('holder')
  holder.ondragover = () => {
    return false;
  }
  holder.ondragleave = holder.ondragend = () => {
    return false;
  }
  holder.ondrop = (e) => {
    e.preventDefault()
    for (let f of e.dataTransfer.files) {
      console.log('File(s) you dragged here: ', f.path)
    }
    return false;
  }
</script>

Frameless Window

Open a window without toolbars, borders, or other graphical “chrome”.

A frameless window is a window that has no chrome, the parts of the window, like toolbars, that are not a part of the web page. These are options on the BrowserWindow class.

Create a frameless window

To create a frameless window, you need to set frame to false in BrowserWindow’s options:

const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 600, frame: false})
win.show()

Alternatives on macOS

On macOS 10.9 Mavericks and newer, there’s an alternative way to specify a chromeless window. Instead of setting frame to false which disables both the titlebar and window controls, you may want to have the title bar hidden and your content extend to the full window size, yet still preserve the window controls (“traffic lights”) for standard window actions. You can do so by specifying the new titleBarStyle option:

hidden

Results in a hidden title bar and a full size content window, yet the title bar still has the standard window controls (“traffic lights”) in the top left.

const {BrowserWindow} = require('electron')
let win = new BrowserWindow({titleBarStyle: 'hidden'})
win.show()

hidden-inset

Results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge.

const {BrowserWindow} = require('electron')
let win = new BrowserWindow({titleBarStyle: 'hidden-inset'})
win.show()

Transparent window

By setting the transparent option to true, you can also make the frameless window transparent:

const {BrowserWindow} = require('electron')
let win = new BrowserWindow({transparent: true, frame: false})
win.show()

Limitations

Click-through window

To create a click-through window, i.e. making the window ignore all mouse events, you can call the win.setIgnoreMouseEvents(ignore) API:

const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.setIgnoreMouseEvents(true)

Draggable region

By default, the frameless window is non-draggable. Apps need to specify -webkit-app-region: drag in CSS to tell Electron which regions are draggable (like the OS’s standard titlebar), and apps can also use -webkit-app-region: no-drag to exclude the non-draggable area from the draggable region. Note that only rectangular shapes are currently supported.

To make the whole window draggable, you can add -webkit-app-region: drag as body’s style:

<body style="-webkit-app-region: drag">
</body>

And note that if you have made the whole window draggable, you must also mark buttons as non-draggable, otherwise it would be impossible for users to click on them:

button {
  -webkit-app-region: no-drag;
}

If you’re setting just a custom titlebar as draggable, you also need to make all buttons in titlebar non-draggable.

Text selection

In a frameless window the dragging behaviour may conflict with selecting text. For example, when you drag the titlebar you may accidentally select the text on the titlebar. To prevent this, you need to disable text selection within a draggable area like this:

.titlebar {
  -webkit-user-select: none;
  -webkit-app-region: drag;
}

Context menu

On some platforms, the draggable area will be treated as a non-client frame, so when you right click on it a system menu will pop up. To make the context menu behave correctly on all platforms you should never use a custom context menu on draggable areas.


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. You should not use this module until the ready event of the app module is emitted.

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

app.on('ready', () => {
  // 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)

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.

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.


Class: IncomingMessage

Handle responses to HTTP/HTTPS requests.

Process: Main

IncomingMessage implements the Readable Stream interface and is therefore an EventEmitter.

Instance Events

Event: ‘data’

Returns:

The data event is the usual method of transferring response data into applicative code.

Event: ‘end’

Indicates that response body has ended.

Event: ‘aborted’

Emitted when a request has been canceled during an ongoing HTTP transaction.

Event: ‘error’

Returns:

error Error - Typically holds an error string identifying failure root cause.

Emitted when an error was encountered while streaming response data events. For instance, if the server closes the underlying while the response is still streaming, an error event will be emitted on the response object and a close event will subsequently follow on the request object.

Instance Properties

An IncomingMessage instance has the following readable properties:

response.statusCode

An Integer indicating the HTTP response status code.

response.statusMessage

A String representing the HTTP status message.

response.headers

An Object representing the response HTTP headers. The headers object is formatted as follows:

response.httpVersion

A String indicating the HTTP protocol version number. Typical values are ‘1.0’ or ‘1.1’. Additionally httpVersionMajor and httpVersionMinor are two Integer-valued readable properties that return respectively the HTTP major and minor version numbers.

response.httpVersionMajor

An Integer indicating the HTTP protocol major version number.

response.httpVersionMinor

An Integer indicating the HTTP protocol minor version number.


ipcMain

Communicate asynchronously from the main process to renderer processes.

Process: Main

The ipcMain module is an instance of the EventEmitter class. 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.

Sending Messages

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

An example of sending and handling messages between the render and main processes:

// In main process.
const {ipcMain} = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
  console.log(arg)  // prints "ping"
  event.sender.send('asynchronous-reply', 'pong')
})

ipcMain.on('synchronous-message', (event, arg) => {
  console.log(arg)  // prints "ping"
  event.returnValue = 'pong'
})
// In renderer process (web page).
const {ipcRenderer} = require('electron')
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"

ipcRenderer.on('asynchronous-reply', (event, arg) => {
  console.log(arg) // prints "pong"
})
ipcRenderer.send('asynchronous-message', 'ping')

Methods

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

ipcMain.on(channel, listener)

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

ipcMain.once(channel, listener)

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)

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

ipcMain.removeAllListeners([channel])

Removes all listeners, or those of the specified channel.

Event object

The event object passed to the callback has the following methods:

event.returnValue

Set this to the value to be returned in a synchronous message.

event.sender

Returns the webContents that sent the message, you can call event.sender.send to reply to the asynchronous message, see webContents.send for more information.


ipcRenderer

Communicate asynchronously from a renderer process to the main process.

Process: Renderer

The ipcRenderer module is an instance of the EventEmitter class. It provides a few methods so you can send synchronous and asynchronous messages from the render process (web page) to the main process. You can also receive replies from the main process.

See ipcMain for code examples.

Methods

The ipcRenderer module has the following method to listen for events and send messages:

ipcRenderer.on(channel, listener)

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

ipcRenderer.once(channel, listener)

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.

ipcRenderer.removeListener(channel, listener)

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

ipcRenderer.removeAllListeners([channel])

Removes all listeners, or those of the specified channel.

ipcRenderer.send(channel[, arg1][, arg2][, ...])

Send a message to the main process asynchronously via channel, you can also send arbitrary arguments. Arguments will be serialized in JSON internally and hence no functions or prototype chain will be included.

The main process handles it by listening for channel with ipcMain module.

ipcRenderer.sendSync(channel[, arg1][, arg2][, ...])

Send a message to the main process synchronously via channel, you can also send arbitrary arguments. Arguments will be serialized in JSON internally and hence no functions or prototype chain will be included.

The main process handles it by listening for channel with ipcMain module, and replies by setting event.returnValue.

Note: Sending a synchronous message will block the whole renderer process, unless you know what you are doing you should never use it.

ipcRenderer.sendToHost(channel[, arg1][, arg2][, ...])

Like ipcRenderer.send but the event will be sent to the <webview> element in the host page instead of the main process.


Locales

Locale values returned by app.getLocale().

Electron uses Chromium’s l10n_util library to fetch the locale. Possible values are listed below:

Language Code Language Name
af Afrikaans
an Aragonese
ar-AE Arabic (U.A.E.)
ar-IQ Arabic (Iraq)
ar Arabic (Standard)
ar-BH Arabic (Bahrain)
ar-DZ Arabic (Algeria)
ar-EG Arabic (Egypt)
ar-JO Arabic (Jordan)
ar-KW Arabic (Kuwait)
ar-LB Arabic (Lebanon)
ar-LY Arabic (Libya)
ar-MA Arabic (Morocco)
ar-OM Arabic (Oman)
ar-QA Arabic (Qatar)
ar-SA Arabic (Saudi Arabia)
ar-SY Arabic (Syria)
ar-TN Arabic (Tunisia)
ar-YE Arabic (Yemen)
as Assamese
ast Asturian
az Azerbaijani
be Belarusian
bg Bulgarian
bg Bulgarian
bn Bengali
br Breton
bs Bosnian
ca Catalan
ce Chechen
ch Chamorro
co Corsican
cr Cree
cs Czech
cv Chuvash
da Danish
de German (Standard)
de-AT German (Austria)
de-CH German (Switzerland)
de-DE German (Germany)
de-LI German (Liechtenstein)
de-LU German (Luxembourg)
el Greek
en-AU English (Australia)
en-BZ English (Belize)
en English
en-CA English (Canada)
en-GB English (United Kingdom)
en-IE English (Ireland)
en-JM English (Jamaica)
en-NZ English (New Zealand)
en-PH English (Philippines)
en-TT English (Trinidad & Tobago)
en-US English (United States)
en-ZA English (South Africa)
en-ZW English (Zimbabwe)
eo Esperanto
et Estonian
eu Basque
fa Persian
fa Farsi
fa-IR Persian/Iran
fi Finnish
fj Fijian
fo Faeroese
fr-CH French (Switzerland)
fr-FR French (France)
fr-LU French (Luxembourg)
fr-MC French (Monaco)
fr French (Standard)
fr-BE French (Belgium)
fr-CA French (Canada)
fur Friulian
fy Frisian
ga Irish
gd-IE Gaelic (Irish)
gd Gaelic (Scots)
gl Galacian
gu Gujurati
he Hebrew
hi Hindi
hr Croatian
ht Haitian
hu Hungarian
hy Armenian
id Indonesian
is Icelandic
it-CH Italian (Switzerland)
it Italian (Standard)
iu Inuktitut
ja Japanese
ka Georgian
kk Kazakh
km Khmer
kn Kannada
ko Korean
ko-KP Korean (North Korea)
ko-KR Korean (South Korea)
ks Kashmiri
ky Kirghiz
la Latin
lb Luxembourgish
lt Lithuanian
lv Latvian
mi Maori
mk FYRO Macedonian
ml Malayalam
mo Moldavian
mr Marathi
ms Malay
mt Maltese
my Burmese
nb Norwegian (Bokmal)
ne Nepali
ng Ndonga
nl Dutch (Standard)
nl-BE Dutch (Belgian)
nn Norwegian (Nynorsk)
no Norwegian
nv Navajo
oc Occitan
om Oromo
or Oriya
sq Albanian
tlh Klingon
zh-TW Chinese (Taiwan)
zh Chinese
zh-CN Chinese (PRC)
zh-HK Chinese (Hong Kong)
zh-SG Chinese (Singapore)

Class: MenuItem

Add items to native application menus and context menus.

Process: Main

See Menu for examples.

new MenuItem(options)

It is best to specify role for any menu item that matches a standard role, rather than trying to manually implement the behavior in a click function. The built-in role behavior will give the best native experience.

The label and accelerator are optional when using a role and will default to appropriate values for each platform.

The role property can have following values:

On macOS role can also have following additional values:

When specifying role on macOS, label and accelerator are the only options that will affect the MenuItem. All other options will be ignored.

Instance Properties

The following properties are available on instances of MenuItem:

A Boolean indicating whether the item is enabled, this property can be dynamically changed.

A Boolean indicating whether the item is visible, this property can be dynamically changed.

A Boolean indicating whether the item is checked, this property can be dynamically changed.

A checkbox menu item will toggle the checked property on and off when selected.

A radio menu item will turn on its checked property when clicked, and will turn off that property for all adjacent items in the same menu.

You can add a click function for additional behavior.

A String representing the menu items visible label

A Function that is fired when the MenuItem recieves a click event


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:

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

Note: This API has to be called after the ready event of app module.

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

Sends the action to the first responder of application. This is used for emulating default Cocoa menu behaviors, usually you would just use the role property of MenuItem.

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

Returns Menu

Generally, the template is just 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:

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

Closes the context menu in the browserWindow.

Appends the menuItem to the menu.

Inserts the menuItem to the pos position of the menu.

Instance Properties

menu objects also have the following properties:

A MenuItem[] array containing the menu’s items.

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

Examples

The Menu class is only available in the main process, but you can also use it in the render process via the remote module.

Main process

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

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

const template = [
  {
    label: 'Edit',
    submenu: [
      {
        role: 'undo'
      },
      {
        role: 'redo'
      },
      {
        type: 'separator'
      },
      {
        role: 'cut'
      },
      {
        role: 'copy'
      },
      {
        role: 'paste'
      },
      {
        role: 'pasteandmatchstyle'
      },
      {
        role: 'delete'
      },
      {
        role: 'selectall'
      }
    ]
  },
  {
    label: 'View',
    submenu: [
      {
        role: 'reload'
      },
      {
        role: 'forcereload'
      },
      {
        role: 'toggledevtools'
      },
      {
        type: 'separator'
      },
      {
        role: 'resetzoom'
      },
      {
        role: 'zoomin'
      },
      {
        role: 'zoomout'
      },
      {
        type: 'separator'
      },
      {
        role: 'togglefullscreen'
      }
    ]
  },
  {
    role: 'window',
    submenu: [
      {
        role: 'minimize'
      },
      {
        role: 'close'
      }
    ]
  },
  {
    role: 'help',
    submenu: [
      {
        label: 'Learn More',
        click () { require('electron').shell.openExternal('http://electron.atom.io') }
      }
    ]
  }
]

if (process.platform === 'darwin') {
  template.unshift({
    label: app.getName(),
    submenu: [
      {
        role: 'about'
      },
      {
        type: 'separator'
      },
      {
        role: 'services',
        submenu: []
      },
      {
        type: 'separator'
      },
      {
        role: 'hide'
      },
      {
        role: 'hideothers'
      },
      {
        role: 'unhide'
      },
      {
        type: 'separator'
      },
      {
        role: 'quit'
      }
    ]
  })
  // Edit menu.
  template[1].submenu.push(
    {
      type: 'separator'
    },
    {
      label: 'Speech',
      submenu: [
        {
          role: 'startspeaking'
        },
        {
          role: 'stopspeaking'
        }
      ]
    }
  )
  // Window menu.
  template[3].submenu = [
    {
      label: 'Close',
      accelerator: 'CmdOrCtrl+W',
      role: 'close'
    },
    {
      label: 'Minimize',
      accelerator: 'CmdOrCtrl+M',
      role: 'minimize'
    },
    {
      label: 'Zoom',
      role: 'zoom'
    },
    {
      type: 'separator'
    },
    {
      label: 'Bring All to Front',
      role: 'front'
    }
  ]
}

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

Render process

Below is an example of creating a menu dynamically in a web page (render process) by using the remote module, and showing it when the user right clicks the page:

<!-- index.html -->
<script>
const {remote} = require('electron')
const {Menu, MenuItem} = remote

const menu = new Menu()
menu.append(new MenuItem({label: 'MenuItem1', click() { console.log('item 1 clicked') }}))
menu.append(new MenuItem({type: 'separator'}))
menu.append(new MenuItem({label: 'MenuItem2', type: 'checkbox', checked: true}))

window.addEventListener('contextmenu', (e) => {
  e.preventDefault()
  menu.popup(remote.getCurrentWindow())
}, false)
</script>

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 following and Electron will recognize them and make them become standard menus:

Standard Menu Item Actions

macOS has provided standard actions for some menu items, like About xxx, Hide 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 position and id to control how the item will be placed when building a menu with Menu.buildFromTemplate.

The position attribute of MenuItem has the form [placement]=[id], where placement is one of before, after, or endof and id is the unique ID of an existing item in the menu:

When an item is positioned, all un-positioned items are inserted after it until a new item is positioned. So if you want to position a group of menu items in the same location you only need to specify a position for the first item.

Examples

Template:

[
  {label: '4', id: '4'},
  {label: '5', id: '5'},
  {label: '1', id: '1', position: 'before=4'},
  {label: '2', id: '2'},
  {label: '3', id: '3'}
]

Menu:

- 1
- 2
- 3
- 4
- 5

Template:

[
  {label: 'a', position: 'endof=letters'},
  {label: '1', position: 'endof=numbers'},
  {label: 'b', position: 'endof=letters'},
  {label: '2', position: 'endof=numbers'},
  {label: 'c', position: 'endof=letters'},
  {label: '3', position: 'endof=numbers'}
]

Menu:

- ---
- a
- b
- c
- ---
- 1
- 2
- 3


nativeImage

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

Process: Main, Renderer

In Electron, for the APIs that take images, you can pass either file paths or NativeImage instances. An empty image will be used when null is passed.

For example, when creating a tray or setting a window’s icon, you can pass an image file path as a String:

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

const appIcon = new Tray('/Users/somebody/images/icon.png')
let win = new BrowserWindow({icon: '/Users/somebody/images/window.png'})
console.log(appIcon, win)

Or read the image from the clipboard which returns a NativeImage:

const {clipboard, Tray} = require('electron')
const image = clipboard.readImage()
const appIcon = new Tray(image)
console.log(appIcon)

Supported Formats

Currently PNG and JPEG image formats are supported. 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 it is recommended to include at least the following sizes in the:

Check the Size requirements section in this article.

High Resolution Image

On platforms that have high-DPI support such as Apple Retina displays, you can append @2x after image’s base filename to mark it as a high resolution image.

For example if icon.png is a normal image that has standard resolution, then icon@2x.png will be treated as a high resolution image that has double 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. For example:

images/
├── icon.png
├── icon@2x.png
└── icon@3x.png
const {Tray} = require('electron')
let appIcon = new Tray('/Users/somebody/images/icon.png')
console.log(appIcon)

Following suffixes for DPI are also supported:

Template Image

Template images consist of black and clear colors (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 icon so it can adapt to both light and dark menu bars.

Note: Template image is only supported on macOS.

To mark an image as a template image, its filename should end with the word Template. For example:

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.createFromPath(path)

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').nativeImage

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

nativeImage.createFromBuffer(buffer[, options])

Returns NativeImage

Creates a new NativeImage instance from buffer.

nativeImage.createFromDataURL(dataURL)

Creates a new NativeImage instance from dataURL.

Class: NativeImage

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

Process: Main, Renderer

Instance Methods

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

image.toPNG()

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

image.toJPEG(quality)

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

image.toBitmap()

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

image.toDataURL()

Returns String - The data URL of the image.

image.getBitmap()

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

The difference between getBitmap() and toBitmap() is, 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 would be 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()

Returns Object:

image.setTemplateImage(option)

Marks the image as a template image.

image.isTemplateImage()

Returns Boolean - Whether the image is a template image.

image.crop(rect)

Returns NativeImage - The cropped image.

image.resize(options)

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()

Returns Float - The image’s aspect ratio.


net

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

Process: Main

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.

The following is a non-exhaustive list of why you may consider using the net module instead of the native Node.js modules:

The net module API has been specifically designed to mimic, as closely as possible, the familiar Node.js API. The API components including classes, methods, properties and event names are similar to those commonly used in Node.js.

For instance, the following example quickly shows how the net API might be used:

const {app} = require('electron')
app.on('ready', () => {
  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()
})

By the way, it is almost identical to how you would normally use the HTTP/HTTPS modules of Node.js

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.


powerMonitor

Monitor power state changes.

Process: Main

You cannot require or use this module until the ready event of the app module is emitted.

For example:

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

app.on('ready', () => {
  electron.powerMonitor.on('suspend', () => {
    console.log('The system is going to sleep')
  })
})

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’ Windows

Emitted when the system changes to AC power.

Event: ‘on-battery’ Windows

Emitted when system changes to battery power.


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)

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-sleep. prevent-display-sleep will be used until B stops its request. After that, prevent-app-suspension is used.

powerSaveBlocker.stop(id)

Stops the specified power save blocker.

powerSaveBlocker.isStarted(id)

Returns Boolean - Whether the corresponding powerSaveBlocker has started.


process

Extensions to process object.

Process: Main, Renderer

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

Events

Event: ‘loaded’

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

It can be used by the preload script to add removed Node global symbols back to the global scope when node integration is turned off:

// preload.js
const _setImmediate = setImmediate
const _clearImmediate = clearImmediate
process.once('loaded', () => {
  global.setImmediate = _setImmediate
  global.clearImmediate = _clearImmediate
})

Properties

process.noAsar

Setting this to true can disable the support for asar archives in Node’s built-in modules.

process.type

Current process’s type, can be "browser" (i.e. main process) or "renderer".

process.versions.electron

Electron’s version string.

process.versions.chrome

Chrome’s version string.

process.resourcesPath

Path to the resources directory.

process.mas

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

process.windowsStore

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

process.defaultApp

When app is started by being passed as parameter to the default app, this property is true in the main process, otherwise it is undefined.

Methods

The process object has the following method:

process.crash()

Causes the main thread of the current process crash.

process.hang()

Causes the main thread of the current process hang.

process.setFdLimit(maxDescriptors) macOS Linux

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

process.getProcessMemoryInfo()

Returns Object:

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

process.getSystemMemoryInfo()

Returns Object:

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


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} = require('electron')
const path = require('path')

app.on('ready', () => {
  protocol.registerFileProtocol('atom', (request, callback) => {
    const url = request.url.substr(7)
    callback({path: path.normalize(`${__dirname}/${url}`)})
  }, (error) => {
    if (error) console.error('Failed to register protocol')
  })
})

Note: All methods unless specified can only be used after the ready event of the app module gets emitted.

Methods

The protocol module has the following methods:

protocol.registerStandardSchemes(schemes[, options])

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, will allow 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:

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

protocol.registerStandardSchemes(['atom'])
app.on('ready', () => {
  protocol.registerHttpProtocol('atom', '...')
})

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

protocol.registerServiceWorkerSchemes(schemes)

protocol.registerFileProtocol(scheme, handler[, completion])

Registers a protocol of scheme that will send the file as a response. The handler will be called with handler(request, callback) when a request is going to be created with scheme. completion will be called with completion(null) when scheme is successfully registered or completion(error) when failed.

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

When callback is called with nothing, a number, or an object that has an error property, the request will fail with the error number you specified. For the available error numbers you can use, please see the net error list.

By default the scheme is treated like http:, which is parsed differently than protocols that follow the “generic URI syntax” like file:, so you probably want to call protocol.registerStandardSchemes to have your scheme treated as a standard scheme.

protocol.registerBufferProtocol(scheme, handler[, completion])

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, mimeType, and charset properties.

Example:

const {protocol} = require('electron')

protocol.registerBufferProtocol('atom', (request, callback) => {
  callback({mimeType: 'text/html', data: new Buffer('<h5>Response</h5>')})
}, (error) => {
  if (error) console.error('Failed to register protocol')
})

protocol.registerStringProtocol(scheme, handler[, completion])

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, mimeType, and charset properties.

protocol.registerHttpProtocol(scheme, handler[, completion])

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 a redirectRequest object that has the url, method, referrer, uploadData and session properties.

By default the HTTP request will reuse the current session. If you want the request to have a different session you should set session to null.

For POST requests the uploadData object must be provided.

protocol.unregisterProtocol(scheme[, completion])

Unregisters the custom protocol of scheme.

protocol.isProtocolHandled(scheme, callback)

The callback will be called with a boolean that indicates whether there is already a handler for scheme.

protocol.interceptFileProtocol(scheme, handler[, completion])

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

protocol.interceptStringProtocol(scheme, handler[, completion])

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

protocol.interceptBufferProtocol(scheme, handler[, completion])

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

protocol.interceptHttpProtocol(scheme, handler[, completion])

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

protocol.uninterceptProtocol(scheme[, completion])

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


remote

Use main process modules from the renderer process.

Process: Renderer

The remote module provides a simple way to do inter-process communication (IPC) between the renderer process (web page) and the main process.

In Electron, GUI-related modules (such as dialog, menu etc.) are only available in the main process, not in the renderer process. In order to use them from the renderer process, the ipc module is necessary to send inter-process messages to the main process. With the remote module, you can invoke methods of the main process object without explicitly sending inter-process messages, similar to Java’s RMI. An example of creating a browser window from a renderer process:

const {BrowserWindow} = require('electron').remote
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('https://github.com')

Note: For the reverse (access the renderer process from the main process), you can use webContents.executeJavascript.

Remote Objects

Each object (including functions) returned by the remote module represents an object in the main process (we call it a remote object or remote function). When you invoke methods of a remote object, call a remote function, or create a new object with the remote constructor (function), you are actually sending synchronous inter-process messages.

In the example above, both BrowserWindow and win were remote objects and new BrowserWindow didn’t create a BrowserWindow object in the renderer process. Instead, it created a BrowserWindow object in the main process and returned the corresponding remote object in the renderer process, namely the win object.

Note: Only enumerable properties which are present when the remote object is first referenced are accessible via remote.

Note: Arrays and Buffers are copied over IPC when accessed via the remote module. Modifying them in the renderer process does not modify them in the main process and vice versa.

Lifetime of Remote Objects

Electron makes sure that as long as the remote object in the renderer process lives (in other words, has not been garbage collected), the corresponding object in the main process will not be released. When the remote object has been garbage collected, the corresponding object in the main process will be dereferenced.

If the remote object is leaked in the renderer process (e.g. stored in a map but never freed), the corresponding object in the main process will also be leaked, so you should be very careful not to leak remote objects.

Primary value types like strings and numbers, however, are sent by copy.

Passing callbacks to the main process

Code in the main process can accept callbacks from the renderer - for instance the remote module - but you should be extremely careful when using this feature.

First, in order to avoid deadlocks, the callbacks passed to the main process are called asynchronously. You should not expect the main process to get the return value of the passed callbacks.

For instance you can’t use a function from the renderer process in an Array.map called in the main process:

// main process mapNumbers.js
exports.withRendererCallback = (mapper) => {
  return [1, 2, 3].map(mapper)
}

exports.withLocalCallback = () => {
  return [1, 2, 3].map(x => x + 1)
}
// renderer process
const mapNumbers = require('electron').remote.require('./mapNumbers')
const withRendererCb = mapNumbers.withRendererCallback(x => x + 1)
const withLocalCb = mapNumbers.withLocalCallback()

console.log(withRendererCb, withLocalCb)
// [undefined, undefined, undefined], [2, 3, 4]

As you can see, the renderer callback’s synchronous return value was not as expected, and didn’t match the return value of an identical callback that lives in the main process.

Second, the callbacks passed to the main process will persist until the main process garbage-collects them.

For example, the following code seems innocent at first glance. It installs a callback for the close event on a remote object:

require('electron').remote.getCurrentWindow().on('close', () => {
  // window was closed...
})

But remember the callback is referenced by the main process until you explicitly uninstall it. If you do not, each time you reload your window the callback will be installed again, leaking one callback for each restart.

To make things worse, since the context of previously installed callbacks has been released, exceptions will be raised in the main process when the close event is emitted.

To avoid this problem, ensure you clean up any references to renderer callbacks passed to the main process. This involves cleaning up event handlers, or ensuring the main process is explicitly told to deference callbacks that came from a renderer process that is exiting.

Accessing built-in modules in the main process

The built-in modules in the main process are added as getters in the remote module, so you can use them directly like the electron module.

const app = require('electron').remote.app
console.log(app)

Methods

The remote module has the following methods:

remote.require(module)

Returns any - The object returned by require(module) in the main process.

remote.getCurrentWindow()

Returns BrowserWindow - The window to which this web page belongs.

remote.getCurrentWebContents()

Returns WebContents - The web contents of this web page.

remote.getGlobal(name)

Returns any - The global variable of name (e.g. global[name]) in the main process.

Properties

remote.process

The process object in the main process. This is the same as remote.getGlobal('process') but is cached.


screen

Retrieve information about screen size, displays, cursor position, etc.

Process: Main, Renderer

You cannot require or use this module until the ready event of the app module is emitted.

screen is an EventEmitter.

Note: In the renderer / DevTools, window.screen is a reserved DOM property, so writing let {screen} = require('electron') will not work.

An example of creating a window that fills the whole screen:

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

let win

app.on('ready', () => {
  const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize
  win = new BrowserWindow({width, height})
  win.loadURL('https://github.com')
})

Another example of creating a window in the external display:

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

let win

app.on('ready', () => {
  let displays = electron.screen.getAllDisplays()
  let externalDisplay = displays.find((display) => {
    return display.bounds.x !== 0 || display.bounds.y !== 0
  })

  if (externalDisplay) {
    win = new BrowserWindow({
      x: externalDisplay.bounds.x + 50,
      y: externalDisplay.bounds.y + 50
    })
    win.loadURL('https://github.com')
  }
})

Events

The screen module emits the following events:

Event: ‘display-added’

Returns:

Emitted when newDisplay has been added.

Event: ‘display-removed’

Returns:

Emitted when oldDisplay has been removed.

Event: ‘display-metrics-changed’

Returns:

Emitted when one or more metrics change in a display. The changedMetrics is an array of strings that describe the changes. Possible changes are bounds, workArea, scaleFactor and rotation.

Methods

The screen module has the following methods:

screen.getCursorScreenPoint()

Returns Object:

The current absolute position of the mouse pointer.

screen.getPrimaryDisplay()

Returns Display - The primary display.

screen.getAllDisplays()

Returns Display[] - An array of displays that are currently available.

screen.getDisplayNearestPoint(point)

Returns Display - The display nearest the specified point.

screen.getDisplayMatching(rect)

Returns Display - The display that most closely intersects the provided bounds.


session

Manage browser sessions, cookies, cache, proxy settings, etc.

Process: Main

The session module can be used to create new Session objects.

You can also access the session of existing pages by using the session property of WebContents, or from the session module.

const {BrowserWindow} = require('electron')

let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('http://github.com')

const ses = win.webContents.session
console.log(ses.getUserAgent())

Methods

The session module has the following methods:

session.fromPartition(partition[, options])

Returns Session - A session instance from partition string. When there is an existing Session with the same partition, it will be returned; otherwise a new Session instance will be created with options.

If partition starts with persist:, the page will use a persistent session available to all pages in the app with the same partition. if there is no persist: prefix, the page will use an in-memory session. If the partition is empty then default session of the app will be returned.

To create a Session with options, you have to ensure the Session with the partition has never been used before. There is no way to change the options of an existing Session object.

Properties

The session module has the following properties:

session.defaultSession

A Session object, the default session object of the app.

Class: Session

Get and set properties of a session.

Process: Main

You can create a Session object in the session module:

const {session} = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())

Instance Events

The following events are available on instances of Session:

Event: ‘will-download’

Emitted when Electron is about to download item in webContents.

Calling event.preventDefault() will cancel the download and item will not be available from next tick of the process.

const {session} = require('electron')
session.defaultSession.on('will-download', (event, item, webContents) => {
  event.preventDefault()
  require('request')(item.getURL(), (data) => {
    require('fs').writeFileSync('/somewhere', data)
  })
})

Instance Methods

The following methods are available on instances of Session:

ses.getCacheSize(callback)

Callback is invoked with the session’s current cache size.

ses.clearCache(callback)

Clears the session’s HTTP cache.

ses.clearStorageData([options, callback])

Clears the data of web storages.

ses.flushStorageData()

Writes any unwritten DOMStorage data to disk.

ses.setProxy(config, callback)

Sets the proxy settings.

When pacScript and proxyRules are provided together, the proxyRules option is ignored and pacScript configuration is applied.

The proxyRules has to follow the rules below:

proxyRules = schemeProxies[";"<schemeProxies>]
schemeProxies = [<urlScheme>"="]<proxyURIList>
urlScheme = "http" | "https" | "ftp" | "socks"
proxyURIList = <proxyURL>[","<proxyURIList>]
proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>]

For example:

The proxyBypassRules is a comma separated list of rules described below:

ses.resolveProxy(url, callback)

Resolves the proxy information for url. The callback will be called with callback(proxy) when the request is performed.

ses.setDownloadPath(path)

Sets download saving directory. By default, the download directory will be the Downloads under the respective app folder.

ses.enableNetworkEmulation(options)

Emulates network with the given configuration for the session.

// To emulate a GPRS connection with 50kbps throughput and 500 ms latency.
window.webContents.session.enableNetworkEmulation({
  latency: 500,
  downloadThroughput: 6400,
  uploadThroughput: 6400
})

// To emulate a network outage.
window.webContents.session.enableNetworkEmulation({offline: true})

ses.disableNetworkEmulation()

Disables any network emulation already active for the session. Resets to the original network configuration.

ses.setCertificateVerifyProc(proc)

Sets the certificate verify proc for session, the proc will be called with proc(request, callback) whenever a server certificate verification is requested. Calling callback(0) accepts the certificate, calling callback(-2) rejects it.

Calling setCertificateVerifyProc(null) will revert back to default certificate verify proc.

const {BrowserWindow} = require('electron')
let win = new BrowserWindow()

win.webContents.session.setCertificateVerifyProc((request, callback) => {
  const {hostname} = request
  if (hostname === 'github.com') {
    callback(0)
  } else {
    callback(-2)
  }
})

ses.setPermissionRequestHandler(handler)

Sets the handler which can be used to respond to permission requests for the session. Calling callback(true) will allow the permission and callback(false) will reject it.

const {session} = require('electron')
session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => {
  if (webContents.getURL() === 'some-host' && permission === 'notifications') {
    return callback(false) // denied.
  }

  callback(true)
})

ses.clearHostResolverCache([callback])

Clears the host resolver cache.

ses.allowNTLMCredentialsForDomains(domains)

Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication.

const {session} = require('electron')
// consider any url ending with `example.com`, `foobar.com`, `baz`
// for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz')

// consider all urls for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*')

ses.setUserAgent(userAgent[, acceptLanguages])

Overrides the userAgent and acceptLanguages for this session.

The acceptLanguages must a comma separated ordered list of language codes, for example "en-US,fr,de,ko,zh-CN,ja".

This doesn’t affect existing WebContents, and each WebContents can use webContents.setUserAgent to override the session-wide user agent.

ses.getUserAgent()

Returns String - The user agent for this session.

ses.getBlobData(identifier, callback)

Returns Blob - The blob data associated with the identifier.

ses.createInterruptedDownload(options)

Allows resuming cancelled or interrupted downloads from previous Session. The API will generate a DownloadItem that can be accessed with the will-download event. The DownloadItem will not have any WebContents associated with it and the initial state will be interrupted. The download will start only when the resume API is called on the DownloadItem.

ses.clearAuthCache(options[, callback])

Clears the session’s HTTP authentication cache.

Instance Properties

The following properties are available on instances of Session:

ses.cookies

A Cookies object for this session.

ses.webRequest

A WebRequest object for this session.

ses.protocol

A Protocol object (an instance of protocol module) for this session.

const {app, session} = require('electron')
const path = require('path')

app.on('ready', function () {
  const protocol = session.fromPartition('some-partition').protocol
  protocol.registerFileProtocol('atom', function (request, callback) {
    var url = request.url.substr(7)
    callback({path: path.normalize(`${__dirname}/${url}`)})
  }, function (error) {
    if (error) console.error('Failed to register protocol')
  })
})

shell

Manage files and URLs using their default applications.

Process: Main, Renderer

The shell module provides functions related to desktop integration.

An example of opening a URL in the user’s default browser:

const {shell} = require('electron')

shell.openExternal('https://github.com')

Methods

The shell module has the following methods:

shell.showItemInFolder(fullPath)

Returns Boolean - Whether the item was successfully shown

Show the given file in a file manager. If possible, select the file.

shell.openItem(fullPath)

Returns Boolean - Whether the item was successfully opened.

Open the given file in the desktop’s default manner.

shell.openExternal(url[, options, callback])

Returns Boolean - Whether an application was available to open the URL. If callback is specified, always returns true.

Open the given external protocol URL in the desktop’s default manner. (For example, mailto: URLs in the user’s default mail agent).

shell.moveItemToTrash(fullPath)

Returns Boolean - Whether the item was successfully moved to the trash

Move the given file to trash and returns a boolean status for the operation.

shell.beep()

Play the beep sound.

shell.writeShortcutLink(shortcutPath[, operation], options) Windows

Returns Boolean - Whether the shortcut was created successfully

Creates or updates a shortcut link at shortcutPath.

shell.readShortcutLink(shortcutPath) Windows

Returns ShortcutDetails

Resolves the shortcut link at shortcutPath.

An exception will be thrown when any error happens.


BluetoothDevice Object


CertificatePrincipal Object


Certificate Object


Cookie Object


CrashReport Object


DesktopCapturerSource Object


Display Object

The Display object represents a physical display connected to the system. A fake Display may exist on a headless system, or a Display may correspond to a remote, virtual display.


FileFilter Object


JumpListCategory Object

Note: If a JumpListCategory object has neither the type nor the name property set then its type is assumed to be tasks. If the name property is set but the type property is omitted then the type is assumed to be custom.


JumpListItem Object


MemoryUsageDetails Object


MimeTypedBuffer Object


Rectangle Object


RemoveClientCertificate Object


RemovePassword Object


ShortcutDetails Object


Task Object


ThumbarButton Object

The flags is an array that can include following Strings:


UploadBlob Object


UploadData Object


UploadFileSystem Object


UploadFile Object


UploadRawData Object


Synopsis

How to use Node.js and Electron APIs.

All of Node.js’s built-in modules are available in Electron and third-party node modules also fully supported as well (including the native modules).

Electron also provides some extra built-in modules for developing native desktop applications. Some modules are only available in the main process, some are only available in the renderer process (web page), and some can be used in both processes.

The basic rule is: if a module is GUI or low-level system related, then it should be only available in the main process. You need to be familiar with the concept of main process vs. renderer process scripts to be able to use those modules.

The main process script is just like a normal Node.js script:

const {app, BrowserWindow} = require('electron')
let win = null

app.on('ready', () => {
  win = new BrowserWindow({width: 800, height: 600})
  win.loadURL('https://github.com')
})

The renderer process is no different than a normal web page, except for the extra ability to use node modules:

<!DOCTYPE html>
<html>
<body>
<script>
  const {app} = require('electron').remote
  console.log(app.getVersion())
</script>
</body>
</html>

To run your app, read Run your app.

Destructuring assignment

As of 0.37, you can use destructuring assignment to make it easier to use built-in modules.

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

let win

app.on('ready', () => {
  win = new BrowserWindow()
  win.loadURL('https://github.com')
})

If you need the entire electron module, you can require it and then using destructuring to access the individual modules from electron.

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

let win

app.on('ready', () => {
  win = new BrowserWindow()
  win.loadURL('https://github.com')
})

This is equivalent to the following code:

const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let win

app.on('ready', () => {
  win = new BrowserWindow()
  win.loadURL('https://github.com')
})

systemPreferences

Get system preferences.

Process: Main

const {systemPreferences} = require('electron')
console.log(systemPreferences.isDarkMode())

Events

The systemPreferences object emits the following events:

Event: ‘accent-color-changed’ Windows

Returns:

Event: ‘color-changed’ Windows

Returns:

Event: ‘inverted-color-scheme-changed’ Windows

Returns:

Methods

systemPreferences.isDarkMode() macOS

Returns Boolean - Whether the system is in Dark Mode.

systemPreferences.isSwipeTrackingFromScrollEventsEnabled() macOS

Returns Boolean - Whether the Swipe between pages setting is on.

systemPreferences.postNotification(event, userInfo) macOS

Posts event as native notifications of macOS. The userInfo is an Object that contains the user information dictionary sent along with the notification.

systemPreferences.postLocalNotification(event, userInfo) macOS

Posts event as native notifications of macOS. The userInfo is an Object that contains the user information dictionary sent along with the notification.

systemPreferences.subscribeNotification(event, callback) macOS

Subscribes to native notifications of macOS, callback will be called with callback(event, userInfo) when the corresponding event happens. The userInfo is an Object that contains the user information dictionary sent along with the notification.

The id of the subscriber is returned, which can be used to unsubscribe the event.

Under the hood this API subscribes to NSDistributedNotificationCenter, example values of event are:

systemPreferences.unsubscribeNotification(id) macOS

Removes the subscriber with id.

systemPreferences.subscribeLocalNotification(event, callback) macOS

Same as subscribeNotification, but uses NSNotificationCenter for local defaults. This is necessary for events such as NSUserDefaultsDidChangeNotification

systemPreferences.unsubscribeLocalNotification(id) macOS

Same as unsubscribeNotification, but removes the subscriber from NSNotificationCenter.

systemPreferences.getUserDefault(key, type) macOS

Get the value of key in system preferences.

This API uses NSUserDefaults on macOS. Some popular key and types are:

systemPreferences.setUserDefault(key, type, value) macOS

Set the value of key in system preferences.

Note that type should match actual type of value. An exception is thrown if they don’t.

This API uses NSUserDefaults on macOS. Some popular key and types are:

systemPreferences.isAeroGlassEnabled() Windows

This method returns true if DWM composition (Aero Glass) is enabled, and false otherwise.

An example of using it to determine if you should create a transparent window or not (transparent windows won’t work correctly when DWM composition is disabled):

const {BrowserWindow, systemPreferences} = require('electron')
let browserOptions = {width: 1000, height: 800}

// Make the window transparent only if the platform supports it.
if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) {
  browserOptions.transparent = true
  browserOptions.frame = false
}

// Create the window.
let win = new BrowserWindow(browserOptions)

// Navigate.
if (browserOptions.transparent) {
  win.loadURL(`file://${__dirname}/index.html`)
} else {
  // No transparency, so we load a fallback that uses basic styles.
  win.loadURL(`file://${__dirname}/fallback.html`)
}

systemPreferences.getAccentColor() Windows

Returns String - The users current system wide accent color preference in RGBA hexadecimal form.

const color = systemPreferences.getAccentColor() // `"aabbccdd"`
const red = color.substr(0, 2) // "aa"
const green = color.substr(2, 2) // "bb"
const blue = color.substr(4, 2) // "cc"
const alpha = color.substr(6, 2) // "dd"

systemPreferences.getColor(color) Windows

Returns String - The system color setting in RGB hexadecimal form (#ABCDEF). See the Windows docs for more details.

systemPreferences.isInvertedColorScheme() Windows

Returns Boolean - true if an inverted color scheme, such as a high contrast theme, is active, false otherwise.


Class: Tray

Add icons and context menus to the system’s notification area.

Process: Main

Tray is an EventEmitter.

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

let tray = null
app.on('ready', () => {
  tray = new Tray('/path/to/my/icon')
  const contextMenu = Menu.buildFromTemplate([
    {label: 'Item1', type: 'radio'},
    {label: 'Item2', type: 'radio'},
    {label: 'Item3', type: 'radio', checked: true},
    {label: 'Item4', type: 'radio'}
  ])
  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)
})

Platform limitations:

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

let appIcon = null
app.on('ready', () => {
  appIcon = new Tray('/path/to/my/icon')
  const contextMenu = Menu.buildFromTemplate([
    {label: 'Item1', type: 'radio'},
    {label: 'Item2', type: 'radio'}
  ])

  // Make a change to the context menu
  contextMenu.items[1].checked = false

  // Call this again for Linux because we modified the context menu
  appIcon.setContextMenu(contextMenu)
})

If you want to keep exact same behaviors on all platforms, you should not rely on the click event and always attach a context menu to the tray icon.

new Tray(image)

Creates a new tray icon associated with the image.

Instance Events

The Tray module emits the following events:

Event: ‘click’

Emitted when the tray icon is clicked.

Event: ‘right-click’ macOS Windows

Emitted when the tray icon is right clicked.

Event: ‘double-click’ macOS Windows

Emitted when the tray icon is double clicked.

Event: ‘balloon-show’ Windows

Emitted when the tray balloon shows.

Event: ‘balloon-click’ Windows

Emitted when the tray balloon is clicked.

Event: ‘balloon-closed’ Windows

Emitted when the tray balloon is closed because of timeout or user manually closes it.

Event: ‘drop’ macOS

Emitted when any dragged items are dropped on the tray icon.

Event: ‘drop-files’ macOS

Emitted when dragged files are dropped in the tray icon.

Event: ‘drop-text’ macOS

Emitted when dragged text is dropped in the tray icon.

Event: ‘drag-enter’ macOS

Emitted when a drag operation enters the tray icon.

Event: ‘drag-leave’ macOS

Emitted when a drag operation exits the tray icon.

Event: ‘drag-end’ macOS

Emitted when a drag operation ends on the tray or ends at another location.

Instance Methods

The Tray class has the following methods:

tray.destroy()

Destroys the tray icon immediately.

tray.setImage(image)

Sets the image associated with this tray icon.

tray.setPressedImage(image) macOS

Sets the image associated with this tray icon when pressed on macOS.

tray.setToolTip(toolTip)

Sets the hover text for this tray icon.

tray.setTitle(title) macOS

Sets the title displayed aside of the tray icon in the status bar.

tray.setHighlightMode(mode) macOS

Sets when the tray’s icon background becomes highlighted (in blue).

Note: You can use highlightMode with a BrowserWindow by toggling between 'never' and 'always' modes when the window visibility changes.

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

const win = new BrowserWindow({width: 800, height: 600})
const tray = new Tray('/path/to/my/icon')

tray.on('click', () => {
  win.isVisible() ? win.hide() : win.show()
})
win.on('show', () => {
  tray.setHighlightMode('always')
})
win.on('hide', () => {
  tray.setHighlightMode('never')
})

tray.displayBalloon(options) Windows

Displays a tray balloon.

tray.popUpContextMenu([menu, position]) macOS Windows

Pops up the context menu of the tray icon. When menu is passed, the menu will be shown instead of the tray icon’s context menu.

The position is only available on Windows, and it is (0, 0) by default.

tray.setContextMenu(menu)

Sets the context menu for this icon.

tray.getBounds() macOS Windows

Returns Rectangle

The bounds of this tray icon as Object.

tray.isDestroyed()

Returns Boolean - Whether the tray icon is destroyed.


webContents

Render and control web pages.

Process: Main

webContents is an EventEmitter. It is responsible for rendering and controlling a web page and is a property of the BrowserWindow object. An example of accessing the webContents object:

const {BrowserWindow} = require('electron')

let win = new BrowserWindow({width: 800, height: 1500})
win.loadURL('http://github.com')

let contents = win.webContents
console.log(contents)

Methods

These methods can be accessed from the webContents module:

const {webContents} = require('electron')
console.log(webContents)

webContents.getAllWebContents()

Returns WebContents[] - An array of all WebContents instances. This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages.

webContents.getFocusedWebContents()

Returns WebContents - The web contents that is focused in this application, otherwise returns null.

webContents.fromId(id)

Returns WebContents - A WebContents instance with the given ID.

Class: WebContents

Render and control the contents of a BrowserWindow instance.

Process: Main

Instance Events

Event: ‘did-finish-load’

Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the onload event was dispatched.

Event: ‘did-fail-load’

Returns:

This event is like did-finish-load but emitted when the load failed or was cancelled, e.g. window.stop() is invoked. The full list of error codes and their meaning is available here.

Event: ‘did-frame-finish-load’

Returns:

Emitted when a frame has done navigation.

Event: ‘did-start-loading’

Corresponds to the points in time when the spinner of the tab started spinning.

Event: ‘did-stop-loading’

Corresponds to the points in time when the spinner of the tab stopped spinning.

Event: ‘did-get-response-details’

Returns:

Emitted when details regarding a requested resource are available. status indicates the socket connection to download the resource.

Event: ‘did-get-redirect-request’

Returns:

Emitted when a redirect is received while requesting a resource.

Event: ‘dom-ready’

Returns:

Emitted when the document in the given frame is loaded.

Event: ‘page-favicon-updated’

Returns:

Emitted when page receives favicon urls.

Event: ‘new-window’

Returns:

Emitted when the page requests to open a new window for a url. It could be requested by window.open or an external link like <a target='_blank'>.

By default a new BrowserWindow will be created for the url.

Calling event.preventDefault() will prevent Electron from automatically creating a new BrowserWindow. If you call event.preventDefault() and manually create a new BrowserWindow then you must set event.newGuest to reference the new BrowserWindow instance, failing to do so may result in unexpected behavior. For example:

myBrowserWindow.webContents.on('new-window', (event, url) => {
  event.preventDefault()
  const win = new BrowserWindow({show: false})
  win.once('ready-to-show', () => win.show())
  win.loadURL(url)
  event.newGuest = win
})

Event: ‘will-navigate’

Returns:

Emitted when a user or the page wants to start navigation. It can happen when the window.location object is changed or a user clicks a link in the page.

This event will not emit when the navigation is started programmatically with APIs like webContents.loadURL and webContents.back.

It is also not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.

Calling event.preventDefault() will prevent the navigation.

Event: ‘did-navigate’

Returns:

Emitted when a navigation is done.

This event is not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.

Event: ‘did-navigate-in-page’

Returns:

Emitted when an in-page navigation happened.

When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM hashchange event is triggered.

Event: ‘crashed’

Returns:

Emitted when the renderer process crashes or is killed.

Event: ‘plugin-crashed’

Returns:

Emitted when a plugin process has crashed.

Event: ‘destroyed’

Emitted when webContents is destroyed.

Event: ‘before-input-event’

Returns:

Emitted before dispatching the keydown and keyup events in the page. Calling event.preventDefault will prevent the page keydown/keyup events from being dispatched.

Event: ‘devtools-opened’

Emitted when DevTools is opened.

Event: ‘devtools-closed’

Emitted when DevTools is closed.

Event: ‘devtools-focused’

Emitted when DevTools is focused / opened.

Event: ‘certificate-error’

Returns:

Emitted when failed to verify the certificate for url.

The usage is the same with the certificate-error event of app.

Event: ‘select-client-certificate’

Returns:

Emitted when a client certificate is requested.

The usage is the same with the select-client-certificate event of app.

Event: ‘login’

Returns:

Emitted when webContents wants to do basic auth.

The usage is the same with the login event of app.

Event: ‘found-in-page’

Returns:

Emitted when a result is available for [webContents.findInPage] request.

Event: ‘media-started-playing’

Emitted when media starts playing.

Event: ‘media-paused’

Emitted when media is paused or done playing.

Event: ‘did-change-theme-color’

Emitted when a page’s theme color changes. This is usually due to encountering a meta tag:

<meta name='theme-color' content='#ff0000'>

Event: ‘update-target-url’

Returns:

Emitted when mouse moves over a link or the keyboard moves the focus to a link.

Event: ‘cursor-changed’

Returns:

Emitted when the cursor’s type changes. The type parameter can be default, crosshair, pointer, text, wait, help, e-resize, n-resize, ne-resize, nw-resize, s-resize, se-resize, sw-resize, w-resize, ns-resize, ew-resize, nesw-resize, nwse-resize, col-resize, row-resize, m-panning, e-panning, n-panning, ne-panning, nw-panning, s-panning, se-panning, sw-panning, w-panning, move, vertical-text, cell, context-menu, alias, progress, nodrop, copy, none, not-allowed, zoom-in, zoom-out, grab, grabbing, custom.

If the type parameter is custom, the image parameter will hold the custom cursor image in a NativeImage, and scale, size and hotspot will hold additional information about the custom cursor.

Event: ‘context-menu’

Returns:

Emitted when there is a new context menu that needs to be handled.

Event: ‘select-bluetooth-device’

Returns:

Emitted when bluetooth device needs to be selected on call to navigator.bluetooth.requestDevice. To use navigator.bluetooth api webBluetooth should be enabled. If event.preventDefault is not called, first available device will be selected. callback should be called with deviceId to be selected, passing empty string to callback will cancel the request.

const {app, webContents} = require('electron')
app.commandLine.appendSwitch('enable-web-bluetooth')

app.on('ready', () => {
  webContents.on('select-bluetooth-device', (event, deviceList, callback) => {
    event.preventDefault()
    let result = deviceList.find((device) => {
      return device.deviceName === 'test'
    })
    if (!result) {
      callback('')
    } else {
      callback(result.deviceId)
    }
  })
})

Event: ‘paint’

Returns:

Emitted when a new frame is generated. Only the dirty area is passed in the buffer.

const {BrowserWindow} = require('electron')

let win = new BrowserWindow({webPreferences: {offscreen: true}})
win.webContents.on('paint', (event, dirty, image) => {
  // updateBitmap(dirty, image.getBitmap())
})
win.loadURL('http://github.com')

Event: ‘devtools-reload-page’

Emitted when the devtools window instructs the webContents to reload

Event: ‘will-attach-webview’

Returns:

Emitted when a <webview>’s web contents is being attached to this web contents. Calling event.preventDefault() will destroy the guest page.

This event can be used to configure webPreferences for the webContents of a <webview> before it’s loaded, and provides the ability to set settings that can’t be set via <webview> attributes.

Instance Methods

contents.loadURL(url[, options])

Loads the url in the window. The url must contain the protocol prefix, e.g. the http:// or file://. If the load should bypass http cache then use the pragma header to achieve it.

const {webContents} = require('electron')
const options = {extraHeaders: 'pragma: no-cache\n'}
webContents.loadURL('https://github.com', options)

contents.downloadURL(url)

Initiates a download of the resource at url without navigating. The will-download event of session will be triggered.

contents.getURL()

Returns String - The URL of the current web page.

const {BrowserWindow} = require('electron')
let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('http://github.com')

let currentURL = win.webContents.getURL()
console.log(currentURL)

contents.getTitle()

Returns String - The title of the current web page.

contents.isDestroyed()

Returns Boolean - Whether the web page is destroyed.

contents.isFocused()

Returns Boolean - Whether the web page is focused.

contents.isLoading()

Returns Boolean - Whether web page is still loading resources.

contents.isLoadingMainFrame()

Returns Boolean - Whether the main frame (and not just iframes or frames within it) is still loading.

contents.isWaitingForResponse()

Returns Boolean - Whether the web page is waiting for a first-response from the main resource of the page.

contents.stop()

Stops any pending navigation.

contents.reload()

Reloads the current web page.

contents.reloadIgnoringCache()

Reloads current page and ignores cache.

contents.canGoBack()

Returns Boolean - Whether the browser can go back to previous web page.

contents.canGoForward()

Returns Boolean - Whether the browser can go forward to next web page.

contents.canGoToOffset(offset)

Returns Boolean - Whether the web page can go to offset.

contents.clearHistory()

Clears the navigation history.

contents.goBack()

Makes the browser go back a web page.

contents.goForward()

Makes the browser go forward a web page.

contents.goToIndex(index)

Navigates browser to the specified absolute web page index.

contents.goToOffset(offset)

Navigates to the specified offset from the “current entry”.

contents.isCrashed()

Returns Boolean - Whether the renderer process has crashed.

contents.setUserAgent(userAgent)

Overrides the user agent for this web page.

contents.getUserAgent()

Returns String - The user agent for this web page.

contents.insertCSS(css)

Injects CSS into the current web page.

contents.executeJavaScript(code[, userGesture, callback])

Returns Promise - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise.

Evaluates code in page.

In the browser window some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. Setting userGesture to true will remove this limitation.

If the result of the executed code is a promise the callback result will be the resolved value of the promise. We recommend that you use the returned Promise to handle code that results in a Promise.

contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true)
  .then((result) => {
    console.log(result) // Will be the JSON object from the fetch call
  })

contents.setAudioMuted(muted)

Mute the audio on the current web page.

contents.isAudioMuted()

Returns Boolean - Whether this page has been muted.

contents.setZoomFactor(factor)

Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0.

contents.getZoomFactor(callback)

Sends a request to get current zoom factor, the callback will be called with callback(zoomFactor).

contents.setZoomLevel(level)

Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively.

contents.getZoomLevel(callback)

Sends a request to get current zoom level, the callback will be called with callback(zoomLevel).

contents.setZoomLevelLimits(minimumLevel, maximumLevel)

Deprecated: Call setVisualZoomLevelLimits instead to set the visual zoom level limits. This method will be removed in Electron 2.0.

contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)

Sets the maximum and minimum pinch-to-zoom level.

contents.setLayoutZoomLevelLimits(minimumLevel, maximumLevel)

Sets the maximum and minimum layout-based (i.e. non-visual) zoom level.

contents.undo()

Executes the editing command undo in web page.

contents.redo()

Executes the editing command redo in web page.

contents.cut()

Executes the editing command cut in web page.

contents.copy()

Executes the editing command copy in web page.

contents.copyImageAt(x, y)

Copy the image at the given position to the clipboard.

contents.paste()

Executes the editing command paste in web page.

contents.pasteAndMatchStyle()

Executes the editing command pasteAndMatchStyle in web page.

contents.delete()

Executes the editing command delete in web page.

contents.selectAll()

Executes the editing command selectAll in web page.

contents.unselect()

Executes the editing command unselect in web page.

contents.replace(text)

Executes the editing command replace in web page.

contents.replaceMisspelling(text)

Executes the editing command replaceMisspelling in web page.

contents.insertText(text)

Inserts text to the focused element.

contents.findInPage(text[, options])

Starts a request to find all matches for the text in the web page and returns an Integer representing the request id used for the request. The result of the request can be obtained by subscribing to found-in-page event.

contents.stopFindInPage(action)

Stops any findInPage request for the webContents with the provided action.

const {webContents} = require('electron')
webContents.on('found-in-page', (event, result) => {
  if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
})

const requestId = webContents.findInPage('api')
console.log(requestId)

contents.capturePage([rect, ]callback)

Captures a snapshot of the page within rect. Upon completion callback will be called with callback(image). The image is an instance of NativeImage that stores data of the snapshot. Omitting rect will capture the whole visible page.

contents.hasServiceWorker(callback)

Checks if any ServiceWorker is registered and returns a boolean as response to callback.

contents.unregisterServiceWorker(callback)

Unregisters any ServiceWorker if present and returns a boolean as response to callback when the JS promise is fulfilled or false when the JS promise is rejected.

contents.print([options])

Prints window’s web page. When silent is set to true, Electron will pick up system’s default printer and default settings for printing.

Calling window.print() in web page is equivalent to calling webContents.print({silent: false, printBackground: false}).

Use page-break-before: always; CSS style to force to print to a new page.

contents.printToPDF(options, callback)

Prints window’s web page as PDF with Chromium’s preview printing custom settings.

The callback will be called with callback(error, data) on completion. The data is a Buffer that contains the generated PDF data.

The landscape will be ignored if @page CSS at-rule is used in the web page.

By default, an empty options will be regarded as:

{
  marginsType: 0,
  printBackground: false,
  printSelectionOnly: false,
  landscape: false
}

Use page-break-before: always; CSS style to force to print to a new page.

An example of webContents.printToPDF:

const {BrowserWindow} = require('electron')
const fs = require('fs')

let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('http://github.com')

win.webContents.on('did-finish-load', () => {
  // Use default printing options
  win.webContents.printToPDF({}, (error, data) => {
    if (error) throw error
    fs.writeFile('/tmp/print.pdf', data, (error) => {
      if (error) throw error
      console.log('Write PDF successfully.')
    })
  })
})

contents.addWorkSpace(path)

Adds the specified path to DevTools workspace. Must be used after DevTools creation:

const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.webContents.on('devtools-opened', () => {
  win.webContents.addWorkSpace(__dirname)
})

contents.removeWorkSpace(path)

Removes the specified path from DevTools workspace.

contents.openDevTools([options])

Opens the devtools.

contents.closeDevTools()

Closes the devtools.

contents.isDevToolsOpened()

Returns Boolean - Whether the devtools is opened.

contents.isDevToolsFocused()

Returns Boolean - Whether the devtools view is focused .

contents.toggleDevTools()

Toggles the developer tools.

contents.inspectElement(x, y)

Starts inspecting element at position (x, y).

contents.inspectServiceWorker()

Opens the developer tools for the service worker context.

contents.send(channel[, arg1][, arg2][, ...])

Send an asynchronous message to renderer process via channel, you can also send arbitrary arguments. Arguments will be serialized in JSON internally and hence no functions or prototype chain will be included.

The renderer process can handle the message by listening to channel with the ipcRenderer module.

An example of sending messages from the main process to the renderer process:

// In the main process.
const {app, BrowserWindow} = require('electron')
let win = null

app.on('ready', () => {
  win = new BrowserWindow({width: 800, height: 600})
  win.loadURL(`file://${__dirname}/index.html`)
  win.webContents.on('did-finish-load', () => {
    win.webContents.send('ping', 'whoooooooh!')
  })
})
<!-- index.html -->
<html>
<body>
  <script>
    require('electron').ipcRenderer.on('ping', (event, message) => {
      console.log(message)  // Prints 'whoooooooh!'
    })
  </script>
</body>
</html>

contents.enableDeviceEmulation(parameters)

Enable device emulation with the given parameters.

contents.disableDeviceEmulation()

Disable device emulation enabled by webContents.enableDeviceEmulation.

contents.sendInputEvent(event)

Sends an input event to the page.

For keyboard events, the event object also have following properties:

For mouse events, the event object also have following properties:

For the mouseWheel event, the event object also have following properties:

contents.beginFrameSubscription([onlyDirty ,]callback)

Begin subscribing for presentation events and captured frames, the callback will be called with callback(frameBuffer, dirtyRect) when there is a presentation event.

The frameBuffer is a Buffer that contains raw pixel data. On most machines, the pixel data is effectively stored in 32bit BGRA format, but the actual representation depends on the endianness of the processor (most modern processors are little-endian, on machines with big-endian processors the data is in 32bit ARGB format).

The dirtyRect is an object with x, y, width, height properties that describes which part of the page was repainted. If onlyDirty is set to true, frameBuffer will only contain the repainted area. onlyDirty defaults to false.

contents.endFrameSubscription()

End subscribing for frame presentation events.

contents.startDrag(item)

Sets the item as dragging item for current drag-drop operation, file is the absolute path of the file to be dragged, and icon is the image showing under the cursor when dragging.

contents.savePage(fullPath, saveType, callback)

Returns Boolean - true if the process of saving page has been initiated successfully.

const {BrowserWindow} = require('electron')
let win = new BrowserWindow()

win.loadURL('https://github.com')

win.webContents.on('did-finish-load', () => {
  win.webContents.savePage('/tmp/test.html', 'HTMLComplete', (error) => {
    if (!error) console.log('Save page successfully')
  })
})

contents.showDefinitionForSelection() macOS

Shows pop-up dictionary that searches the selected word on the page.

contents.setSize(options)

Set the size of the page. This is only supported for <webview> guest contents.

contents.isOffscreen()

Returns Boolean - Indicates whether offscreen rendering is enabled.

contents.startPainting()

If offscreen rendering is enabled and not painting, start painting.

contents.stopPainting()

If offscreen rendering is enabled and painting, stop painting.

contents.isPainting()

Returns Boolean - If offscreen rendering is enabled returns whether it is currently painting.

contents.setFrameRate(fps)

If offscreen rendering is enabled sets the frame rate to the specified number. Only values between 1 and 60 are accepted.

contents.getFrameRate()

Returns Integer - If offscreen rendering is enabled returns the current frame rate.

contents.invalidate()

Schedules a full repaint of the window this web contents is in.

If offscreen rendering is enabled invalidates the frame and generates a new one through the 'paint' event.

Instance Properties

contents.id

A Integer representing the unique ID of this WebContents.

contents.session

A Session object (session) used by this webContents.

contents.hostWebContents

A WebContents instance that might own this WebContents.

contents.devToolsWebContents

A WebContents of DevTools for this WebContents.

Note: Users should never store this object because it may become null when the DevTools has been closed.

contents.debugger

A Debugger instance for this webContents.


webFrame

Customize the rendering of the current web page.

Process: Renderer

An example of zooming current page to 200%.

const {webFrame} = require('electron')

webFrame.setZoomFactor(2)

Methods

The webFrame module has the following methods:

webFrame.setZoomFactor(factor)

Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0.

webFrame.getZoomFactor()

Returns Number - The current zoom factor.

webFrame.setZoomLevel(level)

Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively.

webFrame.getZoomLevel()

Returns Number - The current zoom level.

webFrame.setZoomLevelLimits(minimumLevel, maximumLevel)

Deprecated: Call setVisualZoomLevelLimits instead to set the visual zoom level limits. This method will be removed in Electron 2.0.

webFrame.setVisualZoomLevelLimits(minimumLevel, maximumLevel)

Sets the maximum and minimum pinch-to-zoom level.

webFrame.setLayoutZoomLevelLimits(minimumLevel, maximumLevel)

Sets the maximum and minimum layout-based (i.e. non-visual) zoom level.

webFrame.setSpellCheckProvider(language, autoCorrectWord, provider)

Sets a provider for spell checking in input fields and text areas.

The provider must be an object that has a spellCheck method that returns whether the word passed is correctly spelled.

An example of using node-spellchecker as provider:

const {webFrame} = require('electron')
webFrame.setSpellCheckProvider('en-US', true, {
  spellCheck (text) {
    return !(require('spellchecker').isMisspelled(text))
  }
})

webFrame.registerURLSchemeAsSecure(scheme)

Registers the scheme as secure scheme.

Secure schemes do not trigger mixed content warnings. For example, https and data are secure schemes because they cannot be corrupted by active network attackers.

webFrame.registerURLSchemeAsBypassingCSP(scheme)

Resources will be loaded from this scheme regardless of the current page’s Content Security Policy.

webFrame.registerURLSchemeAsPrivileged(scheme[, options])

Registers the scheme as secure, bypasses content security policy for resources, allows registering ServiceWorker and supports fetch API.

Specify an option with the value of false to omit it from the registration. An example of registering a privileged scheme, without bypassing Content Security Policy:

const {webFrame} = require('electron')
webFrame.registerURLSchemeAsPrivileged('foo', { bypassCSP: false })

webFrame.insertText(text)

Inserts text to the focused element.

webFrame.executeJavaScript(code[, userGesture, callback])

Evaluates code in page.

In the browser window some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. Setting userGesture to true will remove this limitation.

webFrame.getResourceUsage()

Returns Object:

Returns an object describing usage information of Blink’s internal memory caches.

const {webFrame} = require('electron')
console.log(webFrame.getResourceUsage())

This will generate:

{
  images: {
    count: 22,
    size: 2549,
    liveSize: 2542
  },
  cssStyleSheets: { /* same with "images" */ },
  xslStyleSheets: { /* same with "images" */ },
  fonts: { /* same with "images" */ },
  other: { /* same with "images" */ }
}

webFrame.clearCache()

Attempts to free memory that is no longer being used (like images from a previous navigation).

Note that blindly calling this method probably makes Electron slower since it will have to refill these emptied caches, you should only call it if an event in your app has occurred that makes you think your page is actually using less memory (i.e. you have navigated from a super heavy page to a mostly empty one, and intend to stay there).


Class: WebRequest

Intercept and modify the contents of a request at various stages of its lifetime.

Process: Main

Instances of the WebRequest class are accessed by using the webRequest property of a Session.

The methods of WebRequest accept an optional filter and a listener. The listener will be called with listener(details) when the API’s event has happened. The details object describes the request. Passing null as listener will unsubscribe from the event.

The filter object has a urls property which is an Array of URL patterns that will be used to filter out the requests that do not match the URL patterns. If the filter is omitted then all requests will be matched.

For certain events the listener is passed with a callback, which should be called with a response object when listener has done its work.

An example of adding User-Agent header for requests:

const {session} = require('electron')

// Modify the user agent for all requests to the following urls.
const filter = {
  urls: ['https://*.github.com/*', '*://electron.github.io']
}

session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
  details.requestHeaders['User-Agent'] = 'MyAgent'
  callback({cancel: false, requestHeaders: details.requestHeaders})
})

Instance Methods

The following methods are available on instances of WebRequest:

webRequest.onBeforeRequest([filter, ]listener)

The listener will be called with listener(details, callback) when a request is about to occur.

The uploadData is an array of UploadData objects.

The callback has to be called with an response object.

webRequest.onBeforeSendHeaders([filter, ]listener)

The listener will be called with listener(details, callback) before sending an HTTP request, once the request headers are available. This may occur after a TCP connection is made to the server, but before any http data is sent.

The callback has to be called with an response object.

webRequest.onSendHeaders([filter, ]listener)

The listener will be called with listener(details) just before a request is going to be sent to the server, modifications of previous onBeforeSendHeaders response are visible by the time this listener is fired.

webRequest.onHeadersReceived([filter, ]listener)

The listener will be called with listener(details, callback) when HTTP response headers of a request have been received.

The callback has to be called with an response object.

webRequest.onResponseStarted([filter, ]listener)

The listener will be called with listener(details) when first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available.

webRequest.onBeforeRedirect([filter, ]listener)

The listener will be called with listener(details) when a server initiated redirect is about to occur.

webRequest.onCompleted([filter, ]listener)

The listener will be called with listener(details) when a request is completed.

webRequest.onErrorOccurred([filter, ]listener)

The listener will be called with listener(details) when an error occurs.


<webview> Tag

Display external web content in an isolated frame and process.

Use the webview tag to embed ‘guest’ content (such as web pages) in your Electron app. The guest content is contained within the webview container. An embedded page within your app controls how the guest content is laid out and rendered.

Unlike an iframe, the webview runs in a separate process than your app. It doesn’t have the same permissions as your web page and all interactions between your app and embedded content will be asynchronous. This keeps your app safe from the embedded content.

For security purposes, webview can only be used in BrowserWindows that have nodeIntegration enabled.

Example

To embed a web page in your app, add the webview tag to your app’s embedder page (this is the app page that will display the guest content). In its simplest form, the webview tag includes the src of the web page and css styles that control the appearance of the webview container:

<webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview>

If you want to control the guest content in any way, you can write JavaScript that listens for webview events and responds to those events using the webview methods. Here’s sample code with two event listeners: one that listens for the web page to start loading, the other for the web page to stop loading, and displays a “loading…” message during the load time:

<script>
  onload = () => {
    const webview = document.querySelector('webview')
    const indicator = document.querySelector('.indicator')

    const loadstart = () => {
      indicator.innerText = 'loading...'
    }

    const loadstop = () => {
      indicator.innerText = ''
    }

    webview.addEventListener('did-start-loading', loadstart)
    webview.addEventListener('did-stop-loading', loadstop)
  }
</script>

CSS Styling Notes

Please note that the webview tag’s style uses display:flex; internally to ensure the child object element fills the full height and width of its webview container when used with traditional and flexbox layouts (since v0.36.11). Please do not overwrite the default display:flex; CSS property, unless specifying display:inline-flex; for inline layout.

webview has issues being hidden using the hidden attribute or using display: none;. It can cause unusual rendering behaviour within its child browserplugin object and the web page is reloaded, when the webview is un-hidden, as opposed to just becoming visible again. The recommended approach is to hide the webview using CSS by zeroing the width & height and allowing the element to shrink to the 0px dimensions via flex.

<style>
  webview {
    display:inline-flex;
    width:640px;
    height:480px;
  }
  webview.hide {
    flex: 0 1;
    width: 0px;
    height: 0px;
  }
</style>

Tag Attributes

The webview tag has the following attributes:

src

<webview src="https://www.github.com/"></webview>

Returns the visible URL. Writing to this attribute initiates top-level navigation.

Assigning src its own value will reload the current page.

The src attribute can also accept data URLs, such as data:text/plain,Hello, world!.

autosize

<webview src="https://www.github.com/" autosize minwidth="576" minheight="432"></webview>

When this attribute is present the webview container will automatically resize within the bounds specified by the attributes minwidth, minheight, maxwidth, and maxheight. These constraints do not impact the webview unless autosize is enabled. When autosize is enabled, the webview container size cannot be less than the minimum values or greater than the maximum.

nodeintegration

<webview src="http://www.google.com/" nodeintegration></webview>

When this attribute is present the guest page in webview will have node integration and can use node APIs like require and process to access low level system resources. Node integration is disabled by default in the guest page.

plugins

<webview src="https://www.github.com/" plugins></webview>

When this attribute is present the guest page in webview will be able to use browser plugins. Plugins are disabled by default.

preload

<webview src="https://www.github.com/" preload="./test.js"></webview>

Specifies a script that will be loaded before other scripts run in the guest page. The protocol of script’s URL must be either file: or asar:, because it will be loaded by require in guest page under the hood.

When the guest page doesn’t have node integration this script will still have access to all Node APIs, but global objects injected by Node will be deleted after this script has finished executing.

httpreferrer

<webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview>

Sets the referrer URL for the guest page.

useragent

<webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>

Sets the user agent for the guest page before the page is navigated to. Once the page is loaded, use the setUserAgent method to change the user agent.

disablewebsecurity

<webview src="https://www.github.com/" disablewebsecurity></webview>

When this attribute is present the guest page will have web security disabled. Web security is enabled by default.

partition

<webview src="https://github.com" partition="persist:github"></webview>
<webview src="http://electron.atom.io" partition="electron"></webview>

Sets the session used by the page. If partition starts with persist:, the page will use a persistent session available to all pages in the app with the same partition. if there is no persist: prefix, the page will use an in-memory session. By assigning the same partition, multiple pages can share the same session. If the partition is unset then default session of the app will be used.

This value can only be modified before the first navigation, since the session of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception.

allowpopups

<webview src="https://www.github.com/" allowpopups></webview>

When this attribute is present the guest page will be allowed to open new windows. Popups are disabled by default.

webpreferences

<webview src="https://github.com" webpreferences="allowRunningInsecureContent, javascript=no"></webview>

A list of strings which specifies the web preferences to be set on the webview, separated by ,. The full list of supported preference strings can be found in BrowserWindow.

The string follows the same format as the features string in window.open. A name by itself is given a true boolean value. A preference can be set to another value by including an =, followed by the value. Special values yes and 1 are interpreted as true, while no and 0 are interpreted as false.

blinkfeatures

<webview src="https://www.github.com/" blinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>

A list of strings which specifies the blink features to be enabled separated by ,. The full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.

disableblinkfeatures

<webview src="https://www.github.com/" disableblinkfeatures="PreciseMemoryInfo, CSSVariables"></webview>

A list of strings which specifies the blink features to be disabled separated by ,. The full list of supported feature strings can be found in the RuntimeEnabledFeatures.json5 file.

guestinstance

<webview src="https://www.github.com/" guestinstance="3"></webview>

A value that links the webview to a specific webContents. When a webview first loads a new webContents is created and this attribute is set to its instance identifier. Setting this attribute on a new or existing webview connects it to the existing webContents that currently renders in a different webview.

The existing webview will see the destroy event and will then create a new webContents when a new url is loaded.

disableguestresize

<webview src="https://www.github.com/" disableguestresize></webview>

When this attribute is present the webview contents will be prevented from resizing when the webview element itself is resized.

This can be used in combination with webContents.setSize to manually resize the webview contents in reaction to a window size change. This can make resizing faster compared to relying on the webview element bounds to automatically resize the contents.

const {webContents} = require('electron')

// We assume that `win` points to a `BrowserWindow` instance containing a
// `<webview>` with `disableguestresize`.

win.on('resize', () => {
  const [width, height] = win.getContentSize()
  for (let wc of webContents.getAllWebContents()) {
    // Check if `wc` belongs to a webview in the `win` window.
    if (wc.hostWebContents &&
        wc.hostWebContents.id === win.webContents.id) {
      wc.setSize({
        normal: {
          width: width,
          height: height
        }
      })
    }
  }
})

Methods

The webview tag has the following methods:

Note: The webview element must be loaded before using the methods.

Example

const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', () => {
  webview.openDevTools()
})

<webview>.loadURL(url[, options])

Loads the url in the webview, the url must contain the protocol prefix, e.g. the http:// or file://.

<webview>.getURL()

Returns String - The URL of guest page.

<webview>.getTitle()

Returns String - The title of guest page.

<webview>.isLoading()

Returns Boolean - Whether guest page is still loading resources.

<webview>.isWaitingForResponse()

Returns Boolean - Whether the guest page is waiting for a first-response for the main resource of the page.

<webview>.stop()

Stops any pending navigation.

<webview>.reload()

Reloads the guest page.

<webview>.reloadIgnoringCache()

Reloads the guest page and ignores cache.

<webview>.canGoBack()

Returns Boolean - Whether the guest page can go back.

<webview>.canGoForward()

Returns Boolean - Whether the guest page can go forward.

<webview>.canGoToOffset(offset)

Returns Boolean - Whether the guest page can go to offset.

<webview>.clearHistory()

Clears the navigation history.

<webview>.goBack()

Makes the guest page go back.

<webview>.goForward()

Makes the guest page go forward.

<webview>.goToIndex(index)

Navigates to the specified absolute index.

<webview>.goToOffset(offset)

Navigates to the specified offset from the “current entry”.

<webview>.isCrashed()

Returns Boolean - Whether the renderer process has crashed.

<webview>.setUserAgent(userAgent)

Overrides the user agent for the guest page.

<webview>.getUserAgent()

Returns String - The user agent for guest page.

<webview>.insertCSS(css)

Injects CSS into the guest page.

<webview>.executeJavaScript(code, userGesture, callback)

Evaluates code in page. If userGesture is set, it will create the user gesture context in the page. HTML APIs like requestFullScreen, which require user action, can take advantage of this option for automation.

<webview>.openDevTools()

Opens a DevTools window for guest page.

<webview>.closeDevTools()

Closes the DevTools window of guest page.

<webview>.isDevToolsOpened()

Returns Boolean - Whether guest page has a DevTools window attached.

<webview>.isDevToolsFocused()

Returns Boolean - Whether DevTools window of guest page is focused.

<webview>.inspectElement(x, y)

Starts inspecting element at position (x, y) of guest page.

<webview>.inspectServiceWorker()

Opens the DevTools for the service worker context present in the guest page.

<webview>.setAudioMuted(muted)

Set guest page muted.

<webview>.isAudioMuted()

Returns Boolean - Whether guest page has been muted.

<webview>.undo()

Executes editing command undo in page.

<webview>.redo()

Executes editing command redo in page.

<webview>.cut()

Executes editing command cut in page.

<webview>.copy()

Executes editing command copy in page.

<webview>.paste()

Executes editing command paste in page.

<webview>.pasteAndMatchStyle()

Executes editing command pasteAndMatchStyle in page.

<webview>.delete()

Executes editing command delete in page.

<webview>.selectAll()

Executes editing command selectAll in page.

<webview>.unselect()

Executes editing command unselect in page.

<webview>.replace(text)

Executes editing command replace in page.

<webview>.replaceMisspelling(text)

Executes editing command replaceMisspelling in page.

<webview>.insertText(text)

Inserts text to the focused element.

<webview>.findInPage(text[, options])

Starts a request to find all matches for the text in the web page and returns an Integer representing the request id used for the request. The result of the request can be obtained by subscribing to found-in-page event.

<webview>.stopFindInPage(action)

Stops any findInPage request for the webview with the provided action.

<webview>.print([options])

Prints webview’s web page. Same as webContents.print([options]).

<webview>.printToPDF(options, callback)

Prints webview’s web page as PDF, Same as webContents.printToPDF(options, callback).

<webview>.capturePage([rect, ]callback)

Captures a snapshot of the webview’s page. Same as webContents.capturePage([rect, ]callback).

<webview>.send(channel[, arg1][, arg2][, ...])

Send an asynchronous message to renderer process via channel, you can also send arbitrary arguments. The renderer process can handle the message by listening to the channel event with the ipcRenderer module.

See webContents.send for examples.

<webview>.sendInputEvent(event)

Sends an input event to the page.

See webContents.sendInputEvent for detailed description of event object.

<webview>.setZoomFactor(factor)

Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0.

<webview>.setZoomLevel(level)

Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively.

<webview>.showDefinitionForSelection() macOS

Shows pop-up dictionary that searches the selected word on the page.

<webview>.getWebContents()

Returns WebContents - The web contents associated with this webview.

DOM events

The following DOM events are available to the webview tag:

Event: ‘load-commit’

Returns:

Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads.

Event: ‘did-finish-load’

Fired when the navigation is done, i.e. the spinner of the tab will stop spinning, and the onload event is dispatched.

Event: ‘did-fail-load’

Returns:

This event is like did-finish-load, but fired when the load failed or was cancelled, e.g. window.stop() is invoked.

Event: ‘did-frame-finish-load’

Returns:

Fired when a frame has done navigation.

Event: ‘did-start-loading’

Corresponds to the points in time when the spinner of the tab starts spinning.

Event: ‘did-stop-loading’

Corresponds to the points in time when the spinner of the tab stops spinning.

Event: ‘did-get-response-details’

Returns:

Fired when details regarding a requested resource is available. status indicates socket connection to download the resource.

Event: ‘did-get-redirect-request’

Returns:

Fired when a redirect was received while requesting a resource.

Event: ‘dom-ready’

Fired when document in the given frame is loaded.

Event: ‘page-title-updated’

Returns:

Fired when page title is set during navigation. explicitSet is false when title is synthesized from file url.

Event: ‘page-favicon-updated’

Returns:

Fired when page receives favicon urls.

Event: ‘enter-html-full-screen’

Fired when page enters fullscreen triggered by HTML API.

Event: ‘leave-html-full-screen’

Fired when page leaves fullscreen triggered by HTML API.

Event: ‘console-message’

Returns:

Fired when the guest window logs a console message.

The following example code forwards all log messages to the embedder’s console without regard for log level or other properties.

const webview = document.querySelector('webview')
webview.addEventListener('console-message', (e) => {
  console.log('Guest page logged a message:', e.message)
})

Event: ‘found-in-page’

Returns:

Fired when a result is available for webview.findInPage request.

const webview = document.querySelector('webview')
webview.addEventListener('found-in-page', (e) => {
  webview.stopFindInPage('keepSelection')
})

const requestId = webview.findInPage('test')
console.log(requestId)

Event: ‘new-window’

Returns:

Fired when the guest page attempts to open a new browser window.

The following example code opens the new url in system’s default browser.

const {shell} = require('electron')
const webview = document.querySelector('webview')

webview.addEventListener('new-window', (e) => {
  const protocol = require('url').parse(e.url).protocol
  if (protocol === 'http:' || protocol === 'https:') {
    shell.openExternal(e.url)
  }
})

Event: ‘will-navigate’

Returns:

Emitted when a user or the page wants to start navigation. It can happen when the window.location object is changed or a user clicks a link in the page.

This event will not emit when the navigation is started programmatically with APIs like <webview>.loadURL and <webview>.back.

It is also not emitted during in-page navigation, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.

Calling event.preventDefault() does NOT have any effect.

Event: ‘did-navigate’

Returns:

Emitted when a navigation is done.

This event is not emitted for in-page navigations, such as clicking anchor links or updating the window.location.hash. Use did-navigate-in-page event for this purpose.

Event: ‘did-navigate-in-page’

Returns:

Emitted when an in-page navigation happened.

When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM hashchange event is triggered.

Event: ‘close’

Fired when the guest page attempts to close itself.

The following example code navigates the webview to about:blank when the guest attempts to close itself.

const webview = document.querySelector('webview')
webview.addEventListener('close', () => {
  webview.src = 'about:blank'
})

Event: ‘ipc-message’

Returns:

Fired when the guest page has sent an asynchronous message to embedder page.

With sendToHost method and ipc-message event you can easily communicate between guest page and embedder page:

// In embedder page.
const webview = document.querySelector('webview')
webview.addEventListener('ipc-message', (event) => {
  console.log(event.channel)
  // Prints "pong"
})
webview.send('ping')
// In guest page.
const {ipcRenderer} = require('electron')
ipcRenderer.on('ping', () => {
  ipcRenderer.sendToHost('pong')
})

Event: ‘crashed’

Fired when the renderer process is crashed.

Event: ‘gpu-crashed’

Fired when the gpu process is crashed.

Event: ‘plugin-crashed’

Returns:

Fired when a plugin process is crashed.

Event: ‘destroyed’

Fired when the WebContents is destroyed.

Event: ‘media-started-playing’

Emitted when media starts playing.

Event: ‘media-paused’

Emitted when media is paused or done playing.

Event: ‘did-change-theme-color’

Returns:

Emitted when a page’s theme color changes. This is usually due to encountering a meta tag:

<meta name='theme-color' content='#ff0000'>

Event: ‘update-target-url’

Returns:

Emitted when mouse moves over a link or the keyboard moves the focus to a link.

Event: ‘devtools-opened’

Emitted when DevTools is opened.

Event: ‘devtools-closed’

Emitted when DevTools is closed.

Event: ‘devtools-focused’

Emitted when DevTools is focused / opened.


window.open Function

Open a new window and load a URL.

When window.open is called to create a new window in a web page, a new instance of BrowserWindow will be created for the url and a proxy will be returned to window.open to let the page have limited control over it.

The proxy has limited standard functionality implemented to be compatible with traditional web pages. For full control of the new window you should create a BrowserWindow directly.

The newly created BrowserWindow will inherit the parent window’s options by default. To override inherited options you can set them in the features string.

window.open(url[, frameName][, features])

Returns BrowserWindowProxy - Creates a new window and returns an instance of BrowserWindowProxy class.

The features string follows the format of standard browser, but each feature has to be a field of BrowserWindow’s options.

Notes:

window.opener.postMessage(message, targetOrigin)

Sends a message to the parent window with the specified origin or * for no origin preference.


Technical Differences Between Electron and NW.js (formerly node-webkit)

Note: Electron was previously named Atom Shell.

Like NW.js, Electron provides a platform to write desktop applications with JavaScript and HTML and has Node integration to grant access to the low level system from web pages.

But there are also fundamental differences between the two projects that make Electron a completely separate product from NW.js:

1. Entry of Application

In NW.js the main entry point of an application is a web page. You specify a main page URL in the package.json and it is opened in a browser window as the application’s main window.

In Electron, the entry point is a JavaScript script. Instead of providing a URL directly, you manually create a browser window and load an HTML file using the API. You also need to listen to window events to decide when to quit the application.

Electron works more like the Node.js runtime. Electron’s APIs are lower level so you can use it for browser testing in place of PhantomJS.

2. Build System

In order to avoid the complexity of building all of Chromium, Electron uses libchromiumcontent to access Chromium’s Content API. libchromiumcontent is a single shared library that includes the Chromium Content module and all of its dependencies. Users don’t need a powerful machine to build Electron.

3. Node Integration

In NW.js, the Node integration in web pages requires patching Chromium to work, while in Electron we chose a different way to integrate the libuv loop with each platform’s message loop to avoid hacking Chromium. See the node_bindings code for how that was done.

4. Multi-context

If you are an experienced NW.js user, you should be familiar with the concept of Node context and web context. These concepts were invented because of how NW.js was implemented.

By using the multi-context feature of Node, Electron doesn’t introduce a new JavaScript context in web pages.

Note: NW.js has optionally supported multi-context since 0.13.


Build Instructions (Linux)

Follow the guidelines below for building Electron on Linux.

Prerequisites

On Ubuntu, install the following libraries:

$ sudo apt-get install build-essential clang libdbus-1-dev libgtk2.0-dev \
                       libnotify-dev libgnome-keyring-dev libgconf2-dev \
                       libasound2-dev libcap-dev libcups2-dev libxtst-dev \
                       libxss1 libnss3-dev gcc-multilib g++-multilib curl \
                       gperf bison

On RHEL / CentOS, install the following libraries:

$ sudo yum install clang dbus-devel gtk2-devel libnotify-devel \
                   libgnome-keyring-devel xorg-x11-server-utils libcap-devel \
                   cups-devel libXtst-devel alsa-lib-devel libXrandr-devel \
                   GConf2-devel nss-devel

On Fedora, install the following libraries:

$ sudo dnf install clang dbus-devel gtk2-devel libnotify-devel \
                   libgnome-keyring-devel xorg-x11-server-utils libcap-devel \
                   cups-devel libXtst-devel alsa-lib-devel libXrandr-devel \
                   GConf2-devel nss-devel

Other distributions may offer similar packages for installation via package managers such as pacman. Or one can compile from source code.

Getting the Code

$ git clone https://github.com/electron/electron.git

Bootstrapping

The bootstrap script will download all necessary build dependencies and create the build project files. You must have Python 2.7.x for the script to succeed. Downloading certain files can take a long time. Notice that we are using ninja to build Electron so there is no Makefile generated.

$ cd electron
$ ./script/bootstrap.py -v

Cross compilation

If you want to build for an arm target you should also install the following dependencies:

$ sudo apt-get install libc6-dev-armhf-cross linux-libc-dev-armhf-cross \
                       g++-arm-linux-gnueabihf

And to cross compile for arm or ia32 targets, you should pass the --target_arch parameter to the bootstrap.py script:

$ ./script/bootstrap.py -v --target_arch=arm

Building

If you would like to build both Release and Debug targets:

$ ./script/build.py

This script will cause a very large Electron executable to be placed in the directory out/R. The file size is in excess of 1.3 gigabytes. This happens because the Release target binary contains debugging symbols. To reduce the file size, run the create-dist.py script:

$ ./script/create-dist.py

This will put a working distribution with much smaller file sizes in the dist directory. After running the create-dist.py script, you may want to remove the 1.3+ gigabyte binary which is still in out/R.

You can also build the Debug target only:

$ ./script/build.py -c D

After building is done, you can find the electron debug binary under out/D.

Cleaning

To clean the build files:

$ npm run clean

Troubleshooting

Error While Loading Shared Libraries: libtinfo.so.5

Prebulit clang will try to link to libtinfo.so.5. Depending on the host architecture, symlink to appropriate libncurses:

$ sudo ln -s /usr/lib/libncurses.so.5 /usr/lib/libtinfo.so.5

Tests

See Build System Overview: Tests

Advanced topics

The default building configuration is targeted for major desktop Linux distributions, to build for a specific distribution or device, following information may help you.

Building libchromiumcontent locally

To avoid using the prebuilt binaries of libchromiumcontent, you can pass the --build_libchromiumcontent switch to bootstrap.py script:

$ ./script/bootstrap.py -v --build_libchromiumcontent

Note that by default the shared_library configuration is not built, so you can only build Release version of Electron if you use this mode:

$ ./script/build.py -c R

Using system clang instead of downloaded clang binaries

By default Electron is built with prebuilt clang binaries provided by Chromium project. If for some reason you want to build with the clang installed in your system, you can call bootstrap.py with --clang_dir=<path> switch. By passing it the build script will assume the clang binaries reside in <path>/bin/.

For example if you installed clang under /user/local/bin/clang:

$ ./script/bootstrap.py -v --build_libchromiumcontent --clang_dir /usr/local
$ ./script/build.py -c R

Using other compilers other than clang

To build Electron with compilers like g++, you first need to disable clang with --disable_clang switch first, and then set CC and CXX environment variables to the ones you want.

For example building with GCC toolchain:

$ env CC=gcc CXX=g++ ./script/bootstrap.py -v --build_libchromiumcontent --disable_clang
$ ./script/build.py -c R

Environment variables

Apart from CC and CXX, you can also set following environment variables to custom the building configurations:

The environment variables have to be set when executing the bootstrap.py script, it won’t work in the build.py script.


Build Instructions (macOS)

Follow the guidelines below for building Electron on macOS.

Prerequisites

If you are using the Python downloaded by Homebrew, you also need to install the following Python modules:

macOS SDK

If you’re simply developing Electron and don’t plan to redistribute your custom Electron build, you may skip this section.

For certain features (e.g. pinch-zoom) to work properly, you must target the macOS 10.10 SDK.

Official Electron builds are built with Xcode 8.2.1, which does not contain the 10.10 SDK by default. To obtain it, first download and mount the Xcode 6.4 DMG.

Then, assuming that the Xcode 6.4 DMG has been mounted at /Volumes/Xcode and that your Xcode 8.2.1 install is at /Applications/Xcode.app, run:

cp -r /Volumes/Xcode/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/

You will also need to enable Xcode to build against the 10.10 SDK:

Getting the Code

$ git clone https://github.com/electron/electron

Bootstrapping

The bootstrap script will download all necessary build dependencies and create the build project files. Notice that we’re using ninja to build Electron so there is no Xcode project generated.

$ cd electron
$ ./script/bootstrap.py -v

Building

Build both Release and Debug targets:

$ ./script/build.py

You can also only build the Debug target:

$ ./script/build.py -c D

After building is done, you can find Electron.app under out/D.

32bit Support

Electron can only be built for a 64bit target on macOS and there is no plan to support 32bit macOS in the future.

Cleaning

To clean the build files:

$ npm run clean

Tests

See Build System Overview: Tests


Build Instructions (Windows)

Follow the guidelines below for building Electron on Windows.

Prerequisites

If you don’t currently have a Windows installation, dev.microsoftedge.com has timebombed versions of Windows that you can use to build Electron.

Building Electron is done entirely with command-line scripts and cannot be done with Visual Studio. You can develop Electron with any editor but support for building with Visual Studio will come in the future.

Note: Even though Visual Studio is not used for building, it’s still required because we need the build toolchains it provides.

Getting the Code

$ git clone https://github.com/electron/electron.git

Bootstrapping

The bootstrap script will download all necessary build dependencies and create the build project files. Notice that we’re using ninja to build Electron so there is no Visual Studio project generated.

$ cd electron
$ python script\bootstrap.py -v

Building

Build both Release and Debug targets:

$ python script\build.py

You can also only build the Debug target:

$ python script\build.py -c D

After building is done, you can find electron.exe under out\D (debug target) or under out\R (release target).

32bit Build

To build for the 32bit target, you need to pass --target_arch=ia32 when running the bootstrap script:

$ python script\bootstrap.py -v --target_arch=ia32

The other building steps are exactly the same.

Visual Studio project

To generate a Visual Studio project, you can pass the --msvs parameter:

$ python script\bootstrap.py --msvs

Cleaning

To clean the build files:

$ npm run clean

Tests

See Build System Overview: Tests

Troubleshooting

Command xxxx not found

If you encountered an error like Command xxxx not found, you may try to use the VS2015 Command Prompt console to execute the build scripts.

Fatal internal compiler error: C1001

Make sure you have the latest Visual Studio update installed.

Assertion failed: ((handle))->activecnt >= 0

If building under Cygwin, you may see bootstrap.py failed with following error:

Assertion failed: ((handle))->activecnt >= 0, file src\win\pipe.c, line 1430

Traceback (most recent call last):
  File "script/bootstrap.py", line 87, in <module>
    sys.exit(main())
  File "script/bootstrap.py", line 22, in main
    update_node_modules('.')
  File "script/bootstrap.py", line 56, in update_node_modules
    execute([NPM, 'install'])
  File "/home/zcbenz/codes/raven/script/lib/util.py", line 118, in execute
    raise e
subprocess.CalledProcessError: Command '['npm.cmd', 'install']' returned non-zero exit status 3

This is caused by a bug when using Cygwin Python and Win32 Node together. The solution is to use the Win32 Python to execute the bootstrap script (assuming you have installed Python under C:\Python27):

$ /cygdrive/c/Python27/python.exe script/bootstrap.py

LNK1181: cannot open input file ‘kernel32.lib’

Try reinstalling 32bit Node.js.

Error: ENOENT, stat ‘C:\Users\USERNAME\AppData\Roaming\npm’

Simply making that directory should fix the problem:

$ mkdir ~\AppData\Roaming\npm

node-gyp is not recognized as an internal or external command

You may get this error if you are using Git Bash for building, you should use PowerShell or VS2015 Command Prompt instead.


Build System Overview

Electron uses gyp for project generation and ninja for building. Project configurations can be found in the .gyp and .gypi files.

Gyp Files

Following gyp files contain the main rules for building Electron:

Component Build

Since Chromium is quite a large project, the final linking stage can take quite a few minutes, which makes it hard for development. In order to solve this, Chromium introduced the “component build”, which builds each component as a separate shared library, making linking very quick but sacrificing file size and performance.

In Electron we took a very similar approach: for Debug builds, the binary will be linked to a shared library version of Chromium’s components to achieve fast linking time; for Release builds, the binary will be linked to the static library versions, so we can have the best possible binary size and performance.

Minimal Bootstrapping

All of Chromium’s prebuilt binaries (libchromiumcontent) are downloaded when running the bootstrap script. By default both static libraries and shared libraries will be downloaded and the final size should be between 800MB and 2GB depending on the platform.

By default, libchromiumcontent is downloaded from Amazon Web Services. If the LIBCHROMIUMCONTENT_MIRROR environment variable is set, the bootstrap script will download from it. libchromiumcontent-qiniu-mirror is a mirror for libchromiumcontent. If you have trouble in accessing AWS, you can switch the download address to it via export LIBCHROMIUMCONTENT_MIRROR=http://7xk3d2.dl1.z0.glb.clouddn.com/

If you only want to build Electron quickly for testing or development, you can download just the shared library versions by passing the --dev parameter:

$ ./script/bootstrap.py --dev
$ ./script/build.py -c D

Two-Phase Project Generation

Electron links with different sets of libraries in Release and Debug builds. gyp, however, doesn’t support configuring different link settings for different configurations.

To work around this Electron uses a gyp variable libchromiumcontent_component to control which link settings to use and only generates one target when running gyp.

Target Names

Unlike most projects that use Release and Debug as target names, Electron uses R and D instead. This is because gyp randomly crashes if there is only one Release or Debug build configuration defined, and Electron only has to generate one target at a time as stated above.

This only affects developers, if you are just building Electron for rebranding you are not affected.

Tests

Test your changes conform to the project coding style using:

$ npm run lint

Test functionality using:

$ npm test

Whenever you make changes to Electron source code, you’ll need to re-run the build before the tests:

$ npm run build && npm test

You can make the test suite run faster by isolating the specific test or block you’re currently working on using Mocha’s exclusive tests feature. Just append .only to any describe or it function call:

describe.only('some feature', function () {
  // ... only tests in this block will be run
})

Alternatively, you can use mocha’s grep option to only run tests matching the given regular expression pattern:

$ npm test -- --grep child_process

Tests that include native modules (e.g. runas) can’t be executed with the debug build (see #2558 for details), but they will work with the release build.

To run the tests with the release build use:

$ npm test -- -R

Using clang-format on C++ Code

clang-format is a tool to automatically format C/C++/Objective-C code, so that developers don’t need to worry about style issues during code reviews.

It is highly recommended to format your changed C++ code before opening pull requests, which will save you and the reviewers’ time.

You can install clang-format and git-clang-format via npm install -g clang-format.

To automatically format a file according to Electron C++ code style, simply run clang-format -i path/to/electron/file.cc. It should work on macOS/Linux/Windows.

The workflow to format your changed code:

  1. Make codes changes in Electron repository.
  2. Run git add your_changed_file.cc.
  3. Run git-clang-format, and you will probably see modifications in your_changed_file.cc, these modifications are generated from clang-format.
  4. Run git add your_changed_file.cc, and commit your change.
  5. Now the branch is ready to be opened as a pull request.

If you want to format the changed code on your latest git commit (HEAD), you can run git-clang-format HEAD~1. See git-clang-format -h for more details.

Editor Integration

You can also integrate clang-format directly into your favorite editors. For further guidance on setting up editor integration, see these pages:


Coding Style

These are the style guidelines for coding in Electron.

You can run npm run lint to show any style issues detected by cpplint and eslint.

C++ and Python

For C++ and Python, we follow Chromium’s Coding Style. You can use clang-format to format the C++ code automatically. There is also a script script/cpplint.py to check whether all files conform.

The Python version we are using now is Python 2.7.

The C++ code uses a lot of Chromium’s abstractions and types, so it’s recommended to get acquainted with them. A good place to start is Chromium’s Important Abstractions and Data Structures document. The document mentions some special types, scoped types (that automatically release their memory when going out of scope), logging mechanisms etc.

JavaScript

Naming Things

Electron APIs uses the same capitalization scheme as Node.js:

When creating a new API, it is preferred to use getters and setters instead of jQuery’s one-function style. For example, .getText() and .setText(text) are preferred to .text([text]). There is a discussion on this.


Debugging on Windows

If you experience crashes or issues in Electron that you believe are not caused by your JavaScript application, but instead by Electron itself, debugging can be a little bit tricky, especially for developers not used to native/C++ debugging. However, using Visual Studio, GitHub’s hosted Electron Symbol Server, and the Electron source code, it is fairly easy to enable step-through debugging with breakpoints inside Electron’s source code.

Requirements

Attaching to and Debugging Electron

To start a debugging session, open up PowerShell/CMD and execute your debug build of Electron, using the application to open as a parameter.

$ ./out/D/electron.exe ~/my-electron-app/

Setting Breakpoints

Then, open up Visual Studio. Electron is not built with Visual Studio and hence does not contain a project file - you can however open up the source code files “As File”, meaning that Visual Studio will open them up by themselves. You can still set breakpoints - Visual Studio will automatically figure out that the source code matches the code running in the attached process and break accordingly.

Relevant code files can be found in ./atom/ as well as in Brightray, found in ./vendor/brightray/browser and ./vendor/brightray/common. If you’re hardcore, you can also debug Chromium directly, which is obviously found in chromium_src.

Attaching

You can attach the Visual Studio debugger to a running process on a local or remote computer. After the process is running, click Debug / Attach to Process (or press CTRL+ALT+P) to open the “Attach to Process” dialog box. You can use this capability to debug apps that are running on a local or remote computer, debug multiple processes simultaneously.

If Electron is running under a different user account, select the Show processes from all users check box. Notice that depending on how many BrowserWindows your app opened, you will see multiple processes. A typical one-window app will result in Visual Studio presenting you with two Electron.exe entries - one for the main process and one for the renderer process. Since the list only gives you names, there’s currently no reliable way of figuring out which is which.

Which Process Should I Attach to?

Code executed within the main process (that is, code found in or eventually run by your main JavaScript file) as well as code called using the remote (require('electron').remote) will run inside the main process, while other code will execute inside its respective renderer process.

You can be attached to multiple programs when you are debugging, but only one program is active in the debugger at any time. You can set the active program in the Debug Location toolbar or the Processes window.

Using ProcMon to Observe a Process

While Visual Studio is fantastic for inspecting specific code paths, ProcMon’s strength is really in observing everything your application is doing with the operating system - it captures File, Registry, Network, Process, and Profiling details of processes. It attempts to log all events occurring and can be quite overwhelming, but if you seek to understand what and how your application is doing to the operating system, it can be a valuable resource.

For an introduction to ProcMon’s basic and advanced debugging features, go check out this video tutorial provided by Microsoft.


Debugging on macOS

If you experience crashes or issues in Electron that you believe are not caused by your JavaScript application, but instead by Electron itself, debugging can be a little bit tricky, especially for developers not used to native/C++ debugging. However, using lldb, and the Electron source code, it is fairly easy to enable step-through debugging with breakpoints inside Electron’s source code.

Requirements

Attaching to and Debugging Electron

To start a debugging session, open up Terminal and start lldb, passing a debug build of Electron as a parameter.

$ lldb ./out/D/Electron.app
(lldb) target create "./out/D/Electron.app"
Current executable set to './out/D/Electron.app' (x86_64).

Setting Breakpoints

LLDB is a powerful tool and supports multiple strategies for code inspection. For this basic introduction, let’s assume that you’re calling a command from JavaScript that isn’t behaving correctly - so you’d like to break on that command’s C++ counterpart inside the Electron source.

Relevant code files can be found in ./atom/ as well as in Brightray, found in ./vendor/brightray/browser and ./vendor/brightray/common. If you’re hardcore, you can also debug Chromium directly, which is obviously found in chromium_src.

Let’s assume that you want to debug app.setName(), which is defined in browser.cc as Browser::SetName(). Set the breakpoint using the breakpoint command, specifying file and line to break on:

(lldb) breakpoint set --file browser.cc --line 117
Breakpoint 1: where = Electron Framework`atom::Browser::SetName(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) + 20 at browser.cc:118, address = 0x000000000015fdb4

Then, start Electron:

(lldb) run

The app will immediately be paused, since Electron sets the app’s name on launch:

(lldb) run
Process 25244 launched: '/Users/fr/Code/electron/out/D/Electron.app/Contents/MacOS/Electron' (x86_64)
Process 25244 stopped
* thread #1: tid = 0x839a4c, 0x0000000100162db4 Electron Framework`atom::Browser::SetName(this=0x0000000108b14f20, name="Electron") + 20 at browser.cc:118, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x0000000100162db4 Electron Framework`atom::Browser::SetName(this=0x0000000108b14f20, name="Electron") + 20 at browser.cc:118
   115 	}
   116
   117 	void Browser::SetName(const std::string& name) {
-> 118 	  name_override_ = name;
   119 	}
   120
   121 	int Browser::GetBadgeCount() {
(lldb)

To show the arguments and local variables for the current frame, run frame variable (or fr v), which will show you that the app is currently setting the name to “Electron”.

(lldb) frame variable
(atom::Browser *) this = 0x0000000108b14f20
(const string &) name = "Electron": {
    [...]
}

To do a source level single step in the currently selected thread, execute step (or s). This would take you into into name_override_.empty(). To proceed and do a step over, run next (or n).

(lldb) step
Process 25244 stopped
* thread #1: tid = 0x839a4c, 0x0000000100162dcc Electron Framework`atom::Browser::SetName(this=0x0000000108b14f20, name="Electron") + 44 at browser.cc:119, queue = 'com.apple.main-thread', stop reason = step in
    frame #0: 0x0000000100162dcc Electron Framework`atom::Browser::SetName(this=0x0000000108b14f20, name="Electron") + 44 at browser.cc:119
   116
   117 	void Browser::SetName(const std::string& name) {
   118 	  name_override_ = name;
-> 119 	}
   120
   121 	int Browser::GetBadgeCount() {
   122 	  return badge_count_;

To finish debugging at this point, run process continue. You can also continue until a certain line is hit in this thread (thread until 100). This command will run the thread in the current frame till it reaches line 100 in this frame or stops if it leaves the current frame.

Now, if you open up Electron’s developer tools and call setName, you will once again hit the breakpoint.

Further Reading

LLDB is a powerful tool with a great documentation. To learn more about it, consider Apple’s debugging documentation, for instance the LLDB Command Structure Reference or the introduction to Using LLDB as a Standalone Debugger.

You can also check out LLDB’s fantastic manual and tutorial, which will explain more complex debugging scenarios.


Releasing

This document describes the process for releasing a new version of Electron.

Compile release notes

The current process is to maintain a local file, keeping track of notable changes as pull requests are merged. For examples of how to format the notes, see previous releases on the releases page.

Create a temporary branch

Create a new branch from master named release.

git checkout master
git pull
git checkout -b release

This branch is created as a precaution to prevent any merged PRs from sneaking into a release between the time the temporary release branch is created and the CI builds are complete.

Bump the version

Run the bump-version script, passing major, minor, or patch as an argument:

npm run bump-version -- patch
git push origin HEAD

This will bump the version number in several files. See this bump commit for an example.

Most releases will be patch level. Upgrades to Chrome or other major changes should use minor. For more info, see electron-versioning.

Edit the release draft

  1. Visit the releases page and you’ll see a new draft release with placeholder release notes.
  2. Edit the release and add release notes.
  3. Click ‘Save draft’. Do not click ‘Publish release’!
  4. Wait for all the builds to pass. :hourglass_flowing_sand:

Merge temporary branch

Merge the temporary back into master, without creating a merge commit:

git merge release master --no-commit
git push origin master

If this fails, rebase with master and rebuild:

git pull
git checkout release
git rebase master
git push origin HEAD

Run local debug build

Run local debug build to verify that you are actually building the version you want. Sometimes you thought you were doing a release for a new version, but you’re actually not.

npm run build
npm start

Verify the window is displaying the current updated version.

Set environment variables

You’ll need to set the following environment variables to publish a release. Ask another team member for these credentials.

You will only need to do this once.

Publish the release

This script will download the binaries and generate the node headers and the .lib linker used on Windows by node-gyp to build native modules.

npm run release

Note: Many distributions of Python still ship with old HTTPS certificates. You may see a InsecureRequestWarning, but it can be disregarded.

Delete the temporary branch

git checkout master
git branch -D release # delete local branch
git push origin :release # delete remote branch

Setting Up Symbol Server in Debugger

Debug symbols allow you to have better debugging sessions. They have information about the functions contained in executables and dynamic libraries and provide you with information to get clean call stacks. A Symbol Server allows the debugger to load the correct symbols, binaries and sources automatically without forcing users to download large debugging files. The server functions like Microsoft’s symbol server so the documentation there can be useful.

Note that because released Electron builds are heavily optimized, debugging is not always easy. The debugger will not be able to show you the content of all variables and the execution path can seem strange because of inlining, tail calls, and other compiler optimizations. The only workaround is to build an unoptimized local build.

The official symbol server URL for Electron is https://electron-symbols.githubapp.com. You cannot visit this URL directly, you must add it to the symbol path of your debugging tool. In the examples below, a local cache directory is used to avoid repeatedly fetching the PDB from the server. Replace c:\code\symbols with an appropriate cache directory on your machine.

Using the Symbol Server in Windbg

The Windbg symbol path is configured with a string value delimited with asterisk characters. To use only the Electron symbol server, add the following entry to your symbol path (Note: you can replace c:\code\symbols with any writable directory on your computer, if you’d prefer a different location for downloaded symbols):

SRV*c:\code\symbols\*https://electron-symbols.githubapp.com

Set this string as _NT_SYMBOL_PATH in the environment, using the Windbg menus, or by typing the .sympath command. If you would like to get symbols from Microsoft’s symbol server as well, you should list that first:

SRV*c:\code\symbols\*http://msdl.microsoft.com/download/symbols;SRV*c:\code\symbols\*https://electron-symbols.githubapp.com

Using the symbol server in Visual Studio

Troubleshooting: Symbols will not load

Type the following commands in Windbg to print why symbols are not loading:

> !sym noisy
> .reload /f electron.exe


Source Code Directory Structure

The source code of Electron is separated into a few parts, mostly following Chromium on the separation conventions.

You may need to become familiar with Chromium’s multi-process architecture to understand the source code better.

Structure of Source Code

Electron
├── atom/ - C++ source code.
|   ├── app/ - System entry code.
|   ├── browser/ - The frontend including the main window, UI, and all of the
|   |   main process things. This talks to the renderer to manage web pages.
|   |   ├── ui/ - Implementation of UI stuff for different platforms.
|   |   |   ├── cocoa/ - Cocoa specific source code.
|   |   |   ├── win/ - Windows GUI specific source code.
|   |   |   └── x/ - X11 specific source code.
|   |   ├── api/ - The implementation of the main process APIs.
|   |   ├── net/ - Network related code.
|   |   ├── mac/ - Mac specific Objective-C source code.
|   |   └── resources/ - Icons, platform-dependent files, etc.
|   ├── renderer/ - Code that runs in renderer process.
|   |   └── api/ - The implementation of renderer process APIs.
|   └── common/ - Code that used by both the main and renderer processes,
|       including some utility functions and code to integrate node's message
|       loop into Chromium's message loop.
|       └── api/ - The implementation of common APIs, and foundations of
|           Electron's built-in modules.
├── chromium_src/ - Source code that copied from Chromium.
├── default_app/ - The default page to show when Electron is started without
|   providing an app.
├── docs/ - Documentations.
├── lib/ - JavaScript source code.
|   ├── browser/ - Javascript main process initialization code.
|   |   └── api/ - Javascript API implementation.
|   ├── common/ - JavaScript used by both the main and renderer processes
|   |   └── api/ - Javascript API implementation.
|   └── renderer/ - Javascript renderer process initialization code.
|       └── api/ - Javascript API implementation.
├── spec/ - Automatic tests.
├── electron.gyp - Building rules of Electron.
└── common.gypi - Compiler specific settings and building rules for other
    components like `node` and `breakpad`.

Structure of Other Directories

Keeping Git Submodules Up to Date

The Electron repository has a few vendored dependencies, found in the /vendor directory. Occasionally you might see a message like this when running git status:

$ git status

	modified:   vendor/brightray (new commits)
	modified:   vendor/node (new commits)

To update these vendored dependencies, run the following command:

git submodule update --init --recursive

If you find yourself running this command often, you can create an alias for it in your ~/.gitconfig file:

[alias]
	su = submodule update --init --recursive


Upgrading Chrome Checklist

This document is meant to serve as an overview of what steps are needed on each Chrome upgrade in Electron.

These are things to do in addition to updating the Electron code for any Chrome/Node API changes.


Electron FAQ

When will Electron upgrade to latest Chrome?

The Chrome version of Electron is usually bumped within one or two weeks after a new stable Chrome version gets released. This estimate is not guaranteed and depends on the amount of work involved with upgrading.

Only the stable channel of Chrome is used. If an important fix is in beta or dev channel, we will back-port it.

For more information, please see the security introduction.

When will Electron upgrade to latest Node.js?

When a new version of Node.js gets released, we usually wait for about a month before upgrading the one in Electron. So we can avoid getting affected by bugs introduced in new Node.js versions, which happens very often.

New features of Node.js are usually brought by V8 upgrades, since Electron is using the V8 shipped by Chrome browser, the shiny new JavaScript feature of a new Node.js version is usually already in Electron.

How to share data between web pages?

To share data between web pages (the renderer processes) the simplest way is to use HTML5 APIs which are already available in browsers. Good candidates are Storage API, localStorage, sessionStorage, and IndexedDB.

Or you can use the IPC system, which is specific to Electron, to store objects in the main process as a global variable, and then to access them from the renderers through the remote property of electron module:

// In the main process.
global.sharedObject = {
  someProperty: 'default value'
}
// In page 1.
require('electron').remote.getGlobal('sharedObject').someProperty = 'new value'
// In page 2.
console.log(require('electron').remote.getGlobal('sharedObject').someProperty)

My app’s window/tray disappeared after a few minutes.

This happens when the variable which is used to store the window/tray gets garbage collected.

If you encounter this problem, the following articles may prove helpful:

If you want a quick fix, you can make the variables global by changing your code from this:

const {app, Tray} = require('electron')
app.on('ready', () => {
  const tray = new Tray('/path/to/icon.png')
  tray.setTitle('hello world')
})

to this:

const {app, Tray} = require('electron')
let tray = null
app.on('ready', () => {
  tray = new Tray('/path/to/icon.png')
  tray.setTitle('hello world')
})

I can not use jQuery/RequireJS/Meteor/AngularJS in Electron.

Due to the Node.js integration of Electron, there are some extra symbols inserted into the DOM like module, exports, require. This causes problems for some libraries since they want to insert the symbols with the same names.

To solve this, you can turn off node integration in Electron:

// In the main process.
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({
  webPreferences: {
    nodeIntegration: false
  }
})
win.show()

But if you want to keep the abilities of using Node.js and Electron APIs, you have to rename the symbols in the page before including other libraries:

<head>
<script>
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
</script>
<script type="text/javascript" src="jquery.js"></script>
</head>

require('electron').xxx is undefined.

When using Electron’s built-in module you might encounter an error like this:

> require('electron').webFrame.setZoomFactor(1.0)
Uncaught TypeError: Cannot read property 'setZoomLevel' of undefined

This is because you have the npm electron module installed either locally or globally, which overrides Electron’s built-in module.

To verify whether you are using the correct built-in module, you can print the path of the electron module:

console.log(require.resolve('electron'))

and then check if it is in the following form:

"/path/to/Electron.app/Contents/Resources/atom.asar/renderer/api/lib/exports/electron.js"

If it is something like node_modules/electron/index.js, then you have to either remove the npm electron module, or rename it.

npm uninstall electron
npm uninstall -g electron

However if your are using the built-in module but still getting this error, it is very likely you are using the module in the wrong process. For example electron.app can only be used in the main process, while electron.webFrame is only available in renderer processes.


Glossary

This page defines some terminology that is commonly used in Electron development.

ASAR

ASAR stands for Atom Shell Archive Format. An asar archive is a simple tar-like format that concatenates files into a single file. Electron can read arbitrary files from it without unpacking the whole file.

The ASAR format was created primarily to improve performance on Windows… TODO

Brightray

Brightray is a static library that makes libchromiumcontent easier to use in applications. It was created specifically for Electron, but can be used to enable Chromium’s renderer in native apps that are not based on Electron.

Brightray is a low-level dependency of Electron that does not concern the majority of Electron users.

DMG

An Apple Disk Image is a packaging format used by macOS. DMG files are commonly used for distributing application “installers”. electron-builder supports dmg as a build target.

IPC

IPC stands for Inter-Process Communication. Electron uses IPC to send serialized JSON messages between the main and renderer processes.

libchromiumcontent

A single, shared library that includes the Chromium Content module and all its dependencies (e.g., Blink, V8, etc.).

main process

The main process, commonly a file named main.js, is the entry point to every Electron app. It controls the life of the app, from open to close. It also manages native elements such as the Menu, Menu Bar, Dock, Tray, etc. The main process is responsible for creating each new renderer process in the app. The full Node API is built in.

Every app’s main process file is specified in the main property in package.json. This is how electron . knows what file to execute at startup.

See also: process, renderer process

MAS

Acronym for Apple’s Mac App Store. For details on submitting your app to the MAS, see the Mac App Store Submission Guide.

native modules

Native modules (also called addons in Node.js) are modules written in C or C++ that can be loaded into Node.js or Electron using the require() function, and used just as if they were an ordinary Node.js module. They are used primarily to provide an interface between JavaScript running in Node.js and C/C++ libraries.

Native Node modules are supported by Electron, but since Electron is very likely to use a different V8 version from the Node binary installed in your system, you have to manually specify the location of Electron’s headers when building native modules.

See also Using Native Node Modules.

NSIS

Nullsoft Scriptable Install System is a script-driven Installer authoring tool for Microsoft Windows. It is released under a combination of free software licenses, and is a widely-used alternative to commercial proprietary products like InstallShield. electron-builder supports NSIS as a build target.

process

A process is an instance of a computer program that is being executed. Electron apps that make use of the main and one or many renderer process are actually running several programs simultaneously.

In Node.js and Electron, each running process has a process object. This object is a global that provides information about, and control over, the current process. As a global, it is always available to applications without using require().

See also: main process, renderer process

renderer process

The renderer process is a browser window in your app. Unlike the main process, there can be multiple of these and each is run in a separate process. They can also be hidden.

In normal browsers, web pages usually run in a sandboxed environment and are not allowed access to native resources. Electron users, however, have the power to use Node.js APIs in web pages allowing lower level operating system interactions.

See also: process, main process

Squirrel

Squirrel is an open-source framework that enables Electron apps to update automatically as new versions are released. See the autoUpdater API for info about getting started with Squirrel.

userland

This term originated in the Unix community, where “userland” or “userspace” referred to programs that run outside of the operating system kernel. More recently, the term has been popularized in the Node and npm community to distinguish between the features available in “Node core” versus packages published to the npm registry by the much larger “user” community.

Like Node, Electron is focused on having a small set of APIs that provide all the necessary primitives for developing multi-platform desktop applications. This design philosophy allows Electron to remain a flexible tool without being overly prescriptive about how it should be used. Userland enables users to create and share tools that provide additional functionality on top of what is available in “core”.

V8

V8 is Google’s open source JavaScript engine. It is written in C++ and is used in Google Chrome, the open source browser from Google. V8 can run standalone, or can be embedded into any C++ application.

webview

webview tags are used to embed ‘guest’ content (such as external web pages) in your Electron app. They are similar to iframes, but differ in that each webview runs in a separate process. It doesn’t have the same permissions as your web page and all interactions between your app and embedded content will be asynchronous. This keeps your app safe from the embedded content.


About Electron

Electron is an open source library developed by GitHub for building cross-platform desktop applications with HTML, CSS, and JavaScript. Electron accomplishes this by combining Chromium and Node.js into a single runtime and apps can be packaged for Mac, Windows, and Linux.

Electron began in 2013 as the framework on which Atom, GitHub’s hackable text editor, would be built. The two were open sourced in the Spring of 2014.

It has since become a popular tool used by open source developers, startups, and established companies. See who is building on Electron.

Read on to learn more about the contributors and releases of Electron or get started building with Electron in the Quick Start Guide.

Core Team and Contributors

Electron is maintained by a team at GitHub as well as a group of active contributors from the community. Some of the contributors are individuals and some work at larger companies who are developing on Electron. We’re happy to add frequent contributors to the project as maintainers. Read more about contributing to Electron.

Releases

Electron releases frequently. We release when there are significant bug fixes, new APIs or are updating versions of Chromium or Node.js.

Updating Dependencies

Electron’s version of Chromium is usually updated within one or two weeks after a new stable Chromium version is released, depending on the effort involved in the upgrade.

When a new version of Node.js is released, Electron usually waits about a month before upgrading in order to bring in a more stable version.

In Electron, Node.js and Chromium share a single V8 instance—usually the version that Chromium is using. Most of the time this just works but sometimes it means patching Node.js.

Versioning

Due to the hard dependency on Node.js and Chromium, Electron is in a tricky versioning position and does not follow semver. You should therefore always reference a specific version of Electron. Read more about Electron’s versioning or see the versions currently in use.

LTS

Long term support of older versions of Electron does not currently exist. If your current version of Electron works for you, you can stay on it for as long as you’d like. If you want to make use of new features as they come in you should upgrade to a newer version.

A major update came with version v1.0.0. If you’re not yet using this version, you should read more about the v1.0.0 changes.

Core Philosophy

In order to keep Electron small (file size) and sustainable (the spread of dependencies and APIs) the project limits the scope of the core project.

For instance, Electron uses just the rendering library from Chromium rather than all of Chromium. This makes it easier to upgrade Chromium but also means some browser features found in Google Chrome do not exist in Electron.

New features added to Electron should primarily be native APIs. If a feature can be its own Node.js module, it probably should be. See the Electron tools built by the community.

History

Below are milestones in Electron’s history.

:calendar: :tada:
April 2013 Atom Shell is started.
May 2014 Atom Shell is open sourced.
April 2015 Atom Shell is re-named Electron.
May 2016 Electron releases v1.0.0.
May 2016 Electron apps compatible with Mac App Store.
August 2016 Windows Store support for Electron apps.

Accessibility

Making accessible applications is important and we’re happy to introduce new functionality to Devtron and Spectron that gives developers the opportunity to make their apps better for everyone.


Accessibility concerns in Electron applications are similar to those of websites because they’re both ultimately HTML. With Electron apps, however, you can’t use the online resources for accessibility audits because your app doesn’t have a URL to point the auditor to.

These new features bring those auditing tools to your Electron app. You can choose to add audits to your tests with Spectron or use them within DevTools with Devtron. Read on for a summary of the tools or checkout our accessibility documentation for more information.

Spectron

In the testing framework Spectron, you can now audit each window and <webview> tag in your application. For example:

app.client.auditAccessibility().then(function (audit) {
  if (audit.failed) {
    console.error(audit.message)
  }
})

You can read more about this feature in Spectron’s documentation.

Devtron

In Devtron, there is a new accessibility tab which will allow you to audit a page in your app, sort and filter the results.

devtron screenshot

Both of these tools are using the Accessibility Developer Tools library built by Google for Chrome. You can learn more about the accessibility audit rules this library uses on that repository’s wiki.

If you know of other great accessibility tools for Electron, add them to the accessibility documentation with a pull request.


Application Distribution

To distribute your app with Electron, you need to download Electron’s prebuilt binaries. Next, the folder containing your app should be named app and placed in Electron’s resources directory as shown in the following examples. Note that the location of Electron’s prebuilt binaries is indicated with electron/ in the examples below.

On macOS:

electron/Electron.app/Contents/Resources/app/
├── package.json
├── main.js
└── index.html

On Windows and Linux:

electron/resources/app
├── package.json
├── main.js
└── index.html

Then execute Electron.app (or electron on Linux, electron.exe on Windows), and Electron will start as your app. The electron directory will then be your distribution to deliver to final users.

Packaging Your App into a File

Apart from shipping your app by copying all of its source files, you can also package your app into an asar archive to avoid exposing your app’s source code to users.

To use an asar archive to replace the app folder, you need to rename the archive to app.asar, and put it under Electron’s resources directory like below, and Electron will then try to read the archive and start from it.

On macOS:

electron/Electron.app/Contents/Resources/
└── app.asar

On Windows and Linux:

electron/resources/
└── app.asar

More details can be found in Application packaging.

Rebranding with Downloaded Binaries

After bundling your app into Electron, you will want to rebrand Electron before distributing it to users.

Windows

You can rename electron.exe to any name you like, and edit its icon and other information with tools like rcedit.

macOS

You can rename Electron.app to any name you want, and you also have to rename the CFBundleDisplayName, CFBundleIdentifier and CFBundleName fields in the following files:

You can also rename the helper app to avoid showing Electron Helper in the Activity Monitor, but make sure you have renamed the helper app’s executable file’s name.

The structure of a renamed app would be like:

MyApp.app/Contents
├── Info.plist
├── MacOS/
│   └── MyApp
└── Frameworks/
    ├── MyApp Helper EH.app
    |   ├── Info.plist
    |   └── MacOS/
    |       └── MyApp Helper EH
    ├── MyApp Helper NP.app
    |   ├── Info.plist
    |   └── MacOS/
    |       └── MyApp Helper NP
    └── MyApp Helper.app
        ├── Info.plist
        └── MacOS/
            └── MyApp Helper

Linux

You can rename the electron executable to any name you like.

Packaging Tools

Apart from packaging your app manually, you can also choose to use third party packaging tools to do the work for you:

Rebranding by Rebuilding Electron from Source

It is also possible to rebrand Electron by changing the product name and building it from source. To do this you need to modify the atom.gyp file and have a clean rebuild.

grunt-build-atom-shell

Manually checking out Electron’s code and rebuilding could be complicated, so a Grunt task has been created that will handle this automatically: