Electron core consists of Chromium, Node.js and Native apis. These three parts together form the Electron framework.

Chromium can be understood as a browser, supporting HTML, CSS, JS page composition. Native apis are used to support some interactions with the operating system. Node.js is used to manipulate files and so on.

Electron can be seen as a framework to integrate Chromium and Node.js, it allows you to build applications through Web technology, and do everything with the operating system through Native apis.

Desktop applications are software running in different operating systems. Functions in the software are realized through the communication between Native Api and the operating system. The operating system is basically equivalent to a black box for the front segment. When you want to implement functions, you just need to call the API, and you don’t need to pay attention to the internal implementation.

There are different processes inside Electron, one is the main process and the other is the rendering process. When the app is started, the main process will be started first. After the completion of the main process, the Native UI will be created, and one or more Windows will be created. Each window can be regarded as a rendering process, each process is independent of each other, different window data can communicate through RPC or IPC, communication method is encapsulated, developers can use directly.

App to start the process to have the away to create Windows window, and then win the window to load the interface is the rendering process, if the page is interactive, the render process needs to be received by IPC communication instruction information to the main process, main process after receiving information through a call to the operating system to realize the function, complete again after notice to the rendering process.

The main process can be thought of as the file corresponding to the main property in package.json. An application can only have one main process, as long as the main process can perform GUI API operations. The main process manages all the Web interfaces and renderers.

The renderer process is the interface process displayed in Windows. An application can have multiple renderers. The renderer process cannot access the native API directly but can access it through the main process.

Environment set up

www.electronjs.org

Sample project warehouse $# cloning git clone https://github.com/electron/electron-quick-start # $CD electron - quick to enter the warehouse - start # installation and operation of $ npm install && npm startCopy the code

Main.js is the main process.

const { app, BrowserWindow } = require('electron')
const path = require('path')

// The create window and load page interface is run in the render process
function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 800.height: 600.webPreferences: {
            preload: path.join(__dirname, 'preload.js')}})// Load the page
    mainWindow.loadFile('index.html')

    mainWindow.on('close'.() = > {
        console.log('Current window closed')})}// Lifecycle
app.whenReady().then(() = > {
    // Load interface
    createWindow();

    app.on('activate'.() = > {
        console.log('When activated')
    })
})

app.on('window-all-closed'.() = > {
    console.log('All Windows are closed');
    // Close the application
    app.quit(); 
})
Copy the code

The life cycle

  • Ready: The app is initialized
app.on('ready'.() = > {
    const mainWin = new BrowserWindow({
        width: 800.height: 400})})Copy the code
  • Dom-ready: A text file in a window is loaded

WebContents is used to control the contents of the current window, and each window has one webContents.

mainWin.webContents.on('dom-ready'.() = >{})Copy the code
  • Did-finsh-load: triggered when navigation is complete, after DOM-ready
mainWin.webContents.on('did-finsh-load'.() = >{})Copy the code
  • Window-all-closed: this parameter is triggered when all Windows are closed. If no listener is heard, the system exits directly
app.on('window-all-closed'.() = >{})Copy the code
  • Before-quit: Triggers before closing the window
app.on(' before-quit'.() = >{})Copy the code
  • Will-quit: Triggered when the window closes and the application exits
app.on('will-quit'.() = >{})Copy the code
  • Quit: Triggered when all Windows are closed
app.on('quit'.() = >{})Copy the code
  • Close: The window is closed
mainWin.on('close'.() = > {
    mainWin = null;
})
Copy the code

Automatic packaging Settings

"scripts": {
    "start": "nodemon --watch main.js --exec npm run build"."build": "electron ."
}
Copy the code

The window size

const mainWin = new BrowserWindow({
    ...
})

mainWin.loadFile('index.html')
// Page loading completes asynchronous display to avoid page blank
mainWin.on('ready-to-show'.() = > {
    mainWin.show();
})

// x: number Window position
// y: number Specifies the window position
// width: number Window width
// height: number Window height
// shwo: Boolean Displays forms by default
// maxHeight: number Maximum height
// minHeight: number Minimum height
// maxWidth: number Maximum width
// minWidth: number Minimum width
// Resizable: Boolean Zoom setting
// title: string window title. If the HTML has a title tag, the content of the title tag is taken
// icon: string window icon
// frame: Boolean Whether to display TAB page menu bar title bar
Transparent: Boolean Specifies whether the form is transparent
// autoHideMenuBar: Boolean Hide menu
// webPreferences: {
// nodeIntegration: true, // allows the Node environment to run
// enableRemoteModule: true // Enables the remote module
// } 

Copy the code

Window communication

CTRL + R: Reload the page

CTRL + Shift + I: Opens the debugging panel

