electron learning notes

#1. Introduction

  • Official website
  • Electron is an open source project developed by many GitHub developers. It can build cross platform desktop applications using JavaScript, HTML and CSS

2. Get started quickly in five minutes

2.1 installing the electron

Initialize package JSON file

  • npm init

Installing the electron

  • cnpm I electron –S

2.2 configure as portal file

{
  "name": "electron-demo",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron ."
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "electron": "^8.3.0"
  }
}

Create index html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>

2.3 create main JS file

// main.js

// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('path')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,//Using node module and api
      contextIsolation: false,
      enableRemoteModule: true   // Using the remote module
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools. Open debug
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some API s can only be used after the ready event is triggered.
app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code.  You can also split it into several files and import it with require.

2.4 create window

In Electron, the browser window can be created only after the ready event of the app module is fired. You can use app whenReady() API to listen for this event. After whenReady (), createWindow() is called. app.whenReady() and app On ('ready ', () = > {}) is the same

app.on('ready', ()=>{
  const mainWindow = new 
  ({
    width: 800,
    height: 500
  })

  mainWindow.loadFile('index.html')
   app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

3. Automatically refresh the page

  • Install plug-ins

    cnpm install --save-dev electron-reloader
    
  • Introducing plug-ins at the portal

    const reloader = require('electron-reloader')
    reloader(module)
    

4. Main process and rendering process

Electron runs package The process of JSON's main script is called the main process. Scripts running in the main process present the user interface by creating web pages. An electron application always has and has only one main process.

Because Electron uses Chromium to display web pages, Chromium's multi process architecture is also used. The web page in each Electron runs in its process called rendering process.

In ordinary browsers, web pages cannot access the native resources of the operating system. However, Electron's users are at node JS API supports some low-level interaction with the operating system on the page.

ctrl+shift+i open rendering process debugging

Debugging is on by default

app.on('ready', ()=>{
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 500
  })

  mainWindow.loadFile('./index.html')

  const mainWindow2 = new BrowserWindow({
    width: 800,
    height: 500
  })
  
  mainWindow.webContents.openDevTools()

  mainWindow2.loadFile('./index2.html')
})

5. Customize native menu

5.1 custom menu

Detailed documentation: https://www.electronjs.org/docs/api/menu

const electron = require('electron')

const { app, Menu } = electron
const template = [
  {
    label: 'file',
    submenu: [
      {
        label: 'New window'
      }
    ]
  },
  {
    label: 'edit',
    submenu: [
      {
        label: 'New window'
      }
    ]
  }
]
const menu = Menu.buildFromTemplate(template)

Menu.setApplicationMenu(menu)

5.2 define click events for the menu

1. Click to open a new window

submenu: [
  {
    label: 'New window',
    click: ()=>{
      const newMainWindow = new BrowserWindow({
        width: 300,
        height: 300
      })
      newMainWindow.loadFile('./new.html')
    }
  }
]

2. Click to open the browser

The shell module provides the function of integrating other desktop clients

const { BrowserWindow, Menu, shell } = require('electron')
const template = [
  {
    label: 'file',
    submenu: [
      {
        label: 'File 1',
        click () {
          // Click to open a new window
          const mainWindow2 = new BrowserWindow({
            width: 600,
            height: 600
          })
        
          mainWindow2.loadFile('./index.html')
        }
      }
    ]
  },
  {
    label: 'csdn',
    click () {
      // Click to open the browser
      shell.openExternal('https://www.csdn.net/')
    }
  }
]

5.3 pull out menu definition

const { BrowserWindow, Menu} = require('electron')
const template = [
  {
    label: 'file',
    submenu: [
      {
        label: 'New window',
        click: ()=>{
          const newMainWindow = new BrowserWindow({
            width: 300,
            height: 300
          })
          newMainWindow.loadFile('./new.html')
        }
      }
    ]
  },
  {
    label: 'edit',
    submenu: [
      {
        label: 'New window'
      }
    ]
  }
]
const menu = Menu.buildFromTemplate(template)

Menu.setApplicationMenu(menu)
require('./menu')

Open mode

mainWindow.webContents.openDevTools()

5.4 customize top menu

  • Create a borderless window through frame

    const mainWindow = new electron.BrowserWindow({
        frame: false
    })
    
  • Custom window

    <div class="custom-menu">
      <ul>
          <li>New window</li>
          <li>About us</li>
        </ul>
      </div>
    
    * {
      margin: 0;
      padding: 0;
    }
    .custom-menu {
      height: 50px;
      width: 100%;
      background: pink;
    }
    
    .custom-menu ul {
      list-style: none;
    }
    
    .custom-menu ul li {
      float: left;
      width: 50px;
      line-height: 50px;
      text-align: center;
      margin-left: 10px;
    }
    

    Add WebKit app region: drag; Implement drag and drop

