Electron field

Abstract

How time flies, in the busy work, 2020 has already passed.

Despite being a year older, grayer and more skilled by 2021, wages have not risen.

So what? Does XXX stop exploiting so that workers can be free?

“The migrant worker, the soul of the migrant worker, the migrant worker is the most beautiful person”, which reveals the unremitting pursuit of the little people in the ordinary life, with a more positive and optimistic color.

It’s self-deprecating and motivating all the time. As a worker, let’s study electron, which has been hot.

You need some basic knowledge of Node to read this article. Knows Electron is a technology for developing desktop applications.

This paper mainly introduces the history of desktop applications and the history of electron, analyzes the principle of electron and the structure of the electron vue project, and quickly starts the electron vue project.

keywords

Electron Electron-vue

The body of the

This article was first published on the public account “Full stack big guy’s Cultivation road”, welcome to follow.

The background,

In the development of XXX project, electron technology needs to be used. In order to let more students know and like electron, I want to share my practical experience in these years through this article.

The history of desktop applications

Desktop applications, also known as GUI programs.

There are many different techniques for developing desktop applications throughout history, and the pros and cons of each technique are probably familiar:

  1. VB

Ancient programmer’s development tool, once the world’s first development language, drag-and-drop graphical development makes it an excellent desktop development tool. Microsoft relied on the strength of its operating system to keep Delphi, its contemporary rival, at bay.

  1. C + + win32API

Its MFC scheme is based on composite controls and messaging mechanism in Windows. This technology is also more than 20 years old, so the API design is not very friendly. Microsoft stopped maintaining it a few years ago. In short, it’s obsolete.

  1. Winform

However, from the perspective of development experience, customization and beautification of controls will be more troublesome.

  1. C#的.net framework

The case in point is WPF, which has native features that no other library can match: High DPI, Split Screen, and natural advantages over DirectX. But it’s not open source, relies on the.NET framework, and can be slow to start up.

  1. The Java swing/deployment headaches

This is a relatively large group, which has the advantage of a natural combination of cross-platform and popular development language Java, but the interface is not very beautiful.

  1. C + +, Qt

This is the preferred cross-platform option for many clients, because there is a wealth of open source, UI libraries, and libraries of various functions, but learning costs are high.

  1. C + + duilib

This is under Windows open source directUI (Microsoft proposed the separation of UI and logic of the idea) library, it is to cater to the Internet desktop software small and beautiful trend of development, may be less attention to it. But the products developed with it are famous, such as QQ, wechat, iQiyi and many other well-known software.

  1. Objective-c/swift cocoa

This is the solution for the MAC platform. It is easy to call the underlying API, but the disadvantages are not cross-platform, document-unfriendly, and the UI library is not rich. Now it’s less and less developed that way.

From the point of view of the gradual integration of B/S and C/S architecture, desktop program development based on Web technology has gradually become the mainstream. Because the interface part of the code can be reused.

  1. An early solution of this kind of technology is to usevbembeddedwebBrowserControl, based onIEKernel, just a lot of web development is also usefulactiveXBut this approach has an obvious drawback, is very dependent on the user environment, because the missing components will lead to various crashes.
  2. Embedded web framework, this kind of technology is mainly based on browser engine implementationUIRendering. The typical one isappkitThe aboveUIWebViewCEFchro-mium embeded framework). This can be done using web pagesHTML5+CSSAchieve all kinds of cool effect, but the disadvantage is also more obvious, is the desktop program embedded inside a similarChromeBrowser, memory overhead will be relatively large.

Compared with CEF, ELECTRON has a separate JS v8 engine, which can run Node.js to complete server-side functions. An independent client can be realized by interacting with the internal browser’s V8 engine. This is different from CEF’s need to be housed within other programs.

The history of Electron

Electron (originally called Atom Shell) is an open source framework developed by GitHub. It allows desktop GUI application development using Node.js (as the back end) and Chromium (as the front end). Electron has been used for front-end and back-end development by several open source Web applications, including GitHub’s Atom and Microsoft’s Visual Studio Code.

Figure 1 ATM editor

Figure 2 vscode editor

