This article mainly talks about the following points

  • A brief introduction to electron
  • The electron process communicates with the render layer
  • Electron’s packing configuration
  • Automatic update of electron
  • How does ELECTRON integrate with SQlite3
  • Electron data sharing
  • A bit of advice for electron development on the Intranet
  • Life cycle of the electron main process

Quickly start a electron with a brief introduction

What is the electron

When you open the official website, at first glance, you’re building a cross-platform desktop application using JavaScript, HTML, and CSS, or more generally, a desktop browser, which is actually correct. Because Electron is simply using javaScript to enable Chromium to display web pages

Why do I use it

  • The front end can be used to create cross-platform applications
  • Good ecosystem
  • Developed and maintained by Github
  • Electron (70+ K) is twice as much as Nw.js (35+ K) Star
  • I have used electron product with excellent performance
    • Vscode
    • Atom
    • Making the desktop
    • .

How to get started on Electron quickly

Here’s what I think is the best way to start fast

  • Be sure to read more official documents, which can save a lot of time
  • The official quick start template
  • The official provides a template for quickly familiarizing the API

Use the example provided by ELECTRON directly

// Look at the source code of this, very simple can be used quicklyClone the warehouse
$ git clone https://github.com/electron/electron-quick-start
# Enter the warehouse
$ cd electron-quick-start
Install the dependency library
$ npm install
# Run the app
$ npm start
Copy the code

If you want to learn about the ELECTRON API you can clone the library and run it

git clone https://github.com/electron/electron-api-demos

cd electron-api-demos

npm install

npm start

Copy the code

How to Debug electron

Renderer debugger (Web page) Renderer process this chrome browser, BrowserWindow creates window after adding window instance. Webcontents.open

The main process Electron debugging uses the debug in vsCode. Pay attention to the debugging path. If you need to add variables, the environment can be added according to the configuration

The life cycle of the main process in ELECTRON as well as common events and render layers

We mainly talk about the life cycle of the main process in electron, part of the life cycle of the renderer, generally only introduce the general existence of the API, if only a certain system has not written here, you can consult by yourself

Life cycle in the main process

Life cycle diagram

The life cycle that normal processes trigger

  • will-finish-launching: Triggered when the application completes basic startup
  • web-contents-created:webContents is created
  • browser-window-created:BrowserWindow is created
  • ready: triggered when Electron completes initialization
  • remote-require: is called when remote is imported
  • before-quit: Triggered before the application begins to close the window
  • will-quitEmitted when all Windows are closed and the application is about to exit
  • quit: emitted when the application exits
  • window-all-closed: Triggered when all Windows are closed

CMD +Q or window-all-closed with app.quit() will not be triggered. Basic operations will be handled in Ready

Process related

  • gpu-process-crashed: Triggered when the GPU process crashes or is killed.

other

  • browser-window-focusEmitted when browserWindow gets focus
  • browser-window-blurEmitted when browserWindow loses focus

Render process — (browser) -BrowserWindow

  • ready-to-show: Triggered when the page has been rendered (but not yet displayed) and the window can be displayed
  • move: Window movement
  • resize: Triggered after the window is resized
  • close: Triggered when the window is about to close. It fires before the beforeUnload and unload events of the DOM.
  • blur: Lose focus, same as app
  • focus: Get focus, same as app
  • maximize: Triggered when the window is maximized
  • unmaximize: Triggered when the window is maximized exit state
  • minimize: Triggered when a window is minimized
  • restore: Triggers when the window is restored from minimization
  • .

Render webContents in the BrowserWindow instance

  • did-finish-load: triggered when navigation is complete, i.e. the TAB’s spinner will stop spinning and assign the onload event after
  • did-finish-load: This event is similar to did-finish-load, but is triggered after a load failure or cancellation
  • dom-ready: Triggers this event when text in a frame has finished loading
  • crashed: Triggered when the render process crashes or is terminated
  • unresponsive: The page does not respond
  • devtools-opened: Triggers this event when the developer tool is opened.
  • devtools-closed: Triggers this event when the developer tool is closed.
  • .

The electron process communicates with the render layer

  • Main process and renderer process
  • The difference between the main and renderer processes

Since each TAB page is a process, the electron process is called the main process and there is only one. The page that the main process controls each TAB in the browser is called the renderer process. How does this communicate?

