electron 通过webContents.send发送数据时为空对象

cnjp1d6j  于 6个月前  发布在  Electron
关注(0)|答案(1)|浏览(62)

我试图在我的电子应用程序中将数据从Main.js发送到Renderer.js,但一旦它进入preload.js,它就会在一个空对象中转换。
在main.js中:

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

字符串
在prelaod.js中:

contextBridge.exposeInMainWorld('videoEvent', {
  setVideoSources: (callback) => ipcRenderer.on('setVideoSources', (sources) => {
    console.log(sources)
    callback(sources);
  }),
});


在renderer.js中

window.videoEvent.setVideoSources((sources) => {
  console.log(sources)
});


两个console.log都显示了一个空对象,我无法找到为什么我可以检索我的数据。(这里是"test",但当我试图将“真实的数据”作为对象发送时,它显然是相同的)。
如果有人有想法,让我知道!

2skhul33

2skhul331#

在您的Electron应用程序中,您在通过preload.js将数据从main.js传递到renderer.js时遇到的问题似乎与如何处理IPC(进程间通信)消息有关。
在Electron中,ipcRenderer.on函数接收两个参数:通道名称和事件对象。从主进程发送的实际数据包含在事件对象中。在您当前的实现中,您将整个事件对象视为您的数据,这就是为什么您在控制台日志中看到一个空对象。
以下是如何修改代码以正确访问发送的数据:

main.js

您的main.js看起来正常。您正在发送一条包含数据"test"的消息setVideoSources

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

字符串

preload.js

preload.js中,修改setVideoSources函数以正确地从事件对象中提取数据。

contextBridge.exposeInMainWorld('videoEvent', {
  setVideoSources: (callback) => ipcRenderer.on('setVideoSources', (event, data) => {
    console.log(data); // Now 'data' should be the actual data sent from main process
    callback(data);
  }),
});

renderer.js

您的renderer.js现在应该收到正确的数据:

window.videoEvent.setVideoSources((data) => {
  console.log(data); // This should now log 'test' or any other data you send
});


您应该能够在两个console.log语句中看到正确的数据(在本例中为"test")。关键的更改是在preload.js中,您需要从ipcRenderer.on提供的事件对象中正确提取数据。

相关问题