About electron

Electron is a framework for creating native applications using Web technologies such as JavaScript, HTML and CSS. It is fully compatible with Mac, Windows and Linux, truly realizing a cross-platform desktop application solution.

The technical architecture

Electron’s core technology architecture is made up of Chromium + Node.js + Native APIs.

Next, let’s briefly introduce its three core weapons:

  • First of all, Chromium, we can understand it as a Chrome browser with the latest browser features. The advantage it brings us is that we don’t need to consider the compatibility of browsers in the development process. We can use some of the latest ES6 and ES7 syntax, and we can safely use Flex layout. As well as the latest browser features, you can try them out, regardless of compatibility.
  • Node.js provides the ability to read and write files, call local commands, and extend third parties. Based on the entire node.js ecosystem, nearly hundreds of thousands of Node.js modules can be used in the entire client.
  • Native APIs provide the ability to provide a unified Native interface that includes system notifications, keyboard shortcuts, and access to system hardware information. It also provides basic desktop client capabilities, such as update mechanisms and crash reporting.

Differences between Chromium and Chrome

Chromium is an open source browser project of Google and maintained by the open source community. It supports Windows, Mac, Linux and other operating systems, and most dual-core browsers in China are developed based on it.

Chrome is also a secondary development based on Chromium. Based on Chromium, Chrome offers additional advanced features:

  • Support for special audio formats such as AAC, H.264 and MP3 encoding
  • Built-in Flash plug-in
  • Automatic updates: Windows and Mac Users of Chrome can get additional background apps that automatically keep Chrome up to date
  • Extension restrictions: For Chrome, Google will disable extensions that are not hosted in the Chrome Web Store.
  • Crashes and error reporting: Chrome users can choose to send statistics about crashes and errors to Google for analysis.

Quick start

Install the electron application

You can refer to the official documentation – build your first electron application, you can also directly copy the following code on the command line, you can immediately experience a electron application demo.

git clone https://github.com/electron/electron-quick-start
cd electron-quick-start
npm install
npm start
Copy the code

The introduction of the react

You can choose the technical architecture of the render layer, not necessarily react, but vue, Angular, etc. Here I use react as an example, and use the official scaffolding of React directly.

npx create-react-app electron-quick-start
cd electron-quick-start
npm start
Copy the code

We also installed the React scaffolding in the electron directory, so we need to make some adjustments and changes. First, merge the package.json of the electron project and react project, and change the command to start electron to NPM run electron. Secondly, change the file path of loading view in the electron entry file main.js to http://localhost:3000/. Part of the code of main.js is as follows:

