Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Electron app module


May 25, 2021 Electron


Table of contents


App modules are designed to control the lifecycle of the entire app.

The following example shows how to exit the app when the last window is closed:

var app = require('app');
app.on('window-all-closed', function() {
  app.quit();
});

The list of events

The app object triggers the following events:

Event: 'will-finish-launching'

It is triggered when the application completes the underlying startup. I n Windows and Linux, the will-finish-launching event is the same as the ready event; You should often set up listeners for open-file and open-url here and start crash reports and automatic updates.

In most cases, you should only do all the business in the ready event processor.

Event: 'ready'

Triggered when Electron completes initialization.

Event: 'window-all-closed'

Triggered when all windows are closed.

This time can only be triggered if the app has not exited. If the user presses Cmd-Q, or the developer calls app.quit(), Electron will first try to close all windows before triggering the will-quit event, in which case window-all-closed will not be triggered.

Event: 'before-quit'

Return:

  • event Event

It is triggered when the application starts closing its window. Calling event.preventDefault() will prevent the default behavior of terminating the application.

Event: 'will-quit'

Return:

  • event Event

Triggered when all windows have been closed and the app is about to exit. Calling event.preventDefault() will prevent the default behavior of terminating the application.

You can see the difference between the will-quit event and the window-all-closed event in the description of the window-all-closed event.

Event: 'quit'

Return:

  • event Event
  • exitCode Integer

Triggered when the application is exiting.

Event: 'open-file' OS X

Return:

  • event Event
  • path String

Triggered when the user wants to open a file in the app. 20> Open-file events are often triggered when the app is already open and the system wants to open the file again using the app. Open-file is also triggered when a file is dragged into the dock and the app is not already running. Make sure that the open-file event is monitored when the app starts, even before the ready event is triggered, to handle this situation.

If you want to handle this event, you should call event.preventDefault(). In a Windows system, you need to parse process.argv to get the file path.

Event: 'open-url' OS X

Return:

  • event Event
  • url String

It is triggered when the user wants to open a url in the app. The URL format must be identified in advance to be opened by your app.

If you want to handle this event, you should call event.preventDefault().

Event: 'activate' OS X

Return:

  • event Event
  • hasVisibleWindows Boolean

Triggered when an app is activated, it is often used when clicking on the app's dock icon.

Event: 'browser-window-blur'

Return:

  • event Event
  • window BrowserWindow

Triggered when a BrowserWindow loses focus.

Event: 'browser-window-focus'

Return:

  • event Event
  • window BrowserWindow

Triggered when a BrowserWindow gets the focus.

Event: 'browser-window-create'

Return:

  • event Event
  • window BrowserWindow

Triggered when a BrowserWindow is created.

Event: 'certificate-error'

Return:

  • event Event
  • webContents WebContents
  • url String - URL address
  • Error String - Error Code
  • certificate Object
  • Data Buffer - PEM encoded data
  • IssuerName String - The publisher's public name
  • callback Function

When validation of the certificate certificate on url fails, if you need to trust the certificate, you need to block the default behavior event.preventDefault() and call callback (true).

session.on('certificate-error', function(event, webContents, url, error, certificate, callback) {
  if (url == "https://github.com") {
    // 验证逻辑。
    event.preventDefault();
    callback(true);
  } else {
    callback(false);
  }
});

Event: 'select-client-certificate'

Return:

  • event Event
  • webContents WebContents
  • url String - URL address
  • certificateList [Object]
  • Data Buffer - PEM encoded data
  • IssuerName String - The publisher's public name
  • callback Function

Triggered when a client authentication is requested.

Url refers to the web address that requests client authentication and needs to pass in a certificate from a list of certificates when calling callback.

You need to call event.preventDefault() to prevent your app from automatically using the first certificate for validation. Here's what it looks like:

app.on('select-certificate', function(event, host, url, list, callback) {
  event.preventDefault();
  callback(list[0]);
})

Event: 'login'

