当前位置:网站首页>Electronic basic project construction & communication between main thread and rendering thread
Electronic basic project construction & communication between main thread and rendering thread
2022-06-25 18:43:00 【Thunderbolt peach】
electron
One 、 Initialize a electron project
1. So let's create one package.json file
npm init -y
2. Download and install electron
- Note to switch Taobao image download
npm instsll electron -S
3. stay package.json Configure execution script under
- Install first
nodemon
"scripts": {
"start": "nodemon --exec electron . --watch ./ --ext .html,.js,.css"
},
4. Create in the root directory main.js file
const {
app, BrowserWindow } = require("electron");
// The main process
const createWindow = () => {
const win = new BrowserWindow({
// Window size
width: 1400,
height: 800,
// Minimum window size
minHeight: 300,
minWidth: 400,
// Whether the window displays
show: true,
// Can I drag
movable: true,
// Is there a top status bar , Drag bar
// frame: false,
// Causes hidden title bars and full-size content windows
// titleBarStyle: "default",
// Window initial background color
backgroundColor: "aliceblue",
});
// Open the debugging tool
win.webContents.openDevTools();
// Reprint the page to the window
win.loadFile("./render/index.html");
win.once("ready-to-show", () => {
win.show();
});
};
app.on("window-all-closed", () => {
console.log("window-all-closed");
// about MACOS System , When you close a window , Will not directly launch the application
if (process.platform !== "darwin") {
app.quit();
}
});
app.whenReady().then(() => {
createWindow();
// stay MacOS Next , When all windows are closed , Click on dock Icon , The window opens again .
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// console.log(app.isReady())
// console.log(app.getPath('desktop'))
// console.log(app.getPath('music'))
// console.log(app.getPath('temp'))
// console.log(app.getPath('userData'))
// console.log(BrowserWindow.getAllWindows().length)
});
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";
5. Create a folder at the root render Create an entry file inside index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- <meta http-equiv="Content-Security-Policy" content="script-src 'self' unsafe-eval"> -->
<title>Document</title>
</head>
<body>
<h1> first electron project </h1>
</body>
</html>
Two 、 The main process communicates with the rendering process
- Directory structure
-- root directory
--controller The encapsulated main thread sends and receives data
--ipcMessage.js
--preload contextBridge Method , A bridge between the main thread and the rendering thread
--index.js
--render Loaded page entry
--app.js
--index.html
--style.css
--vue.global.js vue Project package of , This sample page uses vue3
--main.js Project entrance
1. Communication needs to be preceded by contextBridge As a bridge between the main thread and the rendering scene
- Use
contextBridgeMethod , Send the information of the main thread to the rendering thread
// example , take electron and node The version number is sent to the rendering thread
const {
contextBridge } = require("electron");
// send out , Of this information key by myAPI
contextBridge.exposeInMainWorld("myAPI", {
versions: process.versions,
});
// Get the method in the page
const versions = window.myAPI.versions;
// Get version number
// chromeVersion: versions.chrome,
// NodeVersion: versions.node,
// electronVersion: versions.electron
2. The rendering process sends synchronization information to the main process
- The rendering process uses
ipcRenderer.send(' Event name ',' Information ')Send a message , This operation is incontextBridgein - Main thread usage
ipcMainreceive , Usage methodevent.sender.sendReturn content
// --------------contextBridge------------------
// Create method sendSync Send a message
const sendSync = (message) => {
ipcRenderer.send("sync-send-event", message);
};
// The method is thrown to Rendering thread calls
contextBridge.exposeInMainWorld("myAPI", {
sendSync,
});
// ----------------- Rendering thread --------------------------
// Rendering thread calls
myAPI.sendSync("from renderer message 1");
// ----------------------- The main thread --------------------
// The main thread accepts data
// Synchronous event listening
ipcMain.on("sync-send-event", (event, msg) => {
// console.log(msg);
// Using parameter event Methods Return message
event.sender.send("sync-receive-event", " I have received :" + msg);
});
contextBridgereceive messages , And throw the method to the rendering thread , The rendering thread creates event listeners
// -----------------contextBridge-------------------
// Use ipcRenderer.on Create a time synchronization listener
const recieveSyncMsg = () => {
return new Promise((resolve) => {
ipcRenderer.on("sync-receive-event", (event, msg) => {
// console.log(msg)
resolve(msg);
});
});
};
// Put the event recieveSyncMsg Send to the rendering thread
contextBridge.exposeInMainWorld("myAPI", {
recieveSyncMsg,
});
// -------------------- Rendering thread -------------------
// Use async await Create a synchronous event listener
async mounted(){
const result = await myAPI.recieveSyncMsg();
}
The above is a complete set of rendering thread sending data -> The main thread accepts the data and returns -> The rendering thread receives the return data The process of
3. The rendering process sends an asynchronous message to the main process
- The rendering thread sends data using
ipcRenderer.invokeMethod , The method of sending data iscontextBridgeUse in , Also throw the method to the rendering thread js A file called - The main thread accepts data usage methods
ipcMain.handle
// --------------contextBridge-------------------
// The method to send the request ipcRenderer.invoke The first parameter of the is the request key, The second parameter is optional , Use return Return data to the rendering thread
const sendAsync = async () => {
const result = await ipcRenderer.invoke("my-invokable-ipc");
return result;
};
// Talking about methods Throw the page to the rendering thread
contextBridge.exposeInMainWorld("myAPI", {
sendAsync,
});
// ---------------- Rendering thread ---------------------------
// If there is a bridging method (contextBridge), Suggest IPC signal communication , All applications are asynchronous .
// Click the method of the event
async sendAsyncMsg() {
const result = await myAPI.sendAsync()
console.log(result)
}
// -------------- The main thread receives and returns data --------------------
// Asynchronous event listening
// If the rendering thread has data, it can be used args receive
ipcMain.handle('my-invokable-ipc', async (event, ...args) => {
const result = await somePromise()
return result
})
// Write an asynchronous function , Simulate asynchronous methods , Return data after three seconds
function somePromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('message from main process.')
}, 3000)
})
}
边栏推荐
- [deeply understand tcapulusdb technology] tmonitor background one click installation
- Analysis of China's road freight volume, market scale and competition pattern in 2020 [figure]
- TCP/IP 测试题(四)
- Analysis on policy, output and market scale of China's natural gas hydrogen production industry in 2020 [figure]
- TCP/IP 测试题(三)
- Training of long and difficult sentences in postgraduate entrance examination day90
- 想知道新股民怎样炒股票开户?在线开户安全么?
- Class 02 loader subsystem
- [in depth understanding of tcapulusdb technology] tcapulusdb model
- GNU nano
猜你喜欢

