2017-04-19 86 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,我有這個問題,但我無法修復它。我該如何解決它? –