Electron-IPC-在windows之间发送数据

Electron-IPC-在windows之间发送数据,ipc,electron,Ipc,Electron,在主进程中,我创建了一个名为mainWindow的窗口。单击一个按钮,我创建了一个新的浏览器窗口,名为notesWindow 我要做的是将数据从notesWindow发送到main窗口 我所做的是使用IPC send首先将数据从notesWindow发送到主进程,检索主进程上的数据,然后将该数据发送到mainWindow,但是mainWindow无法接收发送方事件。将数据发送到主进程工作正常,但从主进程发送到browserWindow似乎不起作用 main.js noteWindow.js ma

在主进程中,我创建了一个名为
mainWindow
的窗口。单击一个按钮,我创建了一个新的
浏览器窗口
,名为
notesWindow

我要做的是将数据从
notesWindow
发送到
main窗口

我所做的是使用IPC send首先将数据从
notesWindow
发送到主进程,检索主进程上的数据,然后将该数据发送到
mainWindow
,但是
mainWindow
无法接收发送方事件。将数据发送到主进程工作正常,但从主进程发送到browserWindow似乎不起作用

main.js

noteWindow.js

mainWindow.js


谁能解释我做错了什么?提前谢谢

main窗口
无法接收事件,因为它未被发送到该窗口。
main.js
中的
events.sender.send()
code将把数据发送回发送
notes
事件的人,在本例中,这就是
note窗口。因此,
notes2
事件将被发送回
noteWindow
,而不是
mainWindow

要将
notes2
事件发送到
main窗口
,请签出。这允许主进程通过事件将数据发送到特定窗口。对
main.js
进行一些修改后,它看起来类似于:

ipcMain.on('notes', function(event, data) {
    mainWindow.webContents.send('notes2', data);
});

无需在
main.js
上设置ipc集线器。我会这样做的

这里的关键是,如果您想在
渲染器之间进行直接ipc对话,他们需要相互了解
getCurrentWebContent().id

步骤1:创建主窗口全局对象 main.js

函数createWindow(){
主窗口=新浏览器窗口(…);
global.mainWindow=mainWindow;
...
}
步骤2:向主窗口发送数据(并接收) noteWindow.js

const ipc=require(“electron”).ipc渲染器;
发送到(
getGlobal(“主窗口”).webContents.id,
“通道形成窗口”,
数据,
web_component.id//用于发送回主窗口
);
mainWindow.js

ipc.on(“ChannelForMainWindow”,(e,数据,网络组件id)=>{
//做点什么
});
(可选)步骤3:发回数据(同时接收) noteWindow.js

让我们为主窗口回复添加侦听器(如果有)

const ipc=require(“electron”).ipc渲染器;
ipc.on(“频道FornoteWindow”,e=>{
...
});
发送到(
getGlobal(“主窗口”).webContents.id,
“通道形成窗口”,
数据,
web_component.id//用于发送回主窗口
);
mainWindow.js

ipc.on(“ChannelForMainWindow”,(e,数据,网络组件id)=>{
//做点什么
//发回数据
ipc.sendTo(网络组件id,“ChannelForNoteWindow”);
});

谢谢!我以前尝试过使用webContents.send,但无法使其正常工作<代码>未捕获异常:TypeError:无法读取未定义的属性“WebContent”
我将主窗口设置为这样的
让mainWindow=new BrowserWindow({…})
所以不确定为什么主窗口未定义:SInteresting。将其放入
app.on('ready',createWindows)
允许此操作。所以我认为你的答案是正确的。谢谢你的帮助@harmonic,我有这个问题,但我无法解决。如何修复它?我得到的错误是
无法读取未定义的属性“sender”
,但仅在windows 10上。。。
const ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.send('notes', "new note");
const ipcRenderer = require("electron").ipcRenderer;
ipcRenderer.on('notes2', function(event, data) {
    // this function never gets called
    console.log(data);
});
ipcMain.on('notes', function(event, data) {
    mainWindow.webContents.send('notes2', data);
});