We have already released the first Electron series, which implements a simple Hello World. If you are interested, you can check it out: juejin.cn/post/698026… Today’s second installment continues to talk about the other uses of Electron.

The operation flow of Electron

Let’s start with a simple process

Graph LR package. json --> Main process file --> Read page layout and presentation -->IPC performs tasks and gets information

Electron’s main process and render process

The main process

  • The entry file in package.json, the process of the main script, 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

  • Create renderer in main.js main process
  • Create and manage application Windows using the BrowserWindow module. When an instance of BrowserWindow is destroyed, the rendering process is terminated
  • Electron uses Chromium to display web pages, so Chromium’s multi-process architecture is also used, with each web page in Electron running in its own rendering process
  • The main process controls the renderer process. A main process can control multiple renderers

With that in mind, let’s do a simple case study

A simple example

Let’s do an example of choosing a meal. Create a menu. TXT file in the root directory, and write the corresponding menu name. With this file, we will modify the main.js file. Since we are going to use the FS module in Node, we will increase the use of Node.js in the setup window.

var electron = require('electron') 

var app = electron.app   

var BrowserWindow = electron.BrowserWindow;

var mainWindow = null ;
app.on('ready'.() = >{
    mainWindow = new BrowserWindow({
        width:500.height:500.webPreferences: {nodeIntegration:true}
    })

    mainWindow.loadFile('index.html')

    mainWindow.on('closed'.() = >{
        mainWindow = null})})Copy the code


<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Idivnitial =1.0"> <title>Document</title> </head> <body> <Button ID =" BTN "></ Button><br/> <div id="menu"></div> </body> </html>Copy the code

We can then create a separate renderer folder named for operations in the render process. After the folder is created, create a new index.js file in the file, and then import it in the index.html page. Normal js import form. Finally, show the complete code:


var fs = require('fs'); 
window.onload = function(){
    var btn = this.document.querySelector('#btn')
    var mybaby = this.document.querySelector('#menu')
    btn.onclick = function(){
        fs.readFile('xiaojiejie.txt'.(err,data) = >{
            mybaby.innerHTML = data
        })
    }
} 
Copy the code

Finally, run the electron.? Command to jump out of the screen and see the directory.

Electron Remote module

Electron has a main process and a renderer process, and the Electron API methods and modules can be used in the main process and renderer process, respectively. Then we can use Electron Remote to communicate between the render and the main process. In the project root directory, create a new WindowDemo.html file, then quickly generate the basic structure of THE HTML, write a button to introduce the rendered JS page. The code is as follows:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <title>Document</title> </head> <body> <Button id=" BTN "> Open a new window </Button><br/> <script src="renderer/windowDemo.js"></script> </body> </html>Copy the code

In the Render folder, create a new WindowDemo.js file and write the following code:

 const btn = this.document.querySelector('#btn')
 const BrowserWindow =require('electron').remote.BrowserWindow

window.onload = function(){
    btn.onclick = ()=>{

         newWin = new BrowserWindow({
             width:500,
             height:500,
         })
         newWin.loadFile('menuList.html')
         newWin.on('close',()=>{win=null})

     }
}
Copy the code

Create a new menulist.html page:



 const btn = this.document.querySelector('#btn')
 const BrowserWindow =require('electron').remote.BrowserWindow

window.onload = function(){
    btn.onclick = () = >{

         newWin = new BrowserWindow({
             width:500.height:500,
         })
         newWin.loadFile('menuLIst.html')
         newWin.on('close'.() = >{win=null}}})Copy the code

Then we run electron in the terminal. If everything is normal, a new window can be opened smoothly. The success of this window is mainly due to the electron Remote. It gives us a lot of native power on the PC side, which is the simple Electron Remote to do more complex things on your own.

Electron create menu

We’ve created several dishes before, but that’s just for demonstration, so this time we’ll implement Electron and use Menu to create the Menu

  • Writing menu templates

Create a new menulist.js file:

const { Menu } = require('electron')

var template = [
    {
        label:'The Land of the South'.submenu:[
            {label:'West Lake Fish in vinegar'},
            {label:'Shrimp with Longjing'}]}, {label:'Sichuan Restaurant'.submenu:[
            {label:'Stir-fried pork'},
            {label:'Twice-cooked pork'}}]]var m = Menu.buildFromTemplate(template)

Menu.setApplicationMenu(m)
Copy the code

