You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron中主进程向渲染进程发送数据时值始终为undefined的问题

Electron IPC通信问题:主进程向渲染进程发送数据丢失

我是Electron新手,正在学习IPC通信。目前能正常通过IPC收发消息,渲染进程向主进程发送值时可正常接收并打印,但主进程向渲染进程发送值时,无论数据类型是什么,值始终为undefined。接收事件能正常触发,但数据丢失。

控制台能打印"YUP IT ARRIVED",但options.newData始终是undefined。需要实现渲染进程请求主进程数据,主进程打包后返回给渲染进程用于HTML元素,但数据丢失问题无法解决。

相关代码

渲染进程向主进程发送数据

const dataSend = "Test Data"
ipcRenderer.send('tester:send', {
    dataSend
});

主进程接收并返回数据

ipcMain.on('tester:send', (e, options) => {
    console.log(options.dataSend);

    const newData = "The Final Data";
    mainWindow.webContents.send('tester:toRender', {
        newData
    });
});

渲染进程接收返回数据

ipcRenderer.on('tester:toRender', (e, options) => {
    console.log("YUP IT ARRIVED");
    console.log(options.newData);
})

preload.js代码

//NOTES:
// The preload function is mainly used for exposing nodes to the renderer
// to be used outside the scope of this file

const fs = require('fs');
const os = require('os');
const path = require('path');
const Toastify = require('toastify-js');
const { contextBridge, ipcRenderer} = require('electron');

//Allows use of functions from nods to be used inside main and render
contextBridge.exposeInMainWorld('os', {
    homedir: () => os.homedir()
});

contextBridge.exposeInMainWorld('path', {
    join: (...args) => path.join(...args)
});

contextBridge.exposeInMainWorld('Toastify', {
    toast: (options) => Toastify(options).showToast(),
});

contextBridge.exposeInMainWorld('ipcRenderer', {
    send: (channel, data) => ipcRenderer.send(channel, data),
    on: (channel, func) => ipcRenderer.on(channel, (event, ...args) => func(...args)),
});

问题原因与解决方案

问题出在preload.js中对ipcRenderer.on的封装上:当前代码把IPC回调的event对象丢弃了,只传递了后续的参数,而渲染进程的接收代码期望第一个参数是event,第二个是数据对象。这导致渲染进程里的e实际上是主进程发送的数据,options变成了undefined。

修改preload.js中的ipcRenderer.on封装,保留event对象的传递即可:

contextBridge.exposeInMainWorld('ipcRenderer', {
    send: (channel, data) => ipcRenderer.send(channel, data),
    // 传递完整的event和参数
    on: (channel, func) => ipcRenderer.on(channel, (event, ...args) => func(event, ...args)),
});

或者更简单,直接把原始回调函数传递给ipcRenderer.on:

contextBridge.exposeInMainWorld('ipcRenderer', {
    send: (channel, data) => ipcRenderer.send(channel, data),
    on: (channel, func) => ipcRenderer.on(channel, func),
});

修改后,渲染进程就能正确获取到主进程发送的options.newData值了。

内容的提问来源于stack exchange,提问作者ColtTheNark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 14:56:35