Electron is a framework that lets you create desktop applications using JavaScript, HTML, and CSS. These applications can then be packaged to run directly on macOS, Windows, and Linux, or distributed through the Mac App Store or Microsoft Store. Typically, you create a desktop application for the operating system (OS) using the native application framework specific to each operating system. Electron can write to your application using techniques you already know. As such, it is a framework, not a library, and front-end developers can develop desktop applications just as they would web applications. Of course, it can be listed on any major app store, which requires its own certification, which will be discussed later in this article.

Figure 3 electron icon

Its advantages are shown below:

Figure 4 Advantages of electron

The advantages of using Electron for desktop development are obvious, which is equivalent to complete Web programming, and it is very easy for those with Web development experience to get started with front-end development. Web development ecosystem is extensive, development cost is low, and scalability is strong. Some popular front-end frameworks such as React, Angular, and Vue can be combined with Electron for development. It also has the same cross-platform features as Qt. For the desktop version program with low performance requirements, a piece of code gets the web version and the desktop version of each platform at the same time, and the development efficiency is unmatched by other programs. This is a trend that most people are optimistic about.

Iv. Introduction to Electron

(a) Application program structure

Figure 5 Electron’s architecture

Electron consists of three main components:

  1. Chromium is used to display web content.
  2. Node.js is used by local file systems and operating systems.
  3. Custom APIs are used to use OS native functions that are often needed.

Developing an application in Electron is like building a node.js application with a web interface. Think of vscode and it becomes instantly clear.

Main process and renderer process

Electron has two kinds of processes: Main and Rendererer.

The Main process, also known as the Main process, is usually a file named main.js that is the entry file for each Electron application. It controls the entire life cycle of the App, from opening to closing. It also manages native system elements such as menus, menu bars, the Dock (a bar that is generated at the bottom of the screen when the software launches) and trays. The main process is responsible for creating each render process of the APP. And the entire Node API is integrated into it. The main process file for each application is specified in the main property in package.json. This is where the program knows what files to execute at startup. The Rendererer process, also called the Rendererer process. In Chromium, this process is called a “browser process”. It was renamed in Electron to avoid confusion with the renderer process. Unlike the main process, it can have more than one, each running in a separate process. They can also be covered up. In normal browsers, web pages usually run in a sandbox environment and cannot use native resources. However, Electron users can perform some low-level interactions with the operating system on the page with the support of the Node.js API.

  1. The main process passes the creationBrowserWindowExample to create a web page. eachBrowserWindowThe instance runs the web page during its rendering. When aBrowserWindowWhen the instance is destroyed, the corresponding rendering process is terminated.
  2. The main process manages all web pages and their corresponding renderers.
  3. The renderer process can only manage each corresponding page. Crashing in one rendering process does not affect other rendering processes.
  4. The render process passesIPCCommunication with the main process is performed on the web pageGUIOperation. Due to security concerns and possible resource leakage, call directly from the renderer process with localGUIRelated to theAPIBe constrained.

To talk about two processes, it must involve interprocess communication. This can be done through interprocess communication modules: ipcMain and ipcRenderer.

ipcMain

Asynchronous communication from the main process to the renderer. Messages can be sent from the main process to the renderer.

  1. When sending a message, the event name ischannel
  2. This parameter is required when synchronizing messages are returnedevent.returnValue.
  3. You can useevent.reply(...)Send an asynchronous message back to the sender.
ipcRenderer

Asynchronous communication from the renderer process to the main process. Here is an example of the renderer communicating with the main process:

Synchronous:

// In the render process
const { ipcRenderer } = require('electron')
ipcRenderer.on('main-reply'.(event, arg) = > {
  console.log(arg) // "main reply message"
})
ipcRenderer.send('render-main-message'.'Message from Render')
Copy the code
// In the main process
const { ipcMain } = require('electron')
ipcMain.on('render-main-message'.(event, arg) = > {
  console.log(arg) // "Message from render"
  event.reply('main-reply'.'Reply message from Main')})Copy the code

Asynchronous:

// In the render process
const { ipcRenderer } = require('electron')
console.log(ipcRenderer.sendSync('render-main-message'.'Message from Render')) // A message from render
Copy the code
// In the main process
const { ipcMain } = require('electron')

ipcMain.on('render-main-message'.(event, arg) = > {
  console.log(arg) // A message from render
  event.returnValue = 'Message from Render'
})
Copy the code

The renderer sends a message, and the main process receives the message and replies with the message. The main difference is that one is asynchronous and the other is synchronous.

Electron API