Return:

  • event Event
  • webContents WebContents
  • request Object
    • method String
    • url URL
    • referrer URL
  • authInfo Object
    • isProxy Boolean
    • scheme String
    • host String
    • port Integer
    • realm String
  • callback Function

It is triggered when the webContents do an HTTP landing verification.

By default, Electron cancels all validation behavior, and if you need to override this behavior, you need to block the default behavior with event.preventDefault() and use callback (username, password) for validation.

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

Event: 'gpu-process-crashed'

Triggered when the GPU process crashes.

The list of methods

App objects have the following methods:

Note that some methods can only be used for specific operating systems.

app.quit()

Try to close all the windows. 20> The before-quit event will be triggered first. If all windows are successfully closed, the will-quit event will be triggered and the app will be closed by default.

This method ensures that all beforeunload and unload event processors are executed correctly. If a window's beforeunload event processor returns false, the entire app may cancel its exit.

app.hide() OS X

Hide all app windows, not minimize them.

app.show() OS X

Hide and rediscofocus all windows, and they are not automatically selected.

app.exit(exitCode)

  • ExitCode integer

Exit the app with exitCode.

All windows are closed immediately and the user is not asked. The two events, before-quit and will-quit, are not triggered

app.getAppPath()

Returns the path to the file where the current app is located.

app.getPath(name)

  • name String

Returns a special folder or file path related to the name parameter. Throw an Error when it fails.

You can request the following path by name:

  • Home user's home folder (home directory)
  • AppData App Data folder for current users, corresponding by default:
    • %APPDATA% Windows
    • $XDG in .CONFIG-HOME or .config Linux
    • s/Library/Application Support OS X
  • userData stores the folder of your application settings files, the default is the appData folder attached to the app's name
  • Temp temporary folder
  • Exe's current executable file
  • module libchromiumcontent library
  • The desktop folder of the current user of the desktop
  • The path to the documents user document directory
  • The downloads user downloads the directory's path.
  • The path to the music user's music catalog.
  • The path to the picture directory of the picture user.
  • The path to the videos user video directory.

app.setPath(name, path)

  • name String
  • path String

The path to override a name is path, which can be a folder or a file, which is related to the type of name. I f the folder to which this path points does not exist, the folder will be created by this method. Error is thrown if an error occurs.

The name parameter can only be defined in app.getPath.

By default, cookies and caches for web pages are stored in the userData folder. If you want to change this location, you need to override the path to userData before the ready event in the app module is triggered.

app.getVersion()

Returns the version of the loaded application. If the application's package.json file does not have a version number written, returns the version of the current package or executable file.

app.getName()

Returns the name in the package.json file for the current application.

Because of the naming rules for npm, the name field is usually a short, small-case string. H owever, the full name of the app name is usually capital letters, and you should use a productName field alone to represent the full name of your application. Electron gives preference to this field as the app name.

app.setName(name)

  • name String

Rewrite the name of the current app

app.getLocale()

Returns the language of the current application.

app.addRecentDocument(path) OS X Windows

  • path String

Add path to the list of recently visited documents.

This list is managed by the operating system. In Windows you can access it through the task bar, and in OS X you can access it through the dock menu.

app.clearRecentDocuments() OS X Windows

Clear the list of recently accessed documents.

app.setUserTasks(tasks) Windows

  • task - an array of Task objects

Add tasks to the Tasks category for JumpList features in Windows.

The Task object format in tasks is as follows:

Task Object

  • Program String - The path to execute the program, usually you should indicate that the path of the current program is the process.execPath field.
  • arguments String - Command line parameters when the program executes.
  • Title String - The title that appears in JumpList.
  • Description String - A description of the task.
  • IconPath String - The absolute path of the icon displayed in JumpList, which can be a resource file that contains any icon. In general, you can display icons in your program by indicating process.execPath.
  • iconIndex Integer - The location of the icon used in the icon file. I f an icon file includes more than one icon, you need to set this value to determine which icon is used. If there is only one icon in this icon file, the value is 0.