The default rendering process will not be able to use the require running node, can open webPreferences. NodeIntegration support this function. Remote is used to find BrowserWindow in the main thread. BrowserWindow is only for the main thread and is not allowed to be called in the render thread. At the same time also need to open webPreferences enableRemoteModule function.

const { remote } = require('electron');

const mainWin = new remote.BrowserWindow({
    ...
})

mainWin.loadFile(' ')
Copy the code

Remote module is the main thread and child thread communication module.

Remote To get the current window object

const mainWin = remote.getCurrentWindow;
/ / close
mainWin.close();
// Maximize the state
mainWin.isMaximized()
/ / maximize
mainWin.maximize();
// return to the initial state
mainWin.restore();
// Minimize state
mainWin.isMinimized()
/ / minimize
mainWin.minmize();
Copy the code

Window closing prompt

window.onbeforeunload = function() {
    // Destroying close creates an infinite loop
    mainWin.destroy();
    // Disable closing
    return false;
}
Copy the code

The Windows created by remote.BrowserWindow do not have parent-child relationships by default, so use the parent parameter if necessary. So you have a father-son relationship. However, there is no difference between the use of father-son relationship.

remote.BrowserWindow({
    parent: remote.getCurrentWindow(),
    width: 200.height: 200
})
Copy the code

If you want the child window to appear and the parent window is not operable you can use a modal window, and you should set the Modal property to true.

remote.BrowserWindow({
    parent: remote.getCurrentWindow(),
    width: 200.height: 200.modal: true
})
Copy the code

Document center

Interprocess communication

  • The renderer sends a message to the main process, which receives the message.

The renderer sends the message

const { ipcRenderer } = require('electron');

window.onload = function() {
    // Use an asynchronous message to send messages to the main thread
    ipcRenderer.send('msg1'.'Parameter string')
    // Send messages synchronously
    ipcRenderer.sendSync('msg3'.'Sync message')}Copy the code

The main process receives the message

const { ipcMain } = require('electron');
ipcMain.on('msg1'.(e, data) = > {
    console.log(e, data);
})

ipcMain.on('msg3'.(e, data) = > {
    console.log(e, data);
})
Copy the code
  • The main process sends a message to the renderer

The main process sends messages

const { ipcMain } = require('electron');
ipcMain.on('msg1'.(e, data) = > {
    console.log(e, data);
    // e.spender is ipcMain
    e.sender.send('msg2'.'Parameter string')
    The main thread returns a synchronization message
    e.returnValue = 'Send sync message'
})
Copy the code

The renderer receives the message

const { ipcRenderer } = require('electron');

window.onload = function() {
    // Use an asynchronous message to send messages to the main thread
    ipcRenderer.send('msg1'.'Parameter string')
}

ipcRenderer.on('msg2'.(ev, data) = > {
    console.log(e, data);
})
Copy the code

OpenDevTools () opens developer tools

mainWin.webContents.openDevTools()
Copy the code

dialog

The Dialog module is the electron built-in module that can be used to manipulate and select files in the system, etc.

shell

Shell modules provide functionality related to desktop integration. For example, use the default browser to open an address. Can be used in all threads.

const { shell } = require('electron')

shell.openExternal('https://github.com')
Copy the code

iframe

Electron is not recommended to use webView. Use iframe instead, or preferably not.

alerts

This can be done with H5’s message notification feature.

const notify = new window.Notification('title', {
    title: 'title'.body: 'content'.icon: './icon.png'
})

notify.onclick = function() {
    console.log('Click on message')}Copy the code

Register shortcut key

The shortcut points are for the main process, and the shortcut keys need to be bound after initialization. Remove prior to destruction.

const { globakShortcut } = require('electron')
app.on('ready'.() = > {
    const ret = globakShortcut('ctrl + q'.() = > {
        console.log('Triggered a shortcut key')})if(! ret) {console.log('Registration failed')}// Whether to register
    console.log(globakShortcut.isRegistered('ctrl + q'))})Copy the code

Hotkey cancellation needs to be done in the Will-quite life cycle.

app.on('will-quit'.() = > {
    // Clear a single
    globakShortcut.unregister('ctrl + q')
    // Clear all registrations
    globakShortcut.unregisterAll()
})
Copy the code

Shear board function

The clipboard is also a thread-free module that can be used in any thread.

const { clipboard } = require('electron')
clipboard.writeText('Write clipboard');
// Read the clipboard
clipboard.readText;
Copy the code

Copy the image to the clipboard

const { clipboard, nativeImage } = require('electron')
const image = nativeImage.createFromPath('./aaa.png')
clipboard.writeImage(image);

// Render to page
img.src = image.toDataURL()
Copy the code