Main process and renderer process

process

A process is an instance of a running program (narrowly defined)

The main process in electron

Electron a process running the package.json main script is called the main process. The script running in the main process presents the user interface by creating a Web page. A Electron application always has one and only one main process.

The renderer process in electron

Since Electron uses Chromium to present Web pages, Chromium’s multi-process architecture is also used. Each Web page in Electron runs in its own rendering process.

The difference between the renderer process and the main process

  • The main process exists from the start, the renderer process creates the instance through BrowserWindow, and the renderer process is destroyed when the instance is destroyed

The main process creates the page using the BrowserWindow instance. Each BrowserWindow instance runs the page in its own rendering process. When an instance of BrowserWindow is destroyed, the rendering process is terminated.

  • The main process manages all renderers, which are independent and self-managing (Web pages)

The main process manages all the Web pages and their corresponding renderers. Each renderer process is independent and only cares about the Web page it is running on.

  • All the underlying GUI apis can be called from the main process, while the renderer process cannot be called at will due to security issues. If you want to call it, you need to communicate it to the main process.

Calling native GUI-related apis in a web page is not allowed, because manipulating native GUI resources in a Web page is dangerous and can lead to resource leaks. If you want to perform GUI actions on a Web page, the corresponding renderer must communicate with the main process and request the main process to perform related GUI actions.

How does the main process communicate with the renderer process

The main process communicates with the renderer process through ipcMain and ipcRenderer

The main process communicates with the renderer process

This is basically the main process using ipcMain and listening on, listening on, and then sending an event via event.Sender send, The rendering process uses ipcRenderer to receive on. If it is synchronous, evnet.returnValue can return the main process result code as follows:

The renderer process communicates with the main process

The renderer process sends messages through the ipcRenderer module send, which can send messages synchronously or asynchronously, and receive messages using ON

The package of electron

Common methods:

  1. Electron builder (I mainly use this)
  2. electron-pakager
  3. electron-forge

electron-builder

Electron – Builder is a complete solution and comes with an automatic update policy

The electron builder package is configured in the script of the package

