electron 主进程 和 渲染进程通信 ipcRenderer 和 mainWindow.webContents

electron 开发时最麻烦就是electron版本和node版本的选择和正确安装

electron 用npm安装时太慢容易报错,建议用cnpm i 进行安装

javascript 复制代码
注意最新版渲染进程使用node
nodeIntegration: true, // 渲染进程可用node
contextIsolation: false, // 这个值影响nodeIntegration是否生效

electron  的主进程的创建
function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true, // 渲染进程可用node
      contextIsolation: false, // 这个值影响nodeIntegration是否生效
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'))

  // Open the DevTools.
  mainWindow.webContents.openDevTools()
  // 渲染进程使用remote 
  remote.enable(mainWindow.webContents)//3
  require("./ipcMain/menu")
  require("./ipcMain/rightMenu")
  // 主进程发送消息
  mainWindow.webContents.send("mainMag","发财发财")
}

app.on('ready', createWindow);
html 复制代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World!</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <h1>💖 Hello World!</h1>
    <p>Welcome to your Electron application.</p>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.

    <!-- You can also require other files to run in this process -->
    <!-- <script src="./renderer.js"></script> -->
  </body>
  <script>
  // 引用node中的函数
    require('path')
    // 高版本,渲染线程打开新窗口方法,需要在主进程打开
    // const {BrowserWindow} = require("@electron/remote")
    // const win = new BrowserWindow({
    //         width:500,
    //         height:500,
    //     })
    // win.loadURL("https://www.baidu.com")
    const { ipcRenderer } = require("electron");
    window.addEventListener('contextmenu', (e) => {
      e.preventDefault()
      // 渲染进程发送消息
      ipcRenderer.send('show-context-menu')
    })
	// 渲染进程接受主进程消息
    ipcRenderer.on('context-menu-command', (e, command) => {
      // ...
    })
    ipcRenderer.on('show-context-menu-reply', (e, command) => {
      console.log("开心",command)
    })
    ipcRenderer.on('mainMag', (e, command) => {
      console.log(e)
      console.log("------------")
      console.log(command)
    })
  </script>
</html>
相关推荐
Komorebi_99997 小时前
LangChain Day5 课程:Agent 智能代理
前端·langchain·大模型
七牛云行业应用7 小时前
别等了!xAI 的终端编码 Agent 来了——Grok Build 0.1 安装到并行 Agent全流程
前端
Asmewill7 小时前
LangGraph学习笔记三(State)
前端
kisshyshy7 小时前
# 🔥 数组去重:从双重循环到 Set,面试官想听什么?
javascript·面试
史前码农JH7 小时前
nodejs项目Monorepo模式的基础操作
前端
RD_daoyi7 小时前
Google 网站收录全流程解析:抓取、索引与排名机制详解
前端·javascript·人工智能·学习·搜索引擎·html
@大迁世界7 小时前
AI还替不了的JS能力
开发语言·前端·javascript·人工智能·ecmascript
相忘于江湖4265437 小时前
vs code 代码保存自动格式化
前端·vue
暗冰ཏོ8 小时前
2026前端开发资源整理大全:从基础学习到工程化实战的完整导航
前端·javascript·css·前端框架·html
前端小D8 小时前
网页渲染过程
前端