electron - 快速了解

发布时间 2023-07-13 15:00:00作者: 一头鹿~

electron 前端可使用的桌面客户端。

包含 一个主进程-main.js
多个渲染进程-render.js文件

主线程和渲染进程的特殊方式进行传递数据,以下是简单的例子。

node需要10版本以上,并且git需要安装

渲染进程js

点击查看代码
const { ipcRenderer } = require("electron");
window.addEventListener("DOMContentLoaded", () => {
  ipcRenderer.send("message", "message");
  ipcRenderer.on('replay',(event,arg)=>{
    document.getElementById('id').innerHTML = arg
  })
});

主进程代码块

点击查看代码
const { app, BrowserWindow,ipcMain } = require("electron");

app.on("ready", () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
  });
  mainWindow.loadFile("index.html");
  ipcMain.on('message',(event ,arg)=>{
    console.log(arg)
    event.sender.send('replay','hello123!')
  })
});

快捷方式创建一个electron例子

点击查看代码
# Clone this repository
git clone https://github.com/electron/electron-quick-start
# Go into the repository
cd electron-quick-start
# Install dependencies
npm install
# Run the app
npm start

main.js 创建BrowserWindow

点击查看代码
const { app, BrowserWindow,ipcMain } = require("electron");

app.on("ready", () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,//render.js 可查看process.versions.node 查看版本
    },
  });
  mainWindow.loadFile("index.html");
  ipcMain.on('message',(event ,arg)=>{
    console.log(arg)
    event.sender.send('replay','hello123!')
  })
});