Common packaging parameters:

  "build": {
    "appId": "your.id", // appid
    "productName": "Program name"// Program name"files": [// Package the required unfiltered files"build/**/*"."main.js"."node_modules/**/*"]."directories": { 
      "output": "./dist-out"// Package the output directory"app": ". /", // Path of package"buildResources": "assets"   
    },
    "nsis": {
      "oneClick": false, // Whether you need to click install, auto update needs to be turned off"allowToChangeInstallationDirectory": true, // Whether the installation path can be selected"perMachine": true// Do I need an auxiliary installation page},"win": {
      "target": [{"target": "nsis"// Output directory mode"arch"The output configuration is ia32 or X64 /x86"x64"]}],"publish": [// automatic update configuration {"provider": "generic"// Use generic to configure the updated server yourself"url": "http://127.0.0.1:8080/updata/"// Update the configured path}]}}Copy the code

Added quick launch items in package.json

"scripts": {
  "pack": "electron-builder --dir"."dist": "electron-builder"
}
Copy the code

Start the packaging

Common points to note

  • Pay attention to the path, because the packaged path will have problems best usepath.join()Let’s deal with that.
  • encounterThe process cannot access the file because it is being used by another process.This problem is mostly occupied by vscode turn it off and restart it

If you use create-react-app to create an application

  • You can first pack the React application into a static file and then pack the static file into electron
  • If the electron- Builder always returns similarelectron.jsCan’t find the warning and prompt you to look at the method in the web page above, can be modified via the electron Builder prompt url, this is actually a tutorial required for scientific surfing.

Auto-update of electron- Builder

If you see the autoUpdater API in the API, you want to refer to the official automatic update before you see the API so that you can avoid the pit, Because the auto-update mechanism of electron builder is somewhat different from that provided by electron, it is also explained on the official website of electron Builder, otherwise error will always be reported

This update is actually a proportional version number between the two versions, if the current version is less than, the server version will download the update

Update mechanism

There’s an article on the update mechanism in the resources. Good. Here’s a quick summary.

AutoUpader life cycle

  • error: If there is a problem in any of the links, it will come to this step
  • checking-for-update: Triggered when checking for updates begins.
  • update-available: Discovery update
  • update-not-available: Triggered when no updates are available.
  • update-downloaded: triggered when the update download is complete.
  • before-quit-for-update: This event is emitted after the user calls quitAndInstall().

Update points to note:

  • AutoUplader in electron- Builder is neededelectron-updaterThis module, non-native module
  • The url in the publish in package.json must match the updated address (note the port), otherwise it will be reportednet::ERR_CONNECTION_REFUSED
  • If it’s unpacked, you want to run awayautoUpdaterThe process requires onedev-app-update.ymlThe files are placed withmain.jsSame level of place, similarwin-ia32-unpacked/resource/app-update.ymlSuch files, directly copy the name can be used
  • If the automatic installation option is configured in the package after the update is completed, the application can be installed directly after closing. If you want to control the immediate installation, you need to add itautoUpdater.quitAndInstall()
  • If the initial application outputs the desired result on the terminal, only a portion of the output in the render selection, or no output, if it does not report an error, you may want to listen to the render processdid-finish-loadThis declaration cycle, which is processed in here, can be used depending on the scenarioonceTo listen to
  • Need a static web server to use in the folder you needhttp-server -oIf not, install one globallynpm i http-server -g, need to be configured in packagepublishIn the"provider": "generic"
  • encounterspawn **/*.exe ENOENTThis is possible if you run an uninstalled application in your development environment and use itautoUpdater.quitAndInstall()It will report an error, if it is installed, it will not report this error
Const {autoUpdater} = require(const {autoUpdater} = require(const {autoUpdater} = require('electron-updater') / / = = = = = = = = = = = = = = = = = must start not = = = = = = = = = = = = = = = constlog = require('electron-log');
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info'; / / = = = = = = = = = = = = = = = = end must not = = = = = = = = = = = = = = = = = = / / encapsulationfunction sendStatusToWindow(text) {
  log.info(text);
  mainWindow.webContents.send('message', text); } /** * automatically updates */function checkUpdata() {
  autoUpdater.setFeedURL('http://127.0.0.1:8080/updata/')
  // autoUpdater.on('error', (error) => {
  //   sendStatusToWindow( `[error]:${error}`)
  // })
  autoUpdater.on('checking-for-update', () => {
    sendStatusToWindow('Checking for update... ');
    // mainWindow.webContents.send('downlaod')

  })
  autoUpdater.on('update-available', (info) => {
    sendStatusToWindow('Update available.');
  })
  autoUpdater.on('update-not-available', (info) => {
    sendStatusToWindow('Update not available.');
  })
  autoUpdater.on('error', (err) => {
    sendStatusToWindow('Error in auto-updater. ' + err);
  })
  autoUpdater.on('download-progress', (progressObj) => {
    let log_message = "Download speed: " + progressObj.bytesPerSecond;
    log_message = log_message + ' - Downloaded ' + progressObj.percent + The '%';
    log_message = log_message + '(' + progressObj.transferred + "/" + progressObj.total + ') ';
    sendStatusToWindow(log_message);
    mainWindow.webContents.send('downloadExe', progressObj.percent)
  })
  autoUpdater.on('update-downloaded', (info) => {
    mainWindow.webContents.send('downloaded')


    sendStatusToWindow('Update downloaded');
    // autoUpdater.quitAndInstall();
  });

Copy the code

Add SQlite3 to electron

Required environment

For Windows, vs2015 and Python2.7 must be available

  1. Python2.7. x can be downloaded and installed
  2. Vs2015 Can be either of the following methods
    1. kitnpm install --vs2015 -g windows-build-tools(recommended)
    2. Install the VS2015 toolkit in Visual Studio

Procedures can be added to the local database, the maximum use of two

  • Sqlite3 (relational type)
  • NeDB (non-relational)

Add the local database SQlite3 to your data

Sqlite3 gitHub adds sqlite3npm I sqlite3 or YARN add sqlite3 to the program

How to use it?

Var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:'); Db.serialize (function() {
var db = new sqlite3.Database()
  db.run("CREATE TABLE lorem (info TEXT)");
  var stmt = db.prepare("INSERT INTO lorem VALUES (?) ");
  for (var i = 0; i < 10; i++) {
      stmt.run("Ipsum " + i);
  }
  stmt.finalize();

  db.each("SELECT rowid AS id, info FROM lorem".function(err, row) {
      console.log(row.id + ":" + row.info);
  });
});

db.close();
Copy the code

Sqilte3 automatically generates the required files for SQLite when it is installed. This binary file is either node-pre-gyp or Node-gyp, which is why you need to install the environment. Who knows how many things are reported at this stage, especially if you want to get it into the Intranet. Such as:

  • As soon as it starts runningError: Cannot find module 'E: \ electronjs \ electron - quick - start/node_modules/sqlite3 \ lib \ binding \ electron - v4.0 - win32 - x64 \ node_sqlite3 node'Something like this, in fact there is no such thing, how to solve it?
    • usenode-gypThis module directly recompiles a correct version
Node - gyp rebuild -- target = 4.0.4 - arch = x64 - target_platform = win32 - dist - url = https://atom.io/download/electron/ --module_name=node_sqlite3 --module_path=.. // target => The electron version number must be the same. // target_platform => Platform ia32/x64 to be packed // dist-url => this is the address to download related content // module_name => module name to package // module_path => where to package outputCopy the code

/node_modules/.bin/ electronic-rebuild./node_modules/.bin/ electronic-rebuild NPM cache clear -f: NPM cache clear -f: NPM cache clear -f: NPM cache clear -f: NPM cache clear -f: NPM cache clear -f: NPM cache clear -f: NPM cache clear -f: NPM cache clear -f: NPM cache clear -f: NPM cache clear -f: NPM cache

was compiled against a different Node.js version using
NODE_MODULE_VERSION 64. This version of Node.js requires
NODE_MODULE_VERSION 69. Please try re-compiling or re-installing
Copy the code

Github [issues] ====> if you select the compiled version of node, there may be a compilation problem. Use the electron rebuild to rebuild sqlite3 or downgrade sqlite3

Be aware of

  • When you packThe error MSB4019: imported project Microsoft was not found. WebApplication. The targetsReinstall the VS2015 toolkit, or have a problem with the previous one (which HAPPENED to me)
  • Compiling SQlite3 with Node-gyp is required for packagingbinding.gypThis Python file as well as other configuration so go straight innode_modules\sqlite3This file runs node-gyp operations
  • When using SQlite3 in the renderer process, there will be packaging problems, which can be resolved by using the local database in the main process
  • There is a problem with using DB after packaging, how can not generate DB in the current directory, check online or through manual authorization for the administrator to open, or manual administrator to open, this is not line, later referenceelectron-vueFound availableapp.getPath('userData')This method is used to get the app’s cacheable address and then use itpath.joinMerging paths solves the problem of generating DB files. In fact, indexDB and locaStore are stored in this directory as well

Other modules

  • globalShortcut: Registers the global shortcut key
  • TrayTray:
  • Menu: Menu event

Pay attention to Intranet development

Intranet development is really annoying. First, you need the environment, then you need to download the package, and then you need to compile various files such as sqlite3 compiled files. If you develop ELECTRON on the Intranet, you need to copy all the required packages to the corresponding location

Most of the files that need to be configured are in C: Users\ XXXXXX which stands for your folder, and some of the download cache files are in the electron and electron-builderer directories in C: Users\ XXX \AppData\Local

Reference study materials

I have read most of the following articles and recommend them to you

electron

  • Electron official website – documents must be eaten, step on 80% less pits
  • Electron, from the toy mentality to build a better and better desktop client product – a Quick Start that is not “Hello Word”
  • The nature of Electron
  • React to Prepare the Electron application for production
  • Uncle Sunan’s electron collection
  • [electron] Ultimate Ouyi 5,000 word tutorial thrown at you
  • Electron builds cross-platform applications for Mac/Windows/Linux
  • Summary of Electron depth practice
  • 【 science online 】 The foundation of electron correlation

Electron construction correlation

  • How does the Electron app use create-React-app to go from 0 to 1
  • Electron series articles – program directory structure
  • Webpack Field – Build the Electron application
  • React + Electron Builds a desktop application

Electron packing correlation

Electron update

electron

  • Build the desktop application using Electron
  • How to build your first desktop application using JavaScript using Electron
  • Build a Todo application using Electron – Scientific Web surfing
  • Summary of XCel Project – Performance optimization of Electron and Vue

Electron compilation

  • Electron compile SQlite3 pit avoidance guide

electron tips

  • Records of trampling pits in Electron engineering
  • The basics of electron