const isDev = require('electron-is-dev')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800.height: 600.webPreferences: {
      preload: path.join(__dirname, 'preload.js')}})if(isDev) {mainwindow.loadurl ('http://localhost:3000/') // React startup directory
  } else {
    mainWindow.loadFile(path.join(__dirname, '/.. /build/index.html')) // Load the packaged HTML}}Copy the code

At this point, we can happily use React in electron. The obvious downside is that you need to start both commands at the same time. If you want to start with one command, you can install the corresponding libraries.

Of course, if you want to use it in a formal project, you can install Electron Forge, a full-fledged scaffolding that integrates packaging, publishing, and templates (React, Vue, Angular, etc.) as a render layer framework.

Interprocess communication

To understand inter-process communication, it is important to understand two important concepts in electron, namely the main process and the renderer process.

The main process

  • Running in the Electronpackage.jsonIn themainThe process of the script is called the master process, i.eMain.js runs in the main process.
  • A electron application has one and only one main process.
  • Only the main process can do guI-related native API operations directly.

Rendering process

  • The Chromium Web page is called a renderer, i.e. the environment in which index.html is running is a renderer.
  • A single electron application can have multiple renderers.
  • With node.js modules, renderers can interact with the operating system at the bottom of the page (such as the FS module).

How to communicate

Now that we know what the main process and the renderer process are, how do they communicate?

Communication between the main process and the renderer process is via the ipcRenderer and ipcMain modules. See the official example for the API documentation. Here is an example of a renderer communicating with the main process.

For example: there is a Textarea input box on the page. After the user enters the content, click “Save to this directory” to save the content of the input box to the msg. TXT folder of this directory.Such a simple communication process is completed, of course, the main process can also actively communicate to the renderer process, as well as between the renderer process communication, will not be described here, the principle is similar.

packaging

Packaging is the last and indispensable step in developing desktop applications. At present, there are two kinds of electron packaging tools commonly used in the market, namely, electric-Packager and electric-Builder, and the first one is relatively simple in our project.

electron-packager

The features of this packaging tool are as follows:

  • Can be generated directly.app..exeAnd other executable files, users do not need to install, open can be used
  • Configuration is simple, usually a command line can be done

Here is an example, part of the package.json code:

"scripts": {
  "start": "electron ."."packageOS": "Electron packager. DMS enterprise Edition --platform=mas --arch=x64 --icon= DMS --out=./dist --asar --app-version=1.0.0"."packageWin64": "Electron packager. 'DMS Enterprise Edition --platform=win32 --arch=x64 --icon= DMS --out=./dist --asar --app-version=1.0.0"."packageWin32": "Electron packager. DMS enterprise Edition --platform=win32 --arch=ia32 --icon= DMS --out=./dist --asar --app-version=1.0.0"
},
Copy the code

You can refer to the development documentation for the specific parameters. It should be noted that different platforms require different image formats for packaging. On the MAC, PNG images are used directly, while on Windows, ICNS images are used.

electron-builder

The electric-Builder can be packaged not only as an executable but also as an installable program, and has more features than the electric-Packager, so the configuration of the package is also more complicated. According to github data, the electron Builder has 2000+ stars more than the electron Packager, which shows that the application of electron Builder will be more extensive.

Hot update

CDN resources updated

In certain scenarios (e.g. Generally in our static web page development resources are of CDN, in order to use a set of code and the web, we can in the APP server directly quoting these static resources, in addition is the scene, the incremental updating our UI view layer code is hosted in the CDN, in order to achieve this time if the user has not been reboot or refresh the APP, Then these static resources will not actively update; At this time, the common practice is to obtain the notification of update through polling call interface or server push. If any update is found, the popup window will remind the user and let the user reload the whole page to refresh the page.

Application Package update

In addition to the above SITUATION of CDN, there is another situation where all resources are packaged in APP. At this time, what should we do if the system is updated? You can use update.electronjs.org directly or you can use your own update server.

1) Use updata.electronjs.org to directly use the tool library:

  • The application runs on macOS or Windows
  • The app has a public GitHub repository
  • The compiled version is released in GitHub Releases
  • The compiled version is signed by the code

If the prerequisite is available, install update-electron-app directly

npm install update-electron-app
Copy the code

Call this update from your app’s main Process file:

require('update-electron-app') ()Copy the code

By default, this module checks for updates when the application starts and then checks again every 10 minutes. When an update is found, it automatically downloads it in the background. When the download is complete, a dialog box is displayed allowing the user to restart the application.

2) Deploy the update server If you’re developing a private Electron application, or if you don’t release it publicly in GitHub Releases, you may need to run your own update server. Depending on your needs, you can choose from below:

  • Hazel – Update server for private or open source applications that can be deployed for free on Now. It pulls updated files from GitHub Releases, and exploits the power of GitHub CDN.
  • Nuts- Also uses GitHub Releases, but has to cache application updates on disk and support private repositories.
  • Electron -release-server – provides a dashboard for handling releases without the need to publish releases on GitHub.
  • Nucleus — a complete update server for the Electron application maintained by Atlassian. Support for multiple applications and channels; Use static file storage to reduce server costs.

Once the update server is deployed, you can call electron’s autoUpdater module directly for update notifications

const { app, autoUpdater, dialog } = require('electron')

// Build the update server URL and notify autoUpdater
const server = 'https://your-deployment-url.com'
const url = `${server}/update/${process.platform}/${app.getVersion()}`

autoUpdater.setFeedURL({ url })

// Polling checks for updates
setInterval(() = > {
  autoUpdater.checkForUpdates()
}, 60000)
Copy the code

Notify user code when an update is detected:

// Success notification
autoUpdater.on('update-downloaded'.(event, releaseNotes, releaseName) = > {
  const dialogOpts = {
    type: 'message'.buttons: ['Restart now'.'Try again later'].title: 'Update Notification'.message: process.platform === 'win32' ? releaseNotes : releaseName,
    detail: 'A new version has been downloaded. Restart the application to apply the updates.'
  }

  dialog.showMessageBox(dialogOpts).then((returnValue) = > {
    if (returnValue.response === 0) autoUpdater.quitAndInstall()
  })
})

// Failure notification
autoUpdater.on('error'.message= > {
  console.error('There was a problem updating the application')
  console.error(message)
})
Copy the code

You can also refer to the official documentation update application section for more information.

Reference Documents:

www.electronjs.org/docs github.com/electron cnodejs.org/topic/57812… www.electronjs.org/docs/tutori…