Electron
If you can build a website, you can build a desktop application. Electron is a framework for creating native applications using Web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts, and you just have to focus on the core of your application.
Introduce a,
- The Web technology Electron is based on Chromium and Node.js and lets you build applications using HTML, CSS and JavaScript.
- Electron is an open source project maintained by GitHub and an active community of contributors.
- Cross-platform Electron is compatible with Mac, Windows, and Linux, and it builds applications that run on all three operating systems.
Second, an introduction to
- The Electron API Electron API
- Electron Fiddle Electron FiddleThe simplest Electron entry mode.
Electron Fiddle lets you create and perform small Electron experiments. It will greet you when it opens with a quick-start template – change a few things, choose the Electron version you want to run it with, and play around. Then, save your Fiddle as a GitHub Gist or to a local folder. Once you push it to GitHub, anyone can quickly try your Fiddle by simply typing it into the address bar.
- Electron Forge Electron Forge
The command line interface for ambitious Electron applications
npm install -g electron-forge # create a new project electron-forge init my-new-project cd my-new-project electron-forge start Copy the code
- Quick start electron-quick-start
$git clone $git clone//github.com/electron/electron-quick-start# install the dependency and run $NPM install && NPM startCopy the code
- Electron-vue Electron-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.
Iii. Actual combat of the project
1, electron – quick – start
- After clone, NPM I or YARN
- NPM start or electron.
- code
/ / main process
const {app, BrowserWindow} = require('electron') / / introduction
let mainWindow // Define the window variable name
function createWindow () { // Create a window function
mainWindow = new BrowserWindow({
width: 800.height: 600.webPreferences: {
nodeIntegration: true // Whether node is fully supported. Default is true. (with pits)
}
})
mainWindow.loadFile('index.html') // Load a page, either a local page or a web link
//mainWindow.loadURL('https://www.baidu.com');
mainWindow.on('closed'.function () { // Release variables when closed
mainWindow = null
})
}
app.on('ready', createWindow) / / app ready event
app.on('window-all-closed'.function () {
if(process.platform ! = ='darwin') app.quit()
})
app.on('activate'.function () {
if (mainWindow === null) createWindow()
})
Copy the code
2, electron – vue
- vue init simulatedgreg/electron-vue my-project
- yarn
- yarn run dev
3, PDDCJDZ
Entry file main.js (main process)
mainWindow = new BrowserWindow({
width: 1300.height: 800.webPreferences: {
The default value is true. In some cases, nodeIntegeration needs to be turned off to be compatible with dependency loading of Web resources.
nodeIntegration: false.// When set to false, it disables the same origin policy (usually used to test websites) if this option was not set by the developer
webSecurity: false.// Allow an HTTPS page to run resources in HTTP URLS, including JavaScript, CSS, or plugins.
allowRunningInsecureContent: true.Whether the page is integrated with Node or not, this script can access all Node API scripts. The script path is the absolute path of the file.
preload: path.resolve(path.join(__dirname, './src/preload.js'))}})Copy the code
The script file preload.js is introduced in the entry
const electron = require('electron') / / introduction of the electron
const request = require('superagent'); / / into the superagent
/ / https://developer.mozilla.org/zh-CN/docs/Web/Events#DOM%E5%8F%98%E5%BC%82%E4%BA%8B%E4%BB%B6 DOM mutation events
document.addEventListener('DOMNodeInserted'.(event) = > {
window.cjdz = {
request, // Expose the crawler request and electron.
electron,
version: 1.0}});// If nodeIntegration is set to true, the electron can be exposed without the need to use require('electron') to obtain the electron. However, true means that the electron integrated node is used, which will conflict with some other places; If it's false, you need to expose electron through the window. Find it.
Copy the code
4, develop
A single electron project requires only one main process (main.js). Electron can have multiple renderers using Chromium to display web pages, each page running in its own renderer. Normal project development is ok.
Four, packaging,
1. Electron packager electron packager 2. Electron Builder
A complete solution to package and build a ready for distribution Electron, Proton Native or Muon app for macOS, Windows and Linux with Auto Update support out of the box.
A complete solution that packages and builds a distributed Electron, Proton Native or Muon application for macOS, Windows and Linux, with out-of-the-box “auto update” support.
The electric-Builder has more features than the electric-Packager, supports more platforms, and also supports automatic updates. In addition to these points, the packages typed out of electron Builder are lighter and can be packaged with a Setup installer that does not expose the source code.
The package is: — MAC (MAC), — X64 (Window64), –ia32(Window32), Linux: — Linux;
"build": {
"productName": "my-project"./ / package name
"appId": "org.simulatedgreg.electron-vue".//appID
"directories": {
"output": "build" // Output directory
},
"files": [ // Package the file directory
"dist/electron*"]."dmg": { //Mac configures macOS DMG options
"contents": [{"x": 410."y": 150."type": "link"."path": "/Applications"
},
{
"x": 130."y": 150."type": "file"}},"mac": { // Options related to how the macOS target is built.
"icon": "build/icons/icon.icns" / / Mac icon
},
"win": { // Options related to how the Windows target is built.
"icon": "build/icons/icon.ico" / / Windows icon
},
"linux": { // Options related to how the Linux target is built.
"icon": "build/icons" / / Linux icon}}Copy the code
Packaging scripts
"scripts": {
"start": "electron ."."pack": "electron-builder --dir"."mac": "electron-builder --mac"."win64": "electron-builder --win --x64"."win32": "electron-builder --win --ia32"
},
Copy the code
DMG file yarn/NPM run win64 //. Exe file yarn/NPM run win32 //. Exe file == Win64 and Win32 generate.exe file is the same file source, so it should be marked after packaging and then packaging another system.
Building(build parameters): Command Line Interface (CLI)
parameter | platform | Type/Reference |
---|---|---|
– MAC, -m, – o – macos | Build for macOS | array |
–linux, -l | Build for Linux | array |
–win, -w, –windows | Build for Windows | array |
–x64 | Build for x64 | boolean |
–ia32 | Build for Ia32 (32-bit installation package) | boolean |
–armv7l | Build for armv7l | boolean |
–arm64 | Build for arm64 | boolean |
–dir | Build unpacked dir. Useful to test | boolean |
–prepackaged, –pd | Path to the prepackaged application | Package in a distributable format |
–projectDir, –project | Path to the project directory | The default is the current working directory |
–config, -c | Configuration file path | The default iselectron-builder.yml |
Publish configuration Publish
Icon generation Window and Mac icon generation
Other requirements
1. Click close to confirm
Closed < mainWindow > close < mainWindow > Reference electron’s dialog
const {dialog} = require('electron');
mainWindow.on('close'.(e) = > {
e.preventDefault(); // Block event default behavior
let message = 'After logging out, if you need to log in again, please confirm whether to log out? ';
//let message = copyTaskFlag ? 'After exit, the goods being captured will not continue to be captured, please confirm whether to minimize? ':' After logging out, you need to log in again if you need to use it. Please confirm whether to log out? '
dialog.showMessageBox({ / / reference dialog
type: 'info'.title: 'Quit Pinduoduo Super Store Manager'.defaultId: 0.message: message,
buttons: [Minimize.'Straight out']},(index) = >{
if(index===0) {// Corresponds to the subscript of the buttons array
e.preventDefault();
mainWindow.minimize(); / / minimize
} else {
mainWindow = null;
app.exit(); // Exit the application immediately
//app.quit(); // Exit the application and try to close all Windows}})});Copy the code
Two exits: exit() and quit()
- Exit: Directly exits the application
- Quit: Will not directly exit the application, but close the client and leave it in the taskbar. If you use this on the close event of a mianWindow, it will pop up twice. If you want to do that you need to write flag separately.
2. The main process communicates with the renderer
IpcMain ipcRenderer ipcMain: When used in the main process, it handles asynchronous and synchronous information sent from the renderer process (web page). Messages sent from the renderer process will be sent to this module. IpcRenderer: You can use some of the methods it provides to send synchronous or asynchronous messages from the renderer process (web pages) to the main process. It can also receive messages returned by the main process. Simple example: Q: Click the close button to display a section of text while it is being copied in the rendering process and another section when it is not being copied. Main process:
const {ipcMain} = require('electron');
let copyTaskFlag = false; // Define a variable flag
ipcMain.on('copyTask-message'.(event, arg) = > { // Listen for the event name of the renderer.
copyTaskFlag = arg; //arg is the value passed by the renderer event
});
Copy the code
Render process:
const { ipcRenderer } = require('electron') // in the render process
ipcRenderer.send('copyTask-message', options); //send
Copy the code
3. Right-click the client
A new client right-click is nothing that needs to be customized.
/ / right-click menu: 1 call the electron configuration in the menu at https://electronjs.org/docs/api/menu-item
let electron = require('electron');
const remote = require('electron').remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
var menu = new Menu();
menu.append(new MenuItem({ label: 'copy'.selector: "copy:" ,role: "copy:" }));
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({ label: 'cut'.selector: "cut:".role: "cut:"}));
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({ label: 'paste'.selector: "paste:".role: "paste:"}));
window.addEventListener('contextmenu'.function (e) {
e.preventDefault();
menu.popup(remote.getCurrentWindow());
}, false);
Copy the code
// Right-click menu: 2 Use the document method.
let electron = require('electron');
const remote = electron.remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
let menu = new Menu();
menu.append(new MenuItem({ label: 'copy'.click: function() {
document.execCommand("copy"."false".null);
}}));
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({ label: 'paste'.click: function() {
document.execCommand("paste"."false".null);
}}));
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({ label: The 'refresh'.click: function() {
location.reload();
}}));
window.addEventListener('contextmenu'.function (e) {
e.preventDefault();
menu.popup(remote.getCurrentWindow());
}, false);
Copy the code
4,Remote module
The Remote module provides an easy way to conduct interprocess communication (IPC) between the renderer process (web page) and the host process. In Electron, GUI-related modules (dialog, Menu, etc.) are only available in the main process, not in the renderer process. In order to use them in the renderer process, the IPC module is required to send interprocess messages to the main process. Using the remote module, you can call methods on the main process object.
In the rendering process: 1, use dialog
const electron = require('electron').remote;
const dialog = electron.dialog;
Copy the code
2, BrowserWindow
const { BrowserWindow } = require('electron').remote
let win = new BrowserWindow({ width: 800.height: 600 })
win.loadURL('https://blog.csdn.net/guoqiankunmiss')
Copy the code