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>
相关推荐
IT_陈寒25 分钟前
Vue3性能提升30%的秘密:5个90%开发者不知道的组合式API优化技巧
前端·人工智能·后端
我是华为OD~HR~栗栗呀38 分钟前
华为od-22届考研-C++面经
java·前端·c++·python·华为od·华为·面试
老黄编程41 分钟前
FireFox如何滚动截屏?
前端·firefox
_殊途2 小时前
HTML-CSS项目练习
前端·css·html
@AfeiyuO2 小时前
el-table 表格嵌套表格
前端·elementui·vue
我是华为OD~HR~栗栗呀3 小时前
华为OD-23届-测试面经
java·前端·c++·python·华为od·华为·面试
β添砖java4 小时前
vivo响应式官网
前端·css·html·1024程序员节
飞鸟真人7 小时前
VUE+Electron从0开始搭建开发环境
electron·vue
web打印社区9 小时前
使用React如何静默打印页面:完整的前端打印解决方案
前端·javascript·vue.js·react.js·pdf·1024程序员节
喜欢踢足球的老罗9 小时前
[特殊字符] PM2 入门实战:从 0 到线上托管 React SPA
前端·react.js·前端框架