经过几天的研究和测试我的代码,我终于让它工作了!
Thanks to this post 帮助我了解我遇到的 ipcRender 和 ipcMain 问题。
对于任何想做类似事情的人,我就是这样做的。
在云端的 UI 代码中,添加以下代码:
const ipcRenderer = window.require('electron').ipcRenderer;
ipcRenderer.send('notes', "the msg from the cloud UI");
在 Electron 的 main.js 中,添加如下代码:
import { ipcMain } from 'electron'
//inside the createWindow function
ipcMain.on('notes', function(event, data) {
console.log('notes: ', data)
mainWindow.webContents.send('notes2', data) //send message back to webview
})
在 Electron 的 webview 标签中,添加如下代码:
<webview src={the_UI_url}
nodeIntegration
preload="file:{the_exact_path_of_preload.js}/preload.js"></webview>
必须包含nodeIntegration,否则你会在UI代码中得到window.require is not a function的错误
在preload.js中,添加如下代码:
const { ipcRenderer } = require('electron')
ipcRenderer.on('notes2', function(event, data) {
console.log('notes2: ', data);
});
添加完所有这些代码后,我在 Electron 控制台中成功看到了“来自云端 UI 的消息”。