1

The following are the modules available for the main process Electron

Moduledescription
appResponsible for controlling the entire life cycle of the application
autoUpdaterThis module provides an Squirrel automatic update framework
BrowserWindowCan be used to create a new browser window
contentTracingUsed to collect tracking information generated by the Chromium
dialogUsed to display native system dialogs, such as open file dialogs
global-ShortcutKeyboard shortcuts for registering and unregistering globally
ipcMainThis module is EventEmitter , used in the main process, can send synchronous or asynchronous messages to interact with the rendering process
MenuUsed to create a native menu, such as a context menu
MenuItemUsed to add menu items to the menu
powerMonitorUsed to display battery power changes, it can only be used in the main process, and only when the ready event has been issued
powerSaveBlockerUsed to prevent the system from entering power saving mode, sleep mode
protocolUsed to register a custom protocol or declare the use of an existing protocol
sessionUsed to create new Session objects, save local objects and other operations
webContentsThis is a EventEmitter , which is responsible for rendering and controlling a web page. It is an attribute of BrowserWindow
TrayA Tray represents an operating system notification area icon , usually is bound and a context menu

app module

app module is designed to control the entire application life cycle.

Example:

For example, to exit the application when the last window is closed:

const app = require('app');

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

app object can emit the following events:

eventdescription
will-finish-launchingWhen the program completes the basic startup, similar to the ready event
readyElectron when 060d55bd4efba7 completes initialization
window-all-closedFires when all windows have been closed. It is only triggered when the program is about to be pushed to exit. app.quit() is called, it will not trigger
before-quitIssued when the program starts to close the window, calling event.prevertDefault() will prevent the default behavior of the application
will-quitThis event is emitted when the windows are closed and the program is about to exit
quitTriggered when the application is exiting

autoUpdater module

autoUpdater module provides an Squirrel automatic update framework.

autoUpdater object will trigger the following events:

eventdescription
errorTriggered when an update error occurs
checking-for-updateTriggered when starting to check for updates
update-availableTriggered when an available update is found, the update package download will start automatically
update-not-availableTriggered when there is no update available
update-downloadedTriggered when the update download is complete

BrowserWindow module

BrowserWindow module is used to create a new browser window.

Example:
// 在主进程中
const BrowserWindow = require('electron').BrowserWindow;
// 在渲染进程中
const BrowserWindow = require('electron').remote.BrowserWindow;

var win = new BrowserWindow({ width: 800, height: 400, show: false });
win.on('closed', function() {
  win = null;
});

win.loadURL('https://github.com');
win.show();

BrowserWindow object can trigger the following events:

eventdescription
closeTo close the window when the trigger, it DOM of beforeunload and unload trigger before the event, using event.preventDefault() can cancel this operation
closedTriggered when the window has been closed, when you receive this event, you should delete the reference to the closed window and avoid using it again
unresponsiveTrigger an event when the interface is stuck
responsiveTriggered when the interface resumes stuck
blurTriggered when the window loses focus
focusTriggered when the window gains focus
maximizeTriggered when the window is maximized
unmaximizeTriggered when the window is maximized
minimizeTriggered when the window is minimized
restoreTriggered when the window is restored from minimized
resizesize when the window 060d55bd4efdf4 changes
moveWhen the window moves triggered, in OS X the alias moved

contentTracing module

contentTracing module is used to collect Chromium content module. This module does not have the web interface, so we need to add chrome://tracing/ chrome browser to load the generated files to view the results.

Example:
const contentTracing = require('contentTracing').;

const options = {
  categoryFilter: '*',
  traceOptions: 'record-until-full,enable-sampling'
}

contentTracing.startRecording(options, function() {
  console.log('Tracing started');

  setTimeout(function() {
    contentTracing.stopRecording('', function(path) {
      console.log('Tracing data recorded to ' + path);
    });
  }, 3000);
});

content-tracing module is as follows:

methoddescription
getCategoriesObtain a set of classification groups, which can be changed to a new code path
startRecordingStart recording to all processes. Once a request to start recording is received, recording will be started immediately and recorded asynchronously in the child process
stopRecordingStop recording of all child processes
startMonitoringStart listening to all processes
stopMonitoringStop listening to all child processes
captureMonitoringSnapshotGet the currently monitored search data
getTraceBufferUsagGet the percentage maximum usage by looking for the buffer
setWatchEventcallback will be called when a specified event occurs on any process at any time
cancelWatchEventCancel the watch event, if you start the search, this may cause an error in the callback function of the watch

dialog module

dialog module provides api to display native system dialogs, such as the open file box or the alert box. So the web application can bring users the same experience as the system application.

Example:

An example of a dialog box showing the selection of files and directories:

var win = ...;  // 显示对话框的浏览器窗口
const dialog = require('electron').dialog;
console.log(dialog.showOpenDialog({ properties: [ 'openFile', 'openDirectory', 'multiSelections' ]}));

global-shortcut module

global-shortcut module is used to set shortcut keys for various custom operations. Note that the shortcut keys registered with this module are system-wide. Do not use this module before the ready

Example:
var app = require('app');
var globalShortcut = require('electron').globalShortcut;

app.on('ready', function() {
  // 注册一个'ctrl+x'快捷方式
  var ret = globalShortcut.register('ctrl+x', function() {
    console.log('ctrl+x is pressed');
  })
  if (!ret) {
    console.log('registration failed');
  }
  // 检查是否注册了'ctrl+x'快捷方式
  console.log(globalShortcut.isRegistered('ctrl+x'));
});

