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

Electron中webContents.send发送数据转为空对象问题求助

Electron IPC 发送数据后显示空对象的修复方案

你遇到的问题是因为ipcRenderer.on的回调参数顺序错误——Electron的IPC监听回调第一个参数是事件对象,第二个才是实际传递的数据。你现在把事件对象当成了数据打印,所以显示为空对象。

修复步骤:

1. 修正 preload.js 的监听逻辑

把回调的参数改成(event, sources),先接收事件对象,再接收传递的数据:

contextBridge.exposeInMainWorld('videoEvent', {
  setVideoSources: (callback) => ipcRenderer.on('setVideoSources', (event, sources) => {
    console.log(sources); // 现在会正确打印传递的"test"或对象
    callback(sources);
  }),
});

2. 确认 Main.js 的发送逻辑(当前代码没问题,可验证)

Main.js里的win.webContents.send调用是正确的,确保窗口win已经被正确创建且ready-to-show事件触发时机没问题:

win.once('ready-to-show', () => {
  win.webContents.send('setVideoSources', "test");
})

3. Renderer.js 代码无需修改

你的Renderer.js逻辑是对的,修正preload后就能正确接收数据:

window.videoEvent.setVideoSources((sources) => {
  console.log(sources); // 现在会输出正确的"test"或对象
});

额外提示

如果传递的是复杂对象,确保对象是可序列化的(比如不能包含函数、DOM元素等),Electron IPC会自动序列化/反序列化普通JSON对象,但复杂类型需要额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 03:42:46