当前位置:网站首页>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
contextBridge
Method , 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 incontextBridge
in - Main thread usage
ipcMain
receive , Usage methodevent.sender.send
Return 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);
});
contextBridge
receive 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.invoke
Method , The method of sending data iscontextBridge
Use 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)
})
}
边栏推荐
- 07 local method stack
- Overview and trend analysis of China's CT examination equipment industry in 2021 [figure]
- TCP/IP 测试题(五)
- 什么是算子?
- How can the self-supporting number evaluation be safer for cross-border e-commerce platforms such as Amazon, eBay, shopee, lazada, express, Wal Mart and Alibaba international?
- TCP/IP 测试题(二)
- 05 virtual machine stack
- Training of long and difficult sentences in postgraduate entrance examination day84
- 158_ Model_ Power Bi uses DAX + SVG to open up almost all possibilities for making business charts
- 【历史上的今天】6 月 25 日:笔记本之父诞生;Windows 98 发布;通用产品代码首次商用
猜你喜欢
如何快速关闭8080端口
Svn introduction and Usage Summary
Analysis on policy, output and market scale of China's natural gas hydrogen production industry in 2020 [figure]
Overview and trend analysis of China's foreign direct investment industry in 2020 [figure]
[deeply understand tcapulusdb technology] one click installation of tmonitor background
《痞子衡嵌入式半月刊》 第 57 期
【ELT.ZIP】OpenHarmony啃论文俱乐部—数据密集型应用内存压缩
Current situation and trend analysis of China's glass packaging containers in 2021: the revenue of glass packaging containers increases year by year [figure]
Command records of common data types for redis cli operations
广州华锐互动VR全景为各行各业带来发展
随机推荐
Training of long and difficult sentences in postgraduate entrance examination day91
[in depth understanding of tcapulusdb technology] form creation and approval of document acceptance
TCP/IP 测试题(二)
el-table高度自适应
Analysis of China's road freight volume, market scale and competition pattern in 2020 [figure]
Oriental Wealth function (the most complete edition of Childe Yong)
[elt.zip] openharmony paper Club - memory compression for data intensive applications
[deeply understand tcapulusdb technology] one click installation of tmonitor background
Analysis on policy, output and market scale of China's natural gas hydrogen production industry in 2020 [figure]
Analysis on the market scale and pattern of contrast agents in China in 2021: Jiangsu Hengrui pharmaceutical, general electric, Yangzijiang Pharmaceutical Group, Bayer and bleco account for more than
Training of long and difficult sentences in postgraduate entrance examination day88
Problems encountered during the use of pychar
shell-跳出循环-shift参数左移-函数的使用
Svn introduction and Usage Summary
06 local method interface
快手616战报首发,次抛精华引新浪潮,快品牌跃入热榜top3
RMAN backup database_ Use RMAN for split mirror backup
PHP数据库连接version1.1
Apifox简单了解——WEB端测试的集大成者
Addition, deletion, modification and query of mysql~ tables (detailed and easy to understand)