preface
The Web side can do a lot of things, but when it comes to operating systems, it can be a bit overwhelming. Some time ago when developing a Web system, encountered a similar situation. We need to get some information about the computer’s operating system, such as the MAC address. Our Web system is completely on the server, through the browser to run, but through the Web side can not directly achieve the effect we want.
Problems are left to people to solve. After discussion among colleagues, because the system itself is not complex, and to carry out rapid development. It was decided to use Electron + the original Web system page to solve problems involving operating system information.
This article summarizes some of the problems AND solutions I have encountered with Electron.
What is Electron?
Build cross-platform desktop applications using JavaScript, HTML, and CSS – this is the introduction to Electron
Electron 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. – zhihu
Electron puts a shell on the Node.js environment for Web projects, enabling us to call the rich API of Node.js. This way we can write desktop applications in JavaScript, extending a lot of things we can’t do on the Web.
How do YOU build Electron?
Building Electron is as simple as looking directly at official documentation or using an existing wheel. Basically, they fall into two broad categories: templates and command-line tools. These two ways have their own advantages, the specific choice of which way to according to their actual situation. For me, because the project I’m going to do already has web pages, these templates are basically not applicable. In order to catch up with the schedule, I will directly refer to the official website for introduction — build your first -electron- application, plus the original code to build the project.
Here are some common build templates and command-line tools
The template
- Electron -react-boilerplate: electron + react
- electron-vue: electron + vue
- .
Command line tool
- Build your first Electron app: official website tutorial
- Electron forge: A sophisticated tool for building modern electron applications
- .
A case in point
The following is a basic Electron project that the rest of the code expands on.
npm install --save-dev electron
Copy the code
The general structure
├─ ├─ download.txt └─ ├─ download.txtCopy the code
package.json
{
"name": "demo"."version": "1.0.0"."description": "electornDemo"."main": "main.js"."scripts": {
"start": "electron ."
},
"author": "xmanlin"."license": "MIT"."devDependencies": {
"electron": "^ 9.0.0"}}Copy the code
main.js
const {app, BrowserWindow} = require('electron')
app.on('ready'.function createWindow () {
// Multiple renderers can be created
let win = new BrowserWindow({
width: 800.height: 600,
})
win.show()
// Web pages in the renderer process can load local files
win.loadFile('index.html')
// Remember to clear this variable after the page is closed to prevent memory leaks
win.on('closed'.function () {
win = null})})// Close the main process after all the pages are closed
app.on('window-all-closed', () => {
app.quit()
})
Copy the code
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>demo</title>
</head>
<body>
<div>An electron project</div>
<script>
</script>
</body>
</html>
Copy the code
What are main processes and renderers?
In Electron, the concept of main process and render process is very important. For details, see main process and Render process on the Electron website.
The main process
- run
package.json
In themain
The script process is the main process. - A electron application has one and only one main process.
- The main process can perform guI-related native API operations.
Rendering process
- Electron uses Chromium to present web pages, so Chromium’s multi-process architecture is also used.
- Each Web page runs in its own rendering process.
- use
BrowserWindow
Class starts a renderer process and runs the instance in that process when aBrowserWindow
After the instance is destroyed, the corresponding rendering process is terminated. - Native resources cannot be called in the renderer process, but the renderer process also contains node.js environment, so you can introduce Node.js module, with node.js support, the page and the operating system can do some low-level interaction.
How does the Node.js API get called in the rendering process?
In Electron5.0, renderers cannot call the Node.js API by default.
Main process (main.js)
let win = new BrowserWindow({
width: 800.height: 600.webPreferences: {
nodeIntegration: true.// Set to true to invoke Node.js in the renderer}})Copy the code
How to open developer tools?
Electron uses Chromium, but opening developer tools isn’t like a browser, like F12 by default on Windows.
There are two ways to open the developer tool in Electron:
The first is to set it in the main process, and when it starts the project, the renderer opens developer tools by default
win.webContents.openDevTools();
Copy the code
The second option is to select View -> Toggle Developer Tools from the menu bar of the render process window. (Or just follow the shortcut keys above)
Does the electron console print garble?
We may encounter Chinese garbled characters in the Windows console. When we input CHCP in the Windows console, we can see the current character encoding. The common gb2312 value is 936, and the UTF8 value is 65001. This can be resolved by simply setting package.json.
"start": "chcp 65001 && electron ."
Copy the code
How does the main process communicate with the renderer process?
The main process and the renderer process can communicate with each other through the ipcRenderer and ipcMain modules.
The main process actively sends a message to the renderer
Main process (main.js)
// The main process sends a message to the renderer process, 'did-finish-load': emits an event when the navigation is complete, and the onload event completes
win.webContents.on('did-finish-load', () => {
win.webContents.send('msg'.'Message coming from autonomous process')})Copy the code
Render process (index.html)
<script>
const {ipcRenderer} = require('electron')
ipcRenderer.on('msg', (event, message) => {
console.log(message) // The message comes from the autonomous process
})
</script>
Copy the code
The renderer actively sends a message to the main process
Render process (index.html)
Const {ipcRenderer} = require('electron') ipcrenderer. send('indexMsg',' message from renderer ')Copy the code
Main process (main.js)
const {ipcMain} = require('electron')
ipcMain.on('indexMsg',(event,msg) => {
console.log(msg) // The message comes from the renderer
})
Copy the code
How do renderers communicate with each other?
There are many ways for renderers to communicate with each other, some of which are listed below:
Use the global share attribute
/ / main process
global.sharedObject = {
user: ' '
}
Render process 1
const {remote} = require('electron')
remote.getGlobal('sharedObject').user = 'xmanlin'
// Render process 2
const {remote} = require('electron')
console.log(remote.getGlobal('sharedObject').user) //xmanlin
Copy the code
ipcRenderer.sendTo()
Here are the arguments to ipcrenderer.sendto ()
ipcRenderer.sendTo(webContentsId, channel, [, arg1][, arg2][, ...] ) ipcRenderer.sendTo(windowId,'ping'.'someThing') //webContentsId : Number //channel : String //... args : any[]Copy the code
The specific use
Main process (main.js)
// Create a new renderer
let win2 = new BrowserWindow({
width: 800.height: 600,})// Set a unique ID for the renderer process
win2.id = 2
Copy the code
Render process 1
<script>
const {ipcRenderer} = require('electron')
// Send a message to the renderer with id 2
ipcRenderer.sendTo(2.'msg1'.'Message from Renderer 1')
</script>
Copy the code
Render Process 2
<script>
const {ipcRenderer} = require('electron')
ipcRenderer.on('msg1', (event, message) => {
console.log(message) // Message from renderer 1
})
</script>
Copy the code
Use the main process as a message relay
/ / main process
ipcMain.on('msg1', (event, message) => {
yourWindow.webContents.send('msg2', message);
}
Render process 1
ipcRenderer.send('msg1'.'Message from Renderer 1')
// Render process 2
ipcRenderer.on('msg2', (event, message) => {
console.log(message) // Message from renderer 1})Copy the code
How are projects packaged?
Packing is also an essential step. Here are two mature packing tools: electron packager and electron Builder. These two tools mainly configure it.
electron-packager
We can use the electron packager to package our existing electron application as an exe executable.
Install first
npm install electron-packager --save-dev
Copy the code
After installing the electron packager, configure the basic command. The following is the basic command format in the official document:
electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch> [optional flags...]
Copy the code
Briefly introduce the meaning of each parameter:
- Sourcedir: indicates the path of the project
- Appname: Application name (packaged file name)
- Platform: Determines which platform you want to build the application on (Windows, Mac, or Linux)
platform=win32
On behalf of the Windowsplatform=darwin
On behalf of the Macplatform=linux
On behalf of the Linux
- Arch: Deciding whether to use x86 or X64 or both architectures
- Optional options: Optional options
Here is an example for your reference
package.json
"scripts": { "build32": "Electron packager./ appDemo --platform=win32 --arch=ia32 --out=./app --app-version=1.0.0 --overwrite --icon=./favicon.ico", "build64": "Electron packager./ appDemo --platform=win32 --arch=x64 --out=./app --app-version=1.0.0 --overwrite --icon=./favicon.ico" }Copy the code
These are all packaged for Windows, build32 packaged for 32-bit, build64 packaged for 64-bit. In addition to basic parameters, the meanings of other parameters are as follows:
- –out indicates the directory of the generated file after packaging
- –app-version Specifies the version number of the generated package file
- — Overwrite Deletes the original package file and generates a new package file
- –icon Indicates the icon of the package file
electron-builder
The electric-Builder can be packaged not only as an exe executable but also as an installable program, and has more features than the electric-Packager.
The official website favors YARN for installation
yarn add electron-builder --dev
Copy the code
Of course NPM is also possible
npm install electron-builder --save-dev
Copy the code
Then we can configure
"scripts": {
"pack": "electron-builder --dir"."dist": "electron-builder"
},
"build": {
"productName": "appDemo".// App name in Chinese
"appId": "appDemoId"./ / app id
"directories": { // Package the output folder
"buildResources": "resources"."output": "dist/"
}
"files": [ // The source file remains after packaging
"dist/electron"."node_modules/"."package.json"]."mac": { // MAC package configuration
"target": "dmg"."icon": "icon.ico"
},
"win": { // Windows package configuration
"target": "nsis"."icon": "icon.ico"
},
"dmg": { // DMG file package configuration
"artifactName": "appDemo.dmg"."contents": [{"type": "link"."path": "/Applications"."x": 410."y": 150
},
{
"type": "file"."x": 130."y": 150}},"nsis": { // nsis file package configuration
"oneClick": false."allowToChangeInstallationDirectory": true.// Allows you to change the installation directory
"allowElevation": true.// Allow request promotion. If false, the user must restart setup with the promoted permissions.
"installerIcon": "./build/icons/aaa.ico".// Install icon
"uninstallerIcon": "./build/icons/bbb.ico".// Uninstall the icon
"installerHeaderIcon": "./build/icons/aaa.ico".// Install header icon
"createDesktopShortcut": true.// Create a desktop icon
"createStartMenuShortcut": true.// Create start menu icon
"shortcutName": "xxxx".// Icon name
"include": "build/script/installer.nsh".// The included custom NSIS script is quite useful for building a strict installation process.}},Copy the code
Parameters can also be specified when using the electron builder package
-- MAC, -m, -O, -- macOS MacOS package -- Linux, -l Linux package --win, -w, -- Windows Windows package -- MWL for macOS, Windows and Linux package --x64 x64 (64-- Ia32 Ia32 (32Bit installation package)Copy the code
For all parameters, see Command Line Interface (CLI).
About NSIS, you can also know the following packing method: electron packing process electron-packager + NSIS
How do I set Windows to Max and full screen by default?
Default maximization
// Main process (main.js)
let win = new BrowserWindow({show: false})
win.maximize()
win.show()
Copy the code
The default full screen
// Main process (main.js)
let win = new BrowserWindow({fullscreen: true})
Copy the code
How to customize the menu bar?
You can refer directly to this article – use the Electron custom menu to write in more detail, or you can refer directly to the official documentation. Of course, we can also hide the built-in menu bar and then call the write Electron API to write a menu bar. VSCode, for example, does this. Open VSCode and find the switch developer tool in help. You may find a new world.
How do I obtain the MAC address of the operating system?
This is a call to node.js API to get the MAC address of the system.
var os=require("os");
// Obtain the MAC address
var mac = ' '
var networkInterfaces=os.networkInterfaces();
for(var i in networkInterfaces){
for(var j in networkInterfaces[i]){
if(networkInterfaces[i][j]["family"= = ="IPv4" && networkInterfaces[i][j]["mac"]! = ="00:00:00:00:00:00" && networkInterfaces[i][j]["address"]! = ="127.0.0.1"){
mac = networkInterfaces[i][j]["mac"]}}}Copy the code
reference
www.electronjs.org/docs
Blog.csdn.net/weixin_4276…
www.jianshu.com/p/62c45eddb…
Blog.csdn.net/qq_34803821…
Segmentfault.com/a/119000001…
Juejin. Cn/post / 684490…
The last
This article is the problems I have encountered and the solutions I have found in learning and applying Electron so far. I hope it will be helpful to you. If there are any shortcomings or mistakes, please point them out