The Electron API is assigned based on process type. This means that some modules can be used from the main program or renderer, and some modules can be used from both. The Electron API documentation specifies the procedures each module can use. For example, to access the Electron API in two processes, we need the module it contains:

const electron = require('electron')
Copy the code

To create a window, call the BrowserWindow class, which can only be used in the main process:

const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
Copy the code

To send messages from the renderer process to the main flow, use the IPC module:

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

ipcMain.on('event'.(event, args) = > {
  console.log('The data received is:', args)
})
// In the render process
const { ipcRenderer } = require('electron')

ipcRender.send('event'. args)Copy the code
Node.js API

Note: To access the Node.js API from the rendering process, you need to set the nodeIntegration option to True.

Electron displays full access to the Node.js API and its modules in the main and renderer processes. For example, I can read all files from the root directory:

const fs = require('fs')

const root = fs.readdirSync('/')

console.log(root)
Copy the code

To use the Node.js module, you need to install it as a dependency:

npm install --save minio
Copy the code

Then, in the Electron application, import the module:

var Minio = require('minio')
Copy the code

The electron template provided on the official website is electron-quick-start. The command for starting the electron template is as follows:

Clone sample project repository
$ git clone https://github.com/electron/electron-quick-start

# Enter this warehouse
$ cd electron-quick-start

Install dependencies and run
$ npm install && npm start
Copy the code

Figure 6. The electron-quick-start template project

This template does not integrate any front-end framework, and the development efficiency is terrible.