快手616战报首发,次抛精华引新浪潮,快品牌跃入热榜top3

07 local method stack
![[deeply understand tcapulusdb technology] table management of document acceptance](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[deeply understand tcapulusdb technology] table management of document acceptance

Web development solution to cross domain problems

Apifox简单了解——WEB端测试的集大成者

为什么生命科学企业都在陆续上云?

Boiled peanuts

Problems encountered during the use of pychar
![Analysis on development status and development suggestions of e-commerce industry in Xinjiang in 2020 [figure]](/img/d1/8ed2958ef365e17494bade6e29ee04.jpg)
Analysis on development status and development suggestions of e-commerce industry in Xinjiang in 2020 [figure]
![Analysis of global tea production, consumption and import and export trade: China's tea production ranks first in the world [figure]](/img/16/ab5056dd26cf7b1a761a92eea46e54.jpg)
Analysis of global tea production, consumption and import and export trade: China's tea production ranks first in the world [figure]
随机推荐
Under what circumstances do you need to manually write the @bean to the container to complete the implementation class
SQL is used for field data types in various databases
Development status of China's hydrotalcite industry in 2020 and analysis of major enterprises: the market scale is rapidly increasing, and there is a large space for domestic substitution [figure]
05 virtual machine stack
一晚上做了一个xpath终结者:xpath-helper-plus
广州华锐互动VR全景为各行各业带来发展
Overview and trend analysis of China's foreign direct investment industry in 2020 [figure]
connect to address IP: No route to host
shell-跳出循环-shift参数左移-函数的使用
RMAN backup database_ Duplexing backup sets
Batch uploading of local jar packages to nexus private server
云上弹性高性能计算,支持生命科学产业高速发展、降本增效
[in depth understanding of tcapulusdb technology] business guide for creating doc acceptance
Anaconda download Tsinghua source
QQ机器人闪照转发/撤回消息转发【最新beta2版本】
Tiger Dao VC products are officially launched, a powerful supplement to seektiger ecology
什么是算子?
【历史上的今天】6 月 25 日:笔记本之父诞生;Windows 98 发布;通用产品代码首次商用
Web development solution to cross domain problems
RMAN backup database_ Skip offline, read-only, and inaccessible files