0

我正在使用预加载和渲染器 js 将数据从 html 传递到服务器。我有一个主窗口,然后打开另一个窗口(添加窗口)。我从添加窗口获取数据并将其传递给服务器。我在服务器上收到数据,但我不知道如何将带有数据的回调从服务器发送到主窗口 html。

在预加载中,我有:

contextBridge.exposeInMainWorld(
'windowControls',
{
add: (data)=> ipcRenderer.send('item:add',data),
received:(data)=> ipcRenderer.send('item:received',data)

在渲染器添加窗口中:

var input = document.getElementById("inputItem").value;
windowControls.add(input)

在 app.js 中:

// Catch item:add
ipcMain.on('item:add',(e,item)=>{
  console.log('item',item); // Here I can read item
  mainWindow.webContents.on('did-finish-load',()=>{
    mainWindow.webContents.send('item:received',item)
});
  addWindow.close();
})

我应该在 rendererMain 中写什么来获取数据作为主窗口中的回调?主渲染器在第一次运行时执行,而不是在触发回调时执行(如果我用这些行触发了回调)。

4

2 回答 2

0

在 app.js 中(从添加窗口输入接收数据时):

// Catch item:add
ipcMain.on('item:add',(e,item)=>{
  console.log('item',item); // Here I can read item
  mainWindow.send('itemreceived',item)
  addWindow.close();
})

在 preload.js 中(在 contextBridge.exposeInMainWorld() 之外):

const { contextBridge, ipcRenderer } = require('electron')

// Set up context bridge between the renderer process and the main process
contextBridge.exposeInMainWorld(
  'windowControls',
  {
    close: () => ipcRenderer.send('windowControls:close'),
    maximize: () => ipcRenderer.send('windowControls:maximize'),
    minimize: () => ipcRenderer.send('windowControls:minimize'),
    add: (data)=> ipcRenderer.send('item:add',data),
  }
)

ipcRenderer.on('itemreceived',(event,message)=>{
  console.log('item received message',message);
}

类似的例子在这里:https ://gist.github.com/malept/3a8fcdc000fbd803d9a3d2b9f6944612

于 2021-09-19T16:00:16.483 回答
0

did-finish-load事件不是您想要的。此事件在网页加载后触发,如果您停留在同一页面上,则仅触发一次。

您有 2 个解决方案来回答在主进程中收到的消息。

调用消息而不是发送它

您应该参考文档以了解如何调用消息。

这是文档中的示例:

// Renderer process
ipcRenderer.invoke('some-name', someArgument).then((result) => {
  // ...
})

// Main process
ipcMain.handle('some-name', async (event, someArgument) => {
  const result = await doSomeWork(someArgument)
  return result
})

这是您的示例中的样子:


// Renderer process
ipcRenderer.invoke('item:add', item) // This sends the item to main process and wait for the answer
  .then((data) => { // Callback triggered once the result comes back
    console.log(data) // Do what you want with the data
})

// Main process
ipcMain.handle('item:add', async (event, item) => {
  console.log(item)
  return item // Or return whatever you want
})

发送新消息

这不是最好的解决方案,因为随着应用程序的增长它会变得非常复杂。但是您可以从 main 向 renderer 发送一条新消息:

// app.js file
ipcMain.on('item:add',(e,item)=>{
  console.log({item})
  if(yourWindow) { // It can throw an error if yourWindow is null or defined
    yourWindow.webContents.send('item:received',item)
  }
})
于 2021-09-19T14:53:16.767 回答