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

Electron - IPC - sending data between windows

在主进程中,我创建了一个名为 mainWindow 的 window。单击按钮后,我创建了一个名为 notesWindow 的新 browserWindow

我想要做的是将数据从 notesWindow 发送到 mainWindow

我所做的是使用 IPC 发送首先将数据从 notesWindow 发送到主进程,在主进程上检索数据,然后将该数据发送到 mainWindow,但是 mainWindow 无法接收发送者事件。向主进程发送数据没问题,但是从主进程向browserWindow发送数据好像不行

main.js

const ipcMain = require('electron').ipcMain;

ipcMain.on('notes', function(event, data) {
      console.log(data) // this properly shows the data
      event.sender.send('notes2', data);
});

noteWindow.js

const ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.send('notes', "new note");

mainWindow.js

const ipcRenderer = require("electron").ipcRenderer;
ipcRenderer.on('notes2', function(event, data) {
    // this function never gets called
    console.log(data);
});

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

mainWindow 无法接收事件,因为它没有发送给它。 main.js 中的 events.sender.send() 代码会将数据发送回发送 notes 事件的任何人,在本例中是 noteWindow。所以 notes2 事件被发送回 noteWindow 而不是 mainWindow

要将 notes2 事件发送到 mainWindow,请查看 webContents.send()。这允许主进程通过事件将数据发送到特定的 window。在对 main.js 进行一些修改后,它看起来类似于:

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

无需在 main.js 上设置 ipc hub。这是我的做法。

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

第 1 步:创建主要 window 全局对象

main.js

function createWindow() {
    mainWindow = new BrowserWindow(...);

    global.mainWindow = mainWindow;

    ...
}

第 2 步:将数据发送到 main window(并接收)

noteWindow.js

const ipc = require("electron").ipcRenderer;
ipc.sendTo(
          getGlobal("mainWindow").webContents.id,
          "ChannelForMainWindow",
          data,
          web_component.id // for main window to send back
        );

mainWindow.js

ipc.on("ChannelForMainWindow", (e, data, web_component_id) => {
    // do something
});

(可选)第 3 步:发回数据(以及接收)

noteWindow.js

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

const ipc = require("electron").ipcRenderer;

ipc.on("ChannelForNoteWindow", e => {
    ...
});

ipc.sendTo(
          getGlobal("mainWindow").webContents.id,
          "ChannelForMainWindow",
          data,
          web_component.id // for main window to send back
        );

mainWindow.js

ipc.on("ChannelForMainWindow", (e, data, web_component_id) => {
    // do something

    //send data back
    ipc.sendTo(web_component_id, "ChannelForNoteWindow");
});