5.5 click create new window

// html
<li class="new-window">New window</li>

// js
// Remote uses the method of the main process through remote
const { remote: {BrowserWindow} } = require('electron')
const newWindow = document.querySelector('.new-window')
newWindow.onclick = function () {
  new BrowserWindow({
    width: 200,
    height: 300
  })
}

The node method can be used in html

const mainWindow = new BrowserWindow({
  width: 800,
  height: 500,
  webPreferences: {
    // Open node module
    nodeIntegration: true,
    // Open remote module
    enableRemoteModule: true
  }
})

5.6 click the page to open the browser

  • html

    <a id="a1" href="https://www.itheima. Com "> open browser</a>
    
  • js

    const { shell } = require('electron')
    const allA = document.querySelectorAll('a')
    
    allA.forEach(item => {
      item.onclick = function (e) {
        e.preventDefault()
        console.log(item)
        shell.openExternal(item.href)
      }
    })
    

6. Open the dialog box to read the file

6.1 reading files

  • Define click events

    <button onclick="openFile()">open</button>
    
  • Define event functions

    Open dialog document: https://www.electronjs.org/docs/api/dialog

    // open a dialog box
    function openFile() {
      const res = dialog.showOpenDialogSync({
        title: 'Select file',
        buttonLabel: 'ha-ha',
        filters: [
          { name: 'Custom File Type', extensions: ['js'] },
      ]
      })
    
      const fileContent = fs.readFileSync(res[0])
      dropEl.innerText = fileContent
    }
    

6.2 saving documents

  • Define click events

    <button onclick="saveFile()">preservation</button>
    
  • Event function

    // Save Dialog 
    function saveFile() {
      const res = remote.dialog.showSaveDialogSync({
        title: 'Save file',
        buttonLabel: 'Save file',
        filters: [
          { name: 'index', extensions: ['js'] },
        ]
      })
      fs.writeFileSync(res, dropEl.value)
    }
    

7. Define shortcut keys

7.1 definition of main thread

  • introduce

    const { app, BrowserWindow, globalShortcut } = require('electron')
    
  • Register shortcut keys in ready

    const ret = globalShortcut.register('CommandOrControl+X', () => {
      console.log('CommandOrControl+X is pressed + The print results are displayed on the command line')
    })
    
  • Define shortcut keys max, min, close window

    globalShortcut.register('CommandOrControl+T',()=>{
        mainWindow.unmaximize();
      })
      globalShortcut.register('CommandOrControl+H',()=>{
        mainWindow.close()
      })
      globalShortcut.register('CommandOrControl+M',()=>{
        mainWindow.maximize()
      })
    

7.2 definition of rendering process

  • Register via remote

    // define custom keyboard shortcut
    remote.globalShortcut.register('Ctrl+O', () => {
      console.log('ctrl+o')
    })
    

8. The rendering process communicates with the main thread

  • Define button

    <div class="maxWindow no-drag" onclick="maxWindow()"></div>
    
  • Event function

    function maxWindow() {
      ipcRenderer.send('max-window')
    }
    
  • Main thread definition event

    ipcMain.on('max-window', () => {
        mainWindow.maximize()
      })
    
  • Transmission parameter

    let windowSize = 'unmax-window'
    function maxWindow() {
      windowSize = windowSize === 'max-window' ?'unmax-window':'max-window'
      ipcRenderer.send('max-window',windowSize)
    }
    
  • Receive parameters

    ipcMain.on('max-window', (event,arg) => {
        console.log(arg)
        if(arg === 'unmax-window') return mainWindow.maximize();
        mainWindow.unmaximize()
      })
    

09. Electronic packaging

  • Installing the electron packer

    cnpm i electron-packager -D
    
  • Add package task

    "build": "electron-packager ./ HelloWorld --platform=win32 --arch=x64 --out ./outApp --overwrite --icon=./favicon.ico"
    

10 . Development of electronic integration framework

  • Initialize project with vue scaffold

  • Installing electron in a project

    cnpm i electron

  • Adding an electron startup configuration

    "main": "main.js",
    "scripts": {
       "start": "react-scripts start",
       "build": "react-scripts build",
       "test": "react-scripts test",
       "eject": "react-scripts eject",
       "electron": "electron ."
      },
    
  • Configure main js

    const {app, BrowserWindow} = require('electron')
    
    function createWindow () {
      // Create the browser window.
      const mainWindow = new BrowserWindow({
        width: 800,
        height: 600
      })
      // Open the DevTools.
      // mainWindow.webContents.openDevTools()
    }
    
    app.on('ready', () => {
      createWindow()
    })
    
  • Load vue project

    mainWindow.loadURL('http://localhost:3000/')
    

Added by cleibesouza on Tue, 18 Jan 2022 12:16:46 +0200