app.on('will-quit', function() {
  // 注销'ctrl+x'快捷方式
  globalShortcut.unregister('ctrl+x');

  // 注销所有快捷方式
  globalShortcut.unregisterAll();
});

ipcMain module

ipcMain module is an instance of the class EventEmitter . When it is used in the main process, it controls the asynchronous or synchronous messages sent by the rendering process, and the messages sent from the rendering process will trigger events.

Example:

The following is an example of sending and processing messages between the main process and the rendering process.

Main process:

const ipcMain = require('electron').ipcMain;
ipcMain.on('asynchronous-message', function(event, arg) {
  console.log(arg);  // 输出ping
  event.sender.send('asynchronous-reply', 'pong');
});

ipcMain.on('synchronous-message', function(event, arg) {
  console.log(arg);  //  输出ping
  event.returnValue = 'pong';
});

Rendering process:

const ipcRenderer = require('electron').ipcRenderer;
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // 输出pong

ipcRenderer.on('asynchronous-reply', function(event, arg) {
  console.log(arg); // 输出pong
});
ipcRenderer.send('asynchronous-message', 'ping');

menu module

menu module can be used to create native menus, which can be used as application menus and content menus.

Example:

The syntax for creating a new menu:

var menu = new Menu();

MenuItem module

MenuItem module is used to add menu sub-items to the menu.

Example:

Create a new MenuItem syntax:

var menuItem = new MenuItem(options)

options are as follows:

  • click
  • role
  • type
  • label
  • sublabel
  • accelerator
  • icon
  • enabled
  • visible
  • checked
  • submenu
  • id
  • position

powerMonitor module

powerMonitor module is used to monitor energy zone changes and can only be used in the main process. This module cannot be used after ready app module is triggered.

Example:
app.on('ready', function() {
  require('electron').powerMonitor.on('suspend', function() {
    console.log('系统将进入休眠状态');
  });
});

powerMonitor object will trigger the following events:

eventdescription
suspendTriggered when the system hangs
resumeTriggered when the system resumes working
on-acTriggered when the system is using AC power
on-batteryTriggered when the system is using battery power

powerSaveBlocker module

powerSaveBlocker module is used to prevent the application system from entering sleep mode, so this allows the application to keep the system and the screen working.

Example:
const powerSaveBlocker = require('electron').powerSaveBlocker;

var id = powerSaveBlocker.start('prevent-display-sleep');
console.log(powerSaveBlocker.isStarted(id));

powerSaveBlocker.stop(id);

powerMonitor module has the following methods:

methoddescription
startStart to prevent the system from entering sleep mode
stopblocker designated 060d55bd501572
isStartedReturn boolean , whether the corresponding powerSaveBlocker has been started

protocol module

protocol module can register a custom protocol, or use an existing protocol. This module can only be used after ready app module is triggered.

Example:

Use a protocol with functions similar file://

const electron = require('electron');
const app = electron.app;
const path = require('path');

app.on('ready', function() {
    var protocol = electron.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('注册协议失败')
    });
});

session module

session module can be used to create a new Session object.

Example:
const BrowserWindow = require('electron').BrowserWindow;

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

var ses = win.webContents.session;

webContents module

webContents is a EventEmitter , responsible for rendering and controlling a web page, and is an BrowserWindow object.

Example:
const BrowserWindow = require('electron').BrowserWindow;

var win = new BrowserWindow({width: 800, height: 1500});
win.loadURL("https://www.9xkd.com/");

var webContents = win.webContents;

webContents object can emit the following events:

eventdescription
did-finish-loadThe event is emitted when the navigation is completed, and the onload event is also completed
did-fail-loadThis event is similar to did-finish-load , but it is issued when the load fails or is canceled
did-frame-finish-loadEvent is emitted when a frame
did-start-loadingWhen the tab of spinner starts spinning
did-stop-loadingWhen tab of spinner ends spinning
did-get-response-detailsEmit an event when detailed information about the requested resource is available
did-get-redirect-requestframe an event when the document in the specified 060d55bd501888 has been loaded
page-favicon-updatedEvent is emitted when page receives the icon url
new-windowEvent is emitted when page requests to open the specified url
will-navigatepage an event when the user or 060d55bd5018e2 wants to start navigation
did-navigateEmit an event when a navigation ends
did-navigate-in-pageEmit an event when in-page navigation occurs
crashedEmit an event when the rendering process crashes
plugin-crashedEmit an event when the plug-in process crashes
destroyedwebContents an event when 060d55bd501933 is deleted
devtools-openedEmit an event when the developer toolbar is opened
devtools-closedEmit an event when the developer toolbar is closed
devtools-focusedEmit an event when the developer toolbar is focused or opened
certificate-errorIssue an event when verification of a certificate or url
select-client-certificateEmit an event when a client certificate is requested
loginIssue an event when webContents wants to do basic verification
found-in-pageEvent is emitted when webContents.findInPage is used for in-page search and a usable value is found
media-started-playingEmit an event when the media starts to play
media-pausedEmit an event when the media stops playing
did-change-theme-colorEvent is emitted when page is used. This is usually due to the introduction of a meta tag
cursor-changedEvent is emitted when the type of mouse changes

Link: https://www.9xkd.com/


知否
221 声望177 粉丝

Skrike while the iron is hot.