【发布时间】:2019-08-22 04:09:42
【问题描述】:
是否有一种标准化的方式将数据发送到 Electron 上的窗口?我的意思是,我确实知道这样做是可能,但是推荐或至少最常用的方法是什么?
此外,是否建议使用运行 Electron 应用程序的 Express 服务器来获取所需的数据?
提前感谢您的回复。
【问题讨论】:
-
到目前为止你有什么?
是否有一种标准化的方式将数据发送到 Electron 上的窗口?我的意思是,我确实知道这样做是可能,但是推荐或至少最常用的方法是什么?
此外,是否建议使用运行 Electron 应用程序的 Express 服务器来获取所需的数据?
提前感谢您的回复。
【问题讨论】:
据我所知,在窗口和主进程之间传输数据最多(也是唯一?)的方式是使用ipcMain和ipcRenderer,这里是@ 987654321@.
基本上,它是这样工作的:
index.js
// You create your browserWindow element here
let win = new BrowserWindow()
// and to send data from your Main to your Renderer, you can do the following once the dom is ready:
win.webContents.once('dom-ready', () => {
// Send some data to your browser window
win.webContents.send('data', 'hello world')
})
请注意,不需要 ipcMain 来发送数据到渲染器,而只需要接收它们。
另一方面,在 renderer.js 中,您可以使用以下内容处理数据:
const ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('data', (data) => {
console.log(`Received data: ${data}`)
// Outputs 'Reveived data: Hello world'
})
如果需要从renderer向main发送数据,基本一样,这里举个例子: renderer.js
ipcRenderer.send('otherData', 'Hey, I am the browser')
在 index.js 方面:
const { ipcMain } = require('electron')
ipcMain.on('otherData', (data) => {
console.log(`Received data: ${data}`)
// Displays: 'Received data: Hey, I am the browser'
})
【讨论】: