本文介绍了将同步消息从IpcMain发送到IpcRenderer-Electron的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在中,可以通过 ipcRenderer.sendSync('synchronous-message','ping')。

还可以使用 window.webContents.send('ping','将 async 消息从IpcMain发送到IpcRenderer whoooooooh!')

Also possible to send async message from IpcMain to IpcRenderer using window.webContents.send('ping', 'whoooooooh!')

但是有什么方法可以将 sync 消息从IpcMain发送到IpcRenderer吗?

but is there any way to send sync message from IpcMain to IpcRenderer?

推荐答案

没有 ipcMain 这样的功能。但是,您可以通过以下步骤异步获得几乎相同的结果:

There is no such functionality of ipcMain . However, you can achieve almost the same result asynchronously with the following steps:


  • 放置仅在同步调用后才能运行的代码一个 ipcMain 回调。

  • 在渲染器进程中回复ipc消息,并使用 event.sender.send返回结果

  • Place your code which you would run only after the synchronous call in an ipcMain callback.
  • Reply to ipc message in renderer process with the result using event.sender.send

使用这种方法的总和的虚拟示例如下:

A dummy example of sum using this approach looks like the following:

main.js

const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')

app.once('ready', () => {
  let win = new BrowserWindow()
  // have to run "sync", that is only after result is ready
  const doJobWithResult = (res) => {
    console.log(res)
  }
  win.webContents.once('dom-ready', () => {
    win.webContents
    .send('sum-request', 23, 98, 3, 61)
    ipcMain.once('sum-reply', (event, sum) => {
      doJobWithResult(sum)
    })
  })
  win.loadURL(path.resolve(__dirname, 'test.html'))
})

renderer.js(引自test.html)

const {ipcRenderer} = require('electron')

window.onload = () => {
  const add = (a, b) => {
    return a + b
  }
  ipcRenderer.on('sum-request', (event, ...args) => {
    event.sender.send('sum-reply', [...args].reduce(add, 0))
  })
}






这篇关于将同步消息从IpcMain发送到IpcRenderer-Electron的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 21:09