webContents.send 和 ipcRenderer.on 不工作

Pri*_*Nom 6 events ipc node.js electron

我对 NodeJS 很陌生,但我对 vanilla JS 有很多经验。

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

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

它与readdir异步的事实有什么关系吗?

索引.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
  })
})
Run Code Online (Sandbox Code Playgroud)

索引.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
 })
Run Code Online (Sandbox Code Playgroud)

这是包含所有代码的CODEPEN

解决方案

事实证明,包装webContents.send在另一个函数中可以解决问题。但是,我不确定为什么会这样。

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

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

Mik*_*ike 12

如果您在创建消息后立即将消息发送到窗口,它将没有时间加载页面并加载 js 来接收消息。

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

mainWindow.webContents.on('did-finish-load', function () {
    mainWindow.webContents.send('channelCanBeAnything', 'message');
});
Run Code Online (Sandbox Code Playgroud)

  • 说得通。那么“did-finish-load”事件监听“index.html”(而不是“index.js”)的加载?这非常奇怪,因为“index.js”中“forEach”循环中的“console.log”吐出了所有值,但我猜“index.html”尚未加载,因此无法侦听或接受传递给它的值吗? (2认同)