Then open the main process main.js file and add the following code directly to the ready lifecycle to implement the custom menu

 require('./main/menuList.js')
Copy the code
  • Use the menu to open a new window

Add the click event to the menu as follows:

const { Menu ,BrowserWindow} = require('electron')


var template = [
    {
        label:'The Land of the South'.submenu:[
            {
                label:'West Lake Fish in vinegar'.// Main code --------------start
                click:() = >{
                    win = new BrowserWindow({
                        width:500.height:500.webPreferences: {nodeIntegration:true}
                    })
                    win.loadFile('menuList.html')
                    win.on('closed'.() = >{
                        win = null})}// Main code ----------------end
            },
            {label:'Shrimp with Longjing'}]}, {label:'Sichuan Restaurant'.submenu:[
            {label:'Stir-fried pork'},
            {label:'Twice-cooked pork'}}]]var m = Menu.buildFromTemplate(template)

Menu.setApplicationMenu(m)
Copy the code

Finally, open the terminal and type electron. Then you can see the effect

Electron makes right-click menu

Above we learned how to set the top menu, we also made a small menu example, this time we continue to learn how to implement the right-click function.

  • Menu shortcut key binding

The binding shortcut property is accelerator property, for example, we open a new window.

accelerator:`ctrl+n`
Copy the code

All the code is still the code above, I won’t paste. After writing the code, type electron into the terminal to run the program and press CTRL + N to create a new page. This implements the new page method.

  • Create right-click menu

The response events for the right-click menu are written in the renderer process, i.e. in index.html, so if used, the remote module will be used.

We open render folder, and then open WindowDemo. js file, write a right-click menu listening event, the code is as follows:

window.addEventListener('contextmenu'.function(){
    alert(123);
})
Copy the code

Using the remote


const { remote} = require('electron')

var rigthTemplate = [
    {label:'paste'},
    {label:'copy'}]var m = remote.Menu.buildFromTemplate(rigthTemplate)



window.addEventListener('contextmenu'.function(e){

    // Block the current window default event
    e.preventDefault();
    // Add the menu template to the right-click menu
    m.popup({window:remote.getCurrentWindow()})

})
Copy the code

Finally we can enter electron in the terminal. Open the program to test the right menu function.

  • The program opens debug mode

We can continue to add a debug mode menu:

mainWindow.webContents.openDevTools()
Copy the code

The full code is as follows:

var electron = require('electron') 

var app = electron.app   

var BrowserWindow = electron.BrowserWindow;

var mainWindow = null ;
app.on('ready'.() = >{
    mainWindow = new BrowserWindow({
        width:500.height:500.webPreferences: {nodeIntegration:true}
    })
    mainWindow.webContents.openDevTools()

    require('./main/menuList.js')

    mainWindow.loadFile('windowDemo.html')

    mainWindow.on('closed'.() = >{
        mainWindow = null})})Copy the code

In this way, the window can be opened and the debugging mode can be directly entered, which greatly improves the debugging efficiency.

Electron opens the browser with a link

We know that by default, we add a tag in the render process to jump to. By default, we open it directly in the window, not in the browser. If we want to open it in the default browser, what do we need to do? That’s the electron shell

  • Default open example

Let’s take a look at what happens when you open a link in electron by default. In the project root directory, create a new demo. HTML file and write a tag as follows:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < title > Document < / title > < / head > < body > < h1 > < a href =" https://www.baidu.com "> < / a > < / h1 > < / body > </html>Copy the code
  • Open it in a browser using a Shell

Add the ID to the tag

<a id="hrefs" href="https://www.baidu.com"></a>
Copy the code

In the Render folder, create a new demo1.js file, introduce a shell on the first page of the file, and write the response event click.

var { shell } = require('electron')

var hrefs = document.querySelector('#hrefs') 

aHref.onclick = function(e){
    e.preventDefault()
    var href = this.getAttribute('href')
    shell.openExternal(href)
}
Copy the code

Introduce the demo1.js file in HTML

<script src="./renderer/demo1.js"></script>
Copy the code

This allows you to open the link in the browser.

Conclusion: This is the second article in the Electron series. Due to a lot of things, I haven't learned and transmitted the article on time, but I will learn and summarize it slowly as long as I have time. Our learning journey is not over yet. The dialog box operation, network outage reminder, message notification and clipboard in Electron will appear successively in later articles.