Electron: 主进程和渲染进程之间通信

复制代码
// 渲染进程 向 主进程 异步通信

// preload.js 预加载
const {ipcRenderer} = require('electron')
ipcRenderer.send('on-send-event', '这里是需要传递的参数') // 第一步

ipcRenderer.on('on-resend-event', (e, data) => {
    console.log(data) // 打印的是ipcMain.on传递过来的参数:这里还是传递的参数
}) // 第四步也就是最后一步



// main.js  主进程
const {ipcMain} = require('electron')
// 第二步
ipcMain.on('on-send-event', (e, data) => {
    console.log(data) // 打印的是ipcRenderer.send传递过来的参数:这里是需要传递的参数

    // 主进程主动给渲染进程传递信息(e.sender就是ipcMain)
    e.sender.send('on-resend-event', '这里还是传递的参数') // 第三步
})


// 渲染进程 向 主进程 同步通信

// preload.js 预加载
const {ipcRenderer} = require('electron')
const val = ipcRenderer.sendSync('on-send-event', '这里是需要传递的参数') // 第一步
console.log(val) // 第四步, 同步接收第三步传递过来的参数:来自于主进程的同步信息




// main.js  主进程
const {ipcMain} = require('electron')
// 第二步
ipcMain.on('on-send-event', (e, data) => {
    console.log(data) // 打印的是ipcRenderer.send传递过来的参数:这里是需要传递的参数

    // 主进程主动给渲染进程传递信息(e.sender就是ipcMain)
    e.returnValue = '来自于主进程的同步信息' // 第三步
})

主进程主动给渲染进程通信代码如下

复制代码
// 主进程 向 渲染进程 通信


// main.js  主进程
const {ipcMain, BroserWindow} = require('electron')
// 第一步,在自定义菜单Menu的click事件触发
click() {
    // BrowserWindow.getFocusedWindow:获取当前窗口
    BrowserWindow.getFocusedWindo().webContents.send('mtp', '来自主进程')
}


// preload.js 预加载
const {ipcRenderer} = require('electron')

// 第二步
ipcRenderer.on('mtp', (e, data) => {
    console.log(data) // 打印的是BrowserWindow.getFocusedWindo().webContents.send传递过来的参数:来自主进程


}) 

实现从子窗口点击按钮后传递数据给父窗口的渲染进程实现逻辑:由子窗口的渲染进程传递消息给主进程,然后再由主进程传递消息给主进程的html渲染进程

复制代码
// preload.js 预加载
const {ipcRenderer} = require('electron')

ipcRenderer.send('mtp', '我是参数') 
ipcRenderer.on('mti', (e, data) => {
    // 接收到数据data
}) 


// main.js  主进程
const {ipcMain, BroserWindow} = require('electron')

let mainWindowId = null;
function createWindow() {
    const mainWindow = new BrowserWindow({
        width: 1000,
        height: 800,
        webPreferences: {
 
        }
    })
    mainWindowId = mainWindow.id
}

ipcMain.on('mtp', (e, data) => {
    // data:我是参数
    let mainWin = BroserWindow.fromId(mainWinId)
    mainWin.webContents.send('mti', data) // 主进程给渲染进程html传递数据
})
相关推荐
Dream-Y.ocean6 小时前
鸿蒙PC平台星图遥感适配实战:基于 Electron 壳方案的纯 JavaScript 遥感图像处理引擎开发
javascript·electron·harmonyos
薛定谔的猫-菜鸟程序员9 小时前
Electron开发超详细教程(从入门到放弃)
前端·javascript·electron
北城笑笑13 小时前
Vue 106 ,上篇:前端桌面端应用实现方案( Electron 框架详细介绍,Vue + Electron )
前端·javascript·vue.js·python·electron
不可能片场1 天前
Electron 发布 别拿 load 事件当页面就绪
前端·electron
lpfasd1232 天前
pywebview与Electron
前端·javascript·electron
甘晴void4 天前
我给 Magpie 做了个 macOS 桌宠:106 段动画,请求一多就亮灯
macos·electron·开源·deepseek·桌面宠物·magpie
还好还好不是吗4 天前
我把开源项目托管给 AI 了:一句话提需求,AI 自己开发、自己测试、自己提 PR
electron
栀椩4 天前
Electron 内嵌页面跨域问题(CORS/PNA)解决全记录
前端·javascript·electron
不可能片场5 天前
Electron 发布 cookie 库先查明文再写解密
前端·electron
又过二十6 天前
用 Electron 做的 AI 视频切片工作台:VClip 的技术选型与踩坑实录
ai·electron·aigc·funasr·视频切片