当前位置:网站首页>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 in contextBridge in
  • Main thread usage ipcMain receive , Usage method event.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 is contextBridge 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)
  })
}
原网站

版权声明
本文为[Thunderbolt peach]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251827125139.html