2017-04-19 145 views
7

在主要过程中,我创建了一个名为mainWindow的窗口。点击一个按钮后,我创建了一个名为notesWindow的新的browserWindowElectron - IPC - 在窗口间发送数据

我想要做的就是从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); 
}); 

任何人都可以解释我做错了吗?提前致谢!

回答

5

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

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

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

谢谢!我之前尝试过使用webContents.send,但无法使其正常工作。 '未捕获的异常: 类型错误:无法读取的undefined' 我做了主窗口这样 财产“webContents”'让主窗口=新BrowserWindow({...})' 所以不知道为什么主窗口是未定义:S – Harmonic

+0

有趣。将它放到'app.on('ready',createWindows)'允许这个工作。所以我将你的答案标记为正确。谢谢你的帮助! – Harmonic

+0

@harmonic,我有这个问题,但我无法修复它。我该如何解决它? –