webContents.send 和 ipcRenderer.on 不工作

webContents.send and ipcRenderer.on Not Working

我是 NodeJS 的新手,但我对 vanilla JS 有相当多的经验。

在下面的代码中,我到底做错了什么?

console.log 在应用程序的开发者控制台中没有任何内容,所以我假设通信渠道以某种方式中断了?

readdir异步有什么关系吗?

index.js

fs.readdir(__dirname, (err, files)=>{
  files.forEach((file, index)=>{
    console.log('display', __dirname+'\'+file) // this prints everything as expected
    mainWindow.webContents.send('display', __dirname+'\'+file)
    // mainWindow.send(...) doesn't work either
  })
})

index.html

const electron = require('electron')
const {ipcRenderer} = electron
const con = document.getElementById('con')

ipcRenderer.on('display', (e, arg)=>{
  const div = document.createElement('div')
  const txt = document.createTextNode(arg)
  div.appendChild(txt)
   con.appendChild(div)

   console.log(e)   // neither this
   console.log(arg) // nor this prints anything to the app's developer console
 })

这是包含所有代码的 CODEPEN

解决方案

事实证明,将 webContents.send 包装在另一个函数中起到了作用。但是,我不确定为什么会这样。

mainWindow.webContents.on('did-finish-load', ()=>{
  mainWindow.webContents.send('display', __dirname+'\'+file)
})

有人愿意向我解释为什么我必须将 webContents.send 包装在另一个函数中才能正常工作吗?

如果消息一创建就发送到 window,它将没有时间加载页面和加载 js 来接收消息。

解决方案是将其包装在 'did-finish-load' 事件中,以便在发送消息之前等待页面准备就绪,如下所示:

mainWindow.webContents.on('did-finish-load', function () {
    mainWindow.webContents.send('channelCanBeAnything', 'message');
});