webContents.send and ipcRenderer.on Not Working

末鹿安然 提交于 2019-12-02 02:44:49

问题


I'm pretty new to NodeJS, but I do have quite a bit of experience with vanilla JS.

In the following code, what exactly am I doing wrong here?

It doesn't console.log anything in the app's developer console, so I'm assuming the channel of communication is broken somehow?

Does it have anything to do with the fact that readdir is asynchronous?

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
 })

Here is a CODEPEN with ALL of the code.

Solution

It turns out wrapping webContents.send in another function did the trick. However, I'm not sure why this is the case.

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

Would somebody care to explain to me why I have to wrap webContents.send within another function for it to work properly?


回答1:


Would somebody care to explain to me why I have to wrap webContents.send within another function for it to work properly?

It's that if you send a message to the window as soon as it's created it doesn't have time to load the page and if the js that receives it isn't loaded yet nothing will happen. But if you send it when it's loaded (which is what the 'did-finish-load' does) then the js ready to receive the event.



来源:https://stackoverflow.com/questions/53753181/webcontents-send-and-ipcrenderer-on-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!