Electron

Description: Allows desktop applications to be developed using web technologies

  • Electron = Chromium(Google kernel, rendering compatibility strong)+ Node.js (can use many packages to add features)+Native API(cross-platform Native ability)

Run flow: need 3 files, index. HTML, main.js, package.json

  • First go to package.json and look for the main method, which records the main process, the entry file, with one and only one
{

  "name""electronDemo1".

  "version""1.0.0".

  "description""".

    // The main process is main.js

  "main""main.js".

  "scripts": {

    "test""echo \"Error: no test specified\" && exit 1"

  },

  "keywords": [].

  "author""".

  "license""ISC"

}

Copy the code
  • After entering main.js, mainWindow.loadFile sets up the render file and creates the render process, one for each window
/ / main process

var electron = require('electron')

var app = electron.app // Reference app below electron

var BrowserWindow = electron.BrowserWindow // Control window references

var mainWindow = null// Declare the main window to open

// To create an application,ready is the identifier when the application starts

app.on('ready', () = > {

    // Set the window size

    mainWindow = new BrowserWindow({ width300.height300 })

        // Set the file to load for page rendering

    mainWindow.loadFile('index.html')

        // Free memory when the page is closed

    mainWindow.on('closed', () = > {

        mainWindow = null

    })

})

Copy the code
  • Go to index.html: Read the layout and style of the page
<! DOCTYPEhtml>

<html lang="en">



<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">

    <title>Hello Electron</title>

</head>



<body>

    Hello Electron

</body>



</html>

Copy the code
  • Use IPC to perform tasks and get information in the main process: We will use the Remote module, which provides a simple way to conduct process communication (IPC) between the renderer process (web page) and the host process

  • {nodeIntegration: true, enableRemoteModule: true} webPreferences: {nodeIntegration: true, enableRemoteModule: true}

    The first is to allow all modules in node to use remote. The second is to allow remote to use

// First we introduce a js file in the index page, which is used to call the main process

<script src="render/demo2.js></script>

// Then we look at demo2.js

// Select the BTN button in the HTML file here

const btn = this.document.querySelector('#btn')

// Use remote to call BrowserWindow indirectly

const BrowserWindow = require('electron').remote.BrowserWindow;

// Add a new popbox here to implement the method in the main process of the renderer operation

window.onload = function() {

    btn.onclick = () => {

Console. log(' Button clicked ')

        newWin = new BrowserWindow({

            width: 500,

            height: 500

        })

        newWin.loadFile('yellow.html')

Console. log(' Rendering finished ')

        newWin.on('close', () => {

            newWin = null

        })

    }

}

Copy the code

Menu creation and its binding events

Let’s first look at creating the menu: we now import the js file that we created the menu in the main process, and then create the import Menu and browserWindow in the file, and then write the template for the menu, register the click event, then build the template, and set the template

// Import the menu file

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

// Introduce the method in electron

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

// Menu template, label is menu title, submenu is menu option

var template = [{

    // The label in the first layer is the largest menu, which is displayed directly at the top of the window.

            label'Dinner time'.

    // The menu bar allows a label, that is, each label can have a submenu, but the submenu can not add click events

            submenu: [{

                    label'Play the game.'.

                    submenu: [{

                        label'CSGO'

                    }, {

                        label'LOL'.

}].

                    click(a)= > {

                        var win = new BrowserWindow({

                            width500.

                            height500.

                            webPreferences: {

                                nodeIntegrationtrue

                            }

                        })

                        win.loadFile('yellow.html')

                        win.on('close', () = > {

                            win = null

                        })

                    }

                },

                { label"Listen up." }

            ]

        },

        {

            label'Go to sleep.'.

            submenu: [

                { label'dream' },

                { label'Have two dreams' }

            ]

        }

    ]

    // Build the template

var m = Menu.buildFromTemplate(template)

Menu.setApplicationMenu(m)

Copy the code

Menu.buildfromtemplate (template), build the template, and then set menu.setApplicationMenu (m)

Right-click menu making and shortcut keys

  • Accelerator: ‘CTRL + W ‘, add a line of this directly under the label, can be set as a shortcut to perform click action

  • Right-click menu: first create template, and then register the last class, and put in the click event, popup control template popup

/ / into the remote

const { remote } = require('electron')

// Menu template

var rightTemplate = [

    { label'copy'.accelerator'ctrl+c' },

    { label'paste'.accelerator'ctrl+v' }

]

// Build the menu template

var m = remote.Menu.buildFromTemplate(rightTemplate)

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

    // Browsers do not perform default actions associated with events

    e.preventDefault()

    / / window

    m.popup({ window: remote.getCurrentWindow() })

    })

Copy the code

Open the browser through the link

  • First jump directly with the A TAB, which will open the url directly in electron. If you want to open it in the browser,
var { shell } = require('electron')

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

aHref.onclick = function(e{

    e.preventDefault();

    var href = this.getAttribute('href')

    shell.openExternal(href)

}

Copy the code

Summary: First introduce the shell properties, then get the element and bind the click event, then turn off the default behavior, then bind the browser open event

Embed a web page in your application

1607258955428
       / / introduction

    var BrowserView = electron.BrowserView

        / / create

    var view = new BrowserView()

        / / a mount

    mainWindow.setBrowserView(view)

        // Set the seat

    view.setBounds({ x0.y120.width1000.height500 })

        // Load the page

    view.webContents.loadURL('https:baidu.com')

Copy the code

Summary: In the main process introduce, set, then mount, rendering as above

Open the child window: window.open

Child window communicates to parent window

 window.opener.postMessage('I am the message passed by the child window', targetOrange), pass all if there is no second parameter



 window.addEventListener('message',(msg)=>{

 let msg = JSON.stringify(msg.data);

  })

Copy the code