Electron uses web pages as the app’s GUI, so you can think of it as a small chrome kernel browser controlled by JavaScript.
Main process vs rendering process
Main process
In electron, runpackage.json
The process of the main script in is called the main process. Scripts running in the main process can play a GUI role by creating a window on a web page.
The main process looks like a script:
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
var window = null;
app.on('ready', function() {
window = new BrowserWindow({width: 800, height: 600});
window.loadURL('https://github.com');
});
Rendering Progress
Because electron uses the chrome kernel, the multiprocess structure can also be used by us. Each page in electron has its own process called rendering process.
In the ordinary browser, the web page runs in a sandbox environment, can’t contact the native source code. Electron allows you to use it on the page Node.js API, a lower degree of interaction with the operating system.
Rendering process is like traditional HTML, but it can directly use Node module: simultaneous interpreting.
<!DOCTYPE html>
<html>
<body>
<script>
const remote = require('electron').remote;
console.log(remote.app.getVersion());
</script>
</body>
</html>
The difference between the main process and the rendering process
The main process is instantiatedBrowserWindow
, eachBrowserWindow
Each instance returns a web page in its own rendering process. WhenBrowserWindow
When the instance is destroyed, the corresponding rendering process is also terminated.
The main process is responsible for all web pages and their corresponding rendering processes. Each rendering process is independent of each other, and they only care about the web page they are running.
It is not allowed to call the API related to native GUI in the page (rendering process), because it is dangerous to take charge of the native GUI in the web page (rendering process), which is easy to cause memory leakage. If you want to perform GUI operations in a web page, the rendering process must communicate the request to the main process, and then complete the operation in the main process.
In electron, we have several ways to connect the main process to the rendering process, such as theipcRenderer
andipcMain
Module, and for RPCremote
modular.
Sharing data between different pages
It’s very simple, and it can be done using the HTML5 API.
Storage API
,IndexedDB
It’s a good choice.
You can also use theIPC
System. It stores an object as a global variable in the main process, and then can use theremote
Modules operate them:
//In the main process
global.sharedObject = {
someProperty: 'default value'
};
// In page 1.
require('remote').getGlobal('sharedObject').someProperty = 'new value';
// In page 2.
console.log(require('remote').getGlobal('sharedObject').someProperty);