This is the 17th day of my participation in the August More text Challenge. For details, see: August More Text Challenge
Now the development of the front end has reached the era of the big front end. The big front-end era is the era of WEB unification. Using HTML5 or 6 or even 7, it can not only develop traditional websites and make cool dynamic effects of WEB pages, but also realize BS architecture applications, develop mobile WEB applications, mobile app applications, mobile Native applications, and smart devices (such as wearable smart watches). While using Node.js can also achieve back-end development. You can even develop desktop applications.
Next, use Eletron to complete a calculator project from zero
Set up the project
Presents a desktop application interface
-
Electron download
npm install electron --save-dev npm install electron -g Copy the code
The introduction of
const { app,BrowserWindow } = require('electron')Copy the code
-
App’s ready event: main.js
-
The electron automatically triggers the ready event
-
In this event you can create the electron window
app.on('ready'.() = > { hm_createWindow() // Create the window function call }) Copy the code
-
-
Creation of the electron application window (hm_createWindow function)
-
The introduction of BrowserWindow
-
Create a window object using the BrowserWindow function
-
Configure the window
win = new BrowserWindow({ width:390.height:670.// Set the title title:'Intelligence Calculator' }) Copy the code
-
-
Common operations in the electron window
-
Loads other specified pages
win.loadURL(path.join(__dirname,'./views/index.html')) // The path module is used to generate the path Copy the code
-
Starting the Debugging Tool
win.webContents.openDevTools() Copy the code
-
Adds an event to close the window
win.on('close'.() = > { // Implement the operation after closing the window win = null // Close the main window as well as the entire application app.quit() }) Copy the code
-
-
The electron application starts
- electron main.js
- electron .
- Add the package.json script configuration: “start”: “electron main.js”, then use NPM start to start electron
Add the application’s menu item
-
To add a Menu item: menu. buildFromTemplate
-
Create a menu item template
-
Label: Menu item text setting
-
Click: Click the event, specifying the event handler
-
Role: Specifies the role of the menu item
-
Accelerator: a shortcut that triggers the current menu item
-
Set a submenu item: Use submenu
let template = [ { label:'Intelligence Calculator'.submenu:[ { label:'exit'.accelerator:'F11'.// Role String (optional)- Built-in event that defines the behavior of the menu item and is ignored when specifying the click property role:'quit'.click:() = > { app.quit() } } ] } ] Copy the code
-
-
Add menu to application:
Menu.setApplicationMenu(menu) Copy the code
Main process and rendering process
- Main process: The process that runs the package.json and main scripts in Electron is called the main process. For example, the main.js file belongs to the main process, and the js files imported directly into the main.js file also belong to the main process (e.g. Require (‘./mainProcess/menu.js’)).
- Rendering process: Electron uses Chromium’s multi-process mechanism to render pages. Each page has its own process, which is called the rendering process. For example, if the index.html file is loaded in the main.js file, the index.js introduced in the index.html file belongs to the rendering process
- Common ways to communicate between the main process and the rendering process :(note that all of these methods are valid only after the main process has created a BrowserWindow)
- IpcRenderer is used for the rendering process
- Ipcrenderer. on(channel, listener) –> channel is the event channel, a string.
- Ipcrenderer.send (channel, data) –> The same concept, used to send asynchronous messages to ipcMain
- IpcMain is used by the main process to respond to messages sent from the rendering process
- Ipcmain. on(channel,listener) –> Responds to the same channel from ipcRender
- Event.sender: The main process listens to the messages sent by the renderer process and uses the event.sender-send () method in the response event callback function to send messages to the renderer process
- webContentIpcMain itself cannot send events directly, only events that respond to the event callback, so if we want the main process to send the message first we can use WebContent. This WebContent is a method in a BrowserWIndow instance
- Webcontent.send (channel,data) –> The main process sends a message to the rendering process
- IpcRenderer is used for the rendering process
- Data is shared between different rendering processes
- We can simply use the APIS provided in HTML5, such as localStorage and sessionStorage
- In electron, we can store an object as a global variable in the main process and manipulate it in the render process via the remote module
Complete the menu item function: color setting
-
Added set color menu item
{ label:The 'color'.click:() = > { wh_createColorWindow() } } Copy the code
-
Add click event – Create Settings Color window
function wh_createColorWindow(){ let win = new BrowserWindow({ width:250.height:100.title:The 'color' }) // Load the About page win.loadURL(path.join(__dirname,".. /views/color.html")) // Settings no longer require a menu block win.setMenu(null)}Copy the code
-
Business implementation: the main process receives the data passed by the rendering process
-
IpcRenderer is introduced into the rendering process
const {ipcRenderer} = require('electron') Copy the code
-
Emit events via ipcRenderer for the main process to listen for processing
// The render process sends a message to the main process ipcRenderer.send('wh_colortomain',currentColor) Copy the code
-
-
Business implementation: the rendering process receives the data passed by the main process
-
Introduce ipcMain in the main process: the main process uses ipcMain to receive messages from the rendering process
-
Listen for events emitted during the render process:
// The main process listens for messages sent by the rendering process ipcMain.on('wh_colortomain'.(event,color) = > { // Set the style: The main process sends a message to the render: Set the style of the DOM elements in the index.html page win.webContents.send('wh_setColor',color) }) Copy the code
-
Business implementation: color setting is handled by a separate module
// The render process listens for messages sent by the main process and processes them ipcRenderer.on('wh_setColor'.(event,color) = > { // Set the corresponding element style result_text.style.color = color // Store the color set by the current user to local storage localStorage.setItem('userColor',color) }) Copy the code
-
Complete the menu item function: font size setting
-
Add event
{ label:'Font reduction'.accelerator:'F12'.click:(item,cwindow,event) = > { cwindow.webContents.send('sub')}}Copy the code
-
Complete event processing
ipcRenderer.on('sub'.() = > { // Get the font size let fontSize = window.getComputedStyle(result_text,null).fontSize // Adjust the font size let fontNum = fontSize.replace('px'.' ') - 0 - 3 / / reset result_text.style.fontSize = fontNum + "px" localStorage.setItem('userFontSize',fontNum) }) Copy the code
Implement desktop hide to tray
-
Tray module: The tray module can realize the function of system tray
-
Our requirements: hide the window when clicking “close”, and hide the task bar as well, and display the interface when clicking the icon in the system notification area
-
Const {Tray,Menu} = require(‘electron’)
-
Code: minProcess/tray. Js
Tray can be used to implement notification bar ICONS const { Menu, Tray, dialog } = require('electron') const path = require('path') function createTray(win) { let appIcon = new Tray(path.join(__dirname, '.. /images/lar.jpg')) // Build a menu item for the icon const menu = Menu.buildFromTemplate([ { label: 'off'.click: () = > { dialog.showMessageBox({ type: 'warning'.title: 'Exit prompt'.message: 'Do you really need to quit? '.buttons: ['sure'.'cancel']},(index) = > { if (index == 0) { appIcon.destroy() app.quit() } }) } } ]) appIcon.on('click'.() = > { // Here we simulate the desktop application by clicking the icon in the notification area to open and close the applicationwin.isVisible() ? win.hide() : win.show() win.isVisible() ? win.setSkipTaskbar(false):win.setSkipTaskbar(true); }) // Set the text prompt when the mouse moves up appIcon.setToolTip('Dark Horse Programmer') // Set the menu item appIcon.setContextMenu(menu) } // Expose members module.exports = createTray Copy the code
Complete simple calculation function
-
Bind events for DOM elements
<div class="calculate"> <div class="item" onClick="main.reset()">AC</div> <div class="item" onClick="main.clickopt('+/-')">+/-</div> <div class="item" onClick="main.clickopt('%')">%</div> <div class="item orange" onClick="main.clickopt('/',this)">present</div> <div class="item" onClick="main.clickNum('7')">7</div> <div class="item" onClick="main.clickNum('8')">8</div> <div class="item" onClick="main.clickNum('9')">9</div> <div class="item orange" onClick="main.clickopt('*',this)">x</div> <div class="item" onClick="main.clickNum('4')">4</div> <div class="item" onClick="main.clickNum('5')">5</div> <div class="item" onClick="main.clickNum('6')">6</div> <div class="item orange" onClick="main.clickopt('-',this)">-</div> <div class="item" onClick="main.clickNum('1')">1</div> <div class="item" onClick="main.clickNum('2')">2</div> <div class="item" onClick="main.clickNum('3')">3</div> <div class="item orange" onClick="main.clickopt('+',this)">+</div> <div class="item large" onClick="main.clickNum('0')">0</div> <div class="item" onClick="main.clickNum('.')">.</div> <div class="item orange" onClick="main.calc()">=</div> </div> Copy the code
-
Click the Numbers
clickNum(num) { res = document.querySelector('.result-text'), isPoint = num === '. '; // Convert numbers to strings result = result.toString(); // If a decimal point is entered and the result already has a decimal point if (result.indexOf('. ')! = = -1 && isPoint) { return; } result = result + num; res.innerHTML = result; } Copy the code
-
Click operator
clickopt(ope) { res = document.querySelector('.result-text'); switch (ope) { case '+ / -: res.innerHTML = result = math.eval(result + '*-1'); break; case The '%': res.innerHTML = result = math.format(math.eval(res.innerHTML + '/ 100'),4); break; default: res.innerHTML = result = result + ope break; }}Copy the code
-
reset
reset() { res = document.querySelector('.result-text'); res.innerHTML = '0'; result = ' ' } Copy the code
-
The calculation results
calc(){ res = document.querySelector('.result-text'); res.innerHTML = result = math.eval(result) } Copy the code
Application packaging
Package as an executable file
- The installation
electron-packager
: NPM install –save-dev electron-packager - The formal packaging
-
Package directly using the command
- Electron -packager < Application directory >< Application name >< Packaging platform > –out=< Output directory >< Schema >< Application version >< Ignore files >< icon > –overwrite
- Configuration description :–platform
- Win: packing platform: – platform = win32 | architecture: – the arch = x64 | icon: — icon = * *. Ico
- MAC: packing platform: – platform = Darwin | architecture: – the arch = x64 | icon: — icon = * *. Cins
-
Configure the package.json command to implement packaging
"packagewin": "electron-packager ./ heima --platform=win32 --out=./dist --arch=x64 --app-version=1.0.1 --icon=./images/icon.ico --overwrite".Copy the code
-
Package as an installation package
-
NPM I electron- Builder-g
-
Description: Electron – Builder can package an application as an installation file, such as.exe. DMG for Windows or.dmg for MAC
-
Realize the configuration of electron- Builder
"build": { "appId": "com.itcast-wu.app"."directories": { "app": ". /" }, "productName": "Guangzhou - Calculator"."dmg": { "icon":"./images/mac.icns"."window": { "x": "200"."y": "150"."width": 500."height": 400}},"mac": {"icon":"./images/mac.icns"}, "win": {"icon":"./images/icon.ico"}}Copy the code
Add script configuration:
"scripts": { "test": "echo \"Error: no test specified\" && exit 1"."packagewin": "electron-packager ./ heima --platform=win32 --out=./dist --arch=x64 --app-version=1.0.1 --icon=./images/icon.ico --overwrite"."buildmac": "electron-builder --platform=mac --arch=x64"."buildwin": "electron-builder --platform=win --arch=x64" } Copy the code
Run command:
npm run buildwin Copy the code