For React developers, check out the electron-react- Boilerplate (github.com/electron-re… For vUE developers, check out electron-vue (github.com/SimulatedGR…

Five, the Electron – vue

Construct the electron application template code based on VUE.

The purpose of this project is to avoid using VUE to manually set up the Electron application. Electric-vue makes full use of vue-CLI as a scaffolding tool, plus webpack, electric-Packager, or electric-Builder with vue-Loader, and some of the most commonly used plug-ins, For example, vuE-Router and VUex.

The advantages:

  1. Basic project structure with a singlepackage.jsonSet up the
  2. Detailed documentation
  3. usevue-cliProject scaffolding
  4. Out of the boxVuePlug-in (axios.vue-electron.vue-router.vuex)
  5. Preinstall development toolsvue-devtoolsdevtron
  6. useelectron-packagerelectron-builderEasily package applications
  7. appveyor.yml.travis.ymlThe configuration is used toelectron-builderAutomatic deployment of
  8. Ability to generate web page output for use in browsers
  9. The convenientNPMThe script
  10. Using portable thermal updates (Hot Module Replacement)webpackvue-loader
  11. inelectronmainRestart the main process when it is modified
  12. Support the use ofvue-loaderHTML/CSS/JSThe preprocessor
  13. The default supportstage-0ES6
  14. usebabiliAvoid full decompilation toES5
  15. ESLint(supportstandardairbnb-base)
  16. Unit testing (useKarma + Mocha)
  17. End to end testing (usingSpectron + Mocha)

(1) Starting

It is a template for vue-CLI and contains multiple options that the final scaffolding can be customized. Node @^7 or later is required for this project. Electron – Vue officially recommends YARN as the package manager because it can handle dependencies better and can use YARN Clean to help reduce the size of the final build file.

Install vuE-CLI scaffolding:

npm install -g vue-cli
vue init simulatedgreg/electron-vue my-project
Copy the code

Install dependencies and run the program:

cd my-project
yarn # or npm install
yarn run dev # or npm run dev
Copy the code

Create a project as follows:

Figure 7 Creating the electron-vue project

The Electron-vue-case2 was successfully installed using the Electron-vue template. After starting the application:

Figure 8. The electron- Vue template project

(II) Project structure

The project structure is different from the official Vuejs-Templates/Webpack setup.

A single package.json setting

Not long ago, two package.json Settings were required, but, thanks to the efforts of @electron-userland, Electron – Packager and electron- Builder now fully support a single package.json setup.

About main process

During development, you may have noticed SRC /main/index.dev.js. This file is dedicated to developing and installing development tools. In principle, this file should not be modified, but can be used to extend your development requirements. During the build process, WebPack steps in and creates a bundle with SRC /main/index.js as the entry file for the bundle. The file tree

Organizational structure

Note: Some files or folders may differ depending on the Settings selected in vue-CLI scaffolding.

My - project ├ ─. Electron - vue │ └ ─ < build/development >. Js files ├ ─ build │ └ ─ the ICONS / ├ ─ dist │ ├ ─ electron / │ └ ─ web / ├ ─ Node_modules / ├ ─ SRC │ ├ ─ the main │ │ ├ ─ index. The dev. Js │ │ └ ─ index. The js │ ├ ─ the renderer │ │ ├ ─ components / │ │ ├ ─ the router / │ │ ├ ─ store / │ │ ├ ─ App. Vue │ │ └ ─ main. Js │ └ ─ index. The ejs ├ ─ static / ├ ─ test │ ├ ─ e2e │ │ ├ ─ specs / │ │ ├ ─ index. The js │ │ └ ─ Utils. Js │ ├ ─ unit │ │ ├ ─ specs / │ │ ├ ─ index. The js │ │ └ ─ karma. Config. Js │ └ ─. Eslintrc ├ ─. Babelrc ├ ─. Eslintignore ├ ─ .eslintrc.js ├─.├ ─ package.json ├─ download.txtCopy the code

Product build

App. Asar ├ ─ dist │ └ ─ electron │ ├ ─ static / │ ├ ─ index. The HTML │ ├ ─ main. Js │ └ ─ the renderer. Js ├ ─ node_modules / └ ─ package.jsonCopy the code

Almost everything, so to speak, is removed in the final product build. This is almost mandatory when distributing electron, because you don’t want users to download bloaty software with huge files.

Rendering process

Public and non-business VUE components go into SRC/Renderer/Components.

The vUE component of the business goes into SRC/Renderer /views.

A common organizational practice when creating child components is to place them in a new folder with the name of their parent component. This is especially useful when coordinating different routes.

In short, vue-Router is more useful for creating a Single Page Application when doing electron. If not, you’re just managing a bunch of BrowserWindows and passing information between them.

Routes are saved in the SRC/renderer/router/index. The js when using the vue – the router, do not use HTML 5 historical patterns. This mode is strictly for providing files over HTTP, and the File protocol cannot be used normally, but Electron uses this protocol to provide files in a production build. The default hash mode is exactly what we need.

Electron – vue using vuex module structure to create multiple data storage, and stored in the SRC/renderer/store/modules.

Multi-module data storage is great for redundant organization without considering cross-infection of irrelevant business data. But don’t worry about the import the annoyance every data, because the renderer/SRC/store/modules/index, js help us deal with these problems! This simple script to SRC/renderer/store/index, js import all of our module.

The main process

In Electron, the process of running the package.json main script is called the main process. A script running in the main process can display its graphical interface by creating a Web page. Since the main process is essentially a complete Node environment, there is no initial project structure other than the following two files.

src/main/index.js

This file is the main file for your application, and electron also launches from here. It is also used as an entry file for WebPack product builds. This is where all main work should start. app/src/main/index.dev.js

This file is used specifically for the development phase, because it installs electron-debug and vue-devTools. This file generally does not need to be modified, but it can be used to extend the requirements you develop.

Since the main process is bound using Webpack, using __dirname and __filename will not give you an expected value at production time. During production, main.js is placed in the dist/electron folder. __dirname and __filename should be used accordingly.

Electron -vue contains three separate Webpack configuration files located in the.electron-vue/ directory. Apart from the optional use of Web output, main and Renderer are similar during installation. Both use babel-preset-env for features of node@7, use babili, and treat all modules as externals.

For the main process of electron. This configuration is fairly simple, but does include some common Webpack practices. . Electron – vue/webpack. The renderer. Config. Js for electron process of the renderer. This configuration is used to process your Vue application, so it contains vue-Loader and many other configurations found in the official Vuejs-Templates/Webpack template.

One important thing about this configuration is that you can whitelist a particular module, rather than treating it as externals for webpack. There are not many cases that require this functionality, but in some cases, for vue UI libraries (element-UI, etc.) that provide original *.vue components, they need to be whitelisted so that vue-Loader can compile them. Another use case is to use the WebPack alias, such as setting up the VUE to import the full build + run environment. Therefore, Vue is already in the whitelist.

. Electron – vue/webpack. Web. Config. Js source code for the browser to build your renderer process. If you need to publish code online, this configuration is a great starting point. Electron -vue does not support much other Web output. Issues related to Web output are likely to be delayed or closed.

(3) Build the electron application

Electric-vue supports using electric-Packager and electric-Builder to build and distribute your production-phase programs. Both build tools are supported by the awesome @electronic-Userland community, and each is well documented. During vue-CLI scaffolding, you will be asked which builder you want to use. If you’re just starting out with the electron application or just need to create a simple executable, then the electron Packager is for you. If you are looking for a complete installer, support for automatic updates, CI builds using Travis CI and AppVeyor, or automatic rebuild of native Node modules, then you will need the auto-Builder. For a detailed update strategy, read my article Electron Automatic Update.

6. Problems existing in development

(a) More and more memory occupation, running slower and slower

background

When the application is stored for a long time, it will become more and more jammed. After opening the task manager, it is found that the Electron application occupies a large amount of memory.

Analysis of the

Much of this is because Electron encapsulates electron.js at the expense of memory footprint. So, it’s a bit of a memory hog, the Windows version starts with 4 threads, plus the business code uses some class libraries.

The solution

Electron’s website also has introduced (www.electronjs.org/docs/tutori…

  1. Load modules carefully
  2. Prematurely loading and executing code
  3. Blocking the main process
  4. Blocking the render process
  5. Polyfills unnecessarily
  6. Unnecessary or blocked network requests
  7. Package your code

The electron program shows the file browser

background

When you start the electron vue project, you’ll often see something like this:

Figure 9 file browser

Why is the file browser displayed? Where did my app go?

Analysis of the

The SRC /renderer error is probably a SRC /renderer inclusion error.

Errors in the SRC /renderer will cause conflicts with ESLint on the first run. Then, an invalid Webpack renderer.js is generated, which interrupts the HtmlWebpackPlugin to create index.html. Because webpack-dev-server has no index.html to serve, the server fails and the program returns to the file browser.

The solution

Check your terminal for a red-hot error, fix the error, and then refresh the Electron app with CommandOrControl+R to see the familiar app page.

(三) ReferenceError: process is not defined

background

When you first start the electron-vue project you will encounter Process is not defined.

The specific error is shown in the figure below:

ReferenceError: process is not defined
  
- index.ejs:11 eval[.]/[html-webpack-plugin]/lib/loader.js! ./src/index.ejs:11:2 - index.ejs:16 module.exports [.]/[html-webpack-plugin]/lib/loader.js! ./src/index.ejs:16:3 - index.js:284 [electron-demo]/[html-webpack-plugin]/index.js:284:18 - runMicrotasks - task_queues.js:93 processTicksAndRejections internal/process/task_queues.js:93:5Copy the code
Cause analysis,

no

The solution

The Internet says a reduced version is also ok.

My local Node version is 12.3.1, and everything seems to be fine until I update it to 12. It looks like the latest version of Node has an error.

Besides, FROM this issue (github.com/SimulatedGR… Webpack. Web. Config. Js and webpack. The renderer. Config. The js HtmlWebpackPlugin simply add the following code:

      // Parameters required by the template
      // https://github.com/jantimon/html-webpack-plugin/blob/master/examples/template-parameters/webpack.config.js
      templateParameters(compilation, assets, options) {
        return {
          / / compile
          compilation: compilation,
          webpack: compilation.getStats().toJson(),
          webpackConfig: compilation.options,
          htmlWebpackPlugin: {
            files: assets,
            options: options
          },
          process,
        };
      },
Copy the code

How does Electron open devTools

background

Application development, if there is no developer tool DevTools, then the development efficiency will be greatly reduced, using developer tools, no matter in debugging or testing, like dragon sea, with ease.

The solution

Open and close DevTools using electron’s webContents object. In the following example, I’m operating on mainWindow.webContents from createWindow in main.js.

Open the devtools:

mainWindow.webContents.openDevTools()

By default, developer tools are located where they were last opened (left, right, or below). Depends on the last state, but not separated, and not at the top.)

Open devTools on the right side of the application:

mainWindow.webContents.openDevTools({mode:'right'})

Open devTools at the bottom:

mainWindow.webContents.openDevTools({mode:'bottom'})

Open devTools on the left:

mainWindow.webContents.openDevTools({mode:'left'})

Open devTools in separate state:

mainWindow.webContents.openDevTools({mode:'detach'}) mainWindow.webContents.openDevTools({mode:'undocked'})

In both cases, DevTools is not attached to the main screen, and is in a separate state. But undocked, the developer tool can be incorporated into the main screen. In detach, it’s permanent separation. That’s the difference between the two.

Close the devtools:

mainWindow.webContents.closeDevTools()

(5) The electron dependent packet cannot be found

background

Error: The electron packet cannot be found when the dependency package is installed.

throw new Error('Electron failed to install correctly, please delete node_modules/electron and try installing again')

Cause analysis,

It was found that Electron must be installed in devDependencies.

To find the source location of the code, see node_modules\electron\index.js:

var pathFile = path.join(__dirname, 'path.txt')

function getElectronPath () {
  if (fs.existsSync(pathFile)) {
    var executablePath = fs.readFileSync(pathFile, 'utf-8')
    if (process.env.ELECTRON_OVERRIDE_DIST_PATH) {
      return path.join(process.env.ELECTRON_OVERRIDE_DIST_PATH, executablePath)
    }
    return path.join(__dirname, 'dist', executablePath)
  } else {
    throw new Error('Electron failed to install correctly, please delete node_modules/electron and try installing again')}}module.exports = getElectronPath()
Copy the code

If you install under Dependencies, you don’t have a path.txt. Then Node cannot read the file, and the electron installation fails.

The solution

Reinstall:

npm install electron --save-dev
Copy the code

(vi) Electron – Vue cannot change the state of VUEX

background

After the vuex plug-in is added to Electron-vue, it cannot be used. There is no way to change vuEX data state between components.

The solution

First of all, the vuex-electron document reads:

In case if you enabled createSharedMutations() plugin you need to create an instance of store in the main process. To do it just add this line into your main process (for example src/main.js):import './path/to/your/store'

Mutations() means that if you enable the createSharedMutations() plug-in, you need to create an instance of Store in the main process, adding the store instance to the main process (e.g., SRC /main.js).

See SRC \renderer\store\index.js for whether the createSharedMutations plug-in is enabled:

const store = new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
  plugins: [
    createPersistedState(),
    createSharedMutations()
  ],
  strict: process.env.NODE_ENV ! = ='production'
})
Copy the code

SRC \main\index.js SRC \main\index.js SRC \main\index.js

import '.. /renderer/store'
Copy the code

Restart the program.

If multi-window sharing is not required in the application, there is no need to add the Stote instance to the main process, and remove the createSharedMutations method from the Store instance.

Element component cannot be used in electron-vue

background

The application needs to integrate third-party UI components, such as Element-UI, but cannot be used once the component is imported.

The solution

Check out this issue (github.com/SimulatedGR…

Okay, I am able to reproduce this issue now. It seems element-ui falls into that category of modules that need to be white-listed. If you go into .electron-vue/webpack.renderer.config.js, around line 21, you can add element-ui to the whiteListedModules list. After making that change, tooltips will work as expected.

Probably mean seems element – the UI does not belong to that kind of module, need those listed in the “white list”, if you enter the electron – vue/webpack. The renderer. Config. Js. Find let whiteListedModules on line 21 or so and add element-UI to it:

let whiteListedModules = ['vue'.'element-ui'.'vuetify']

let rendererConfig = {
  devtool: '#cheap-module-eval-source-map'.entry: {
    renderer: path.join(__dirname, '.. /src/renderer/main.js')},externals: [
    ...Object.keys(dependencies || {}).filter(d= >! whiteListedModules.includes(d)) ],Copy the code

One important thing about this configuration is that a particular module can be whitelisted rather than treated as externals for webpack. There are not many cases that require this functionality, but in some cases, for vue UI libraries that provide original *.vue components, they need to be whitelisted so that vue-Loader can compile them. Another use case is to use the WebPack alias, such as setting up the VUE to import the full build + run environment. Therefore, Vue is already in the whitelist.

(8) Shortcut keys for custom window in the Electron frameless window

background
mainWindow = new BrowserWindow({
    height: 720.minHeight: 720.minWidth: 1080.width: 1080.frame: false
  })
Copy the code

After setting frame to false, Electron hides the toolbar and makes all Windows bezel-less. As a result, the necessary minimize, maximize, and close window shortcuts are missing.

The solution

Start by writing three buttons to the Windowoperate.vue page and binding the events:

Asynchronous communication from the renderer process to the main process.
Use some of the methods it provides to send synchronous or asynchronous messages from the renderer (web page) to the main process.
const {
    ipcRenderer
} = require('electron')

onMinusSm () {
    ipcRenderer.send('min')
},
onRectangle () {
    ipcRenderer.send('max')
},
onCross () {
    ipcRenderer.send('window-close')}Copy the code

Send synchronization messages to the main process and trigger specific events. The onMinusSm method ipcRenderer sends min events, and the main process can listen for min events.

In the SRC/main/index. In js:

const {
  // Asynchronous communication from the main process to the renderer.
  ipcMain
} = require('electron')

ipcMain.on('window-close'.function () {
  // close Cannot close the program
  // mainWindow.close()
  app.exit()
})
ipcMain.on('min'.function () {
  // Minimize the window
  mainWindow.minimize()
})
ipcMain.on('max'.function () {
  if (mainWindow.isMaximized()) {
    // Restore the window from its minimized state to its previous state.
    mainWindow.restore()
  } else {
    // Maximize the window.
    mainWindow.maximize()
  }
})
Copy the code

The main process listens for three events of the renderer. For example, the main process listens for min and triggers the method of minimizing the window. Note: mainwindow.close () does not close the program, you need to use app.exit() to do so.

(nine) monitor window state, dynamic change window maximization icon

background

The previous problem solved the window minimize, maximize, close window shortcut keys. However, shortcuts to dynamically maximize the window are missing.

The solution

Listen for the main-window-max event in windowoperate. vue to trigger the display of the miniaturized icon. Listen for the main-window-unmax event in windowoperate. vue to trigger the display of the maximized icon:

mounted () {
    // Monitor window state, dynamic change picture
    this.changeWin()
  },

changeWin () {
    ipcRenderer.on('main-window-max'.() = > {
    this.isRectangle = false
    })
    ipcRenderer.on('main-window-unmax'.() = > {
    this.isRectangle = true})},Copy the code

Have the main process listen for Windows maximize and unmaximize to send event messages to child processes at SRC /main/index.js:

function createWindow () {} to insert// Listen to the window state and send a message to the renderer
  // When the window is maximized
  mainWindow.on('maximize'.function () {
    mainWindow.webContents.send('main-window-max')})// Triggered when the window exits from the maximized state
  mainWindow.on('unmaximize'.function () {
    mainWindow.webContents.send('main-window-unmax')})Copy the code

Electron Uncaught TypeError: Cannot read property ‘app’ of undefined

background

The electron- Vue project has a few bugs that will cause an error when starting the project:

Uncaught TypeError: Cannot read property 'app' of undefined at new ElectronStore (E:\eleftron-autoupdate-demo\node_modules\electron-store\index.js:8:55) at a (E:\eleftron-autoupdate-demo\node_modules\vuex-electron\dist\persisted-state.js:1:1365) at a (E:\eleftron-autoupdate-demo\node_modules\vuex-electron\dist\persisted-state.js:1:1102) at E:\eleftron-autoupdate-demo\node_modules\vuex-electron\dist\persisted-state.js:1:3174 at E:\eleftron-autoupdate-demo\node_modules\vuex\dist\vuex.common.js:425:46 at Array.forEach (<anonymous>) at new Store (E:\eleftron-autoupdate-demo\node_modules\vuex\dist\vuex.common.js:425:11) at eval (webpack-internal:///./src/renderer/store/index.js:17:64) at Module.. /src/renderer/store/index.js (http://localhost:9080/renderer.js:1583:1) at __webpack_require__ (http://localhost:9080/renderer.js:791:30)Copy the code
The solution

Add the enableRemoteModule attribute to the main window using the remote module:

mainWindow = new BrowserWindow({
    height: 563.useContentSize: true.width: 1000.webPreferences: {
      nodeIntegration: true.enableRemoteModule: true}})Copy the code

conclusion

This article covers the history of desktop applications, the history of Electron, and the project of electron vue.

The Electron application structure is divided into the main process and the rendering process, the Electron API and the NodeJS API. From introducing the electron- Vue project structure to building the application, getting started with the Electron project and completing an electron project (in progress).

The understanding of electron is deepened by analyzing some problems existing in development.

May you work quietly and surprise everyone!

reference

The electron’s official website

Electron – vue website

Finally, I hope you must point to like three times.

Follow my blog: blog address