app.allowNTLMCredentialsForAllDomains(allow)

  • allow Boolean

Dynamically set whether a certificate is always sent for HTTP NTLM or Negotiate authentication. T ypically, Electron only sends NTLM/Kerberos certificates to the local network, such as computers that are in the same domain as you. However, if the network is not well set up, this automatic probe may fail, so you can customize electron's behavior for all URLs through this interface.

app.makeSingleInstance(callback)

  • callback Function

This method allows your app to have up to one instance at a time, otherwise your app can run multiple times and produce multiple instances. You can use this interface to ensure that only one instance is running normally and that all remaining instances are terminated and exited.

If multiple instances are running at the same time, callback in the first instance being run is called as callback (argv, workingDirectory). T he remaining instances are terminated. argv is an array that contains a list of command line parameters for this instance, and workingDirectory is the current running directory for this instance. Typically, we use to remind users that the app has been opened by activating it on the home screen and de-minimizing it.

Callback is not likely to be called after the app's ready event.

If the current instance is the first instance, false is returned in this method to ensure that it continues to run. Otherwise, true will be returned to let it exit immediately.

In OS X, if a user opens an app through Finder, open-file, or open-url, the system enforces that only one instance is running. But if the user opens through the command line, this system mechanism is ignored, so you still need this method to ensure that the app runs as a single instance.

Here's a simple example. We can use this example to learn how to make sure your app runs as a single instance.

var myWindow = null;

var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
  // 当另一个实例运行的时候,这里将会被调用,我们需要激活应用的窗口
  if (myWindow) {
    if (myWindow.isMinimized()) myWindow.restore();
    myWindow.focus();
  }
  return true;
});

// 这个实例是多余的实例,需要退出
if (shouldQuit) {
  app.quit();
  return;
}

// 创建窗口、继续加载应用、应用逻辑等……
app.on('ready', function() {
});

app.setAppUserModelId(id) Windows

  • id String

Change the Application User Model ID of your current app to id .

app.isAeroGlassEnabled() Windows

If DWM composition (Aero Glass) is enabled, this method returns true, otherwise false. You can use this method to decide whether to turn on transparent window effects, because transparent window effects are not valid if the user does not turn on DWM.

For example:

let browserOptions = {width: 1000, height: 800};

// 只有平台支持的时候才使用透明窗口
if (process.platform !== 'win32' || app.isAeroGlassEnabled()) {
  browserOptions.transparent = true;
  browserOptions.frame = false;
}

// 创建窗口
win = new BrowserWindow(browserOptions);

// 转到某个网页
if (browserOptions.transparent) {
  win.loadURL('file://' + __dirname + '/index.html');
} else {
  // 没有透明特效,我们应该用某个只包含基本样式的替代解决方案。
  win.loadURL('file://' + __dirname + '/fallback.html');
}

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

Add a command-line switch to Chromium with the optional parameter value.

Note This method does not affect process.argv, which we usually use to control some of the underlying Chromium behavior.

app.commandLine.appendArgument(value)

Add a command line argument directly to Chromium, which must be quoted and formatted correctly.

Note This method does not affect process.argv.

app.dock.bounce([type]) OS X

  • Type String - Optional parameters, which can be critical or informational. The default is informational.

When critical is passed in, the app in the dock will start bouncing until the app is activated or the request is canceled.

When informational is passed in, the icon in the dock bounces for only one second. However, the request is still activated until the app is activated or the request is canceled.

The return value returned by this method represents the ID of the request.

app.dock.cancelBounce(id) OS X

  • id Integer

Cancel the request for this id.

app.dock.setBadge(text) OS X

  • text String

Set the string that the app displays in the dock.

app.dock.getBadge() OS X

Returns the string that the app displays in the dock.

app.dock.hide() OS X

Hide the icons applied to the dock.

app.dock.show() OS X

Displays the icon applied to the dock.

app.dock.setMenu(menu) OS X

Set the app's dock menu .

app.dock.setIcon(image) OS X

Set the icon that the app displays in the dock.