11

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?

oldboy
  • 5,729
  • 6
  • 38
  • 86

1 Answers1

16

If you send the message to the window as soon as it's created it won't have time to load the page and load the js to recieve the message.

The solution is to wrap it in the 'did-finish-load' event so it waits for the page to be ready before sending the message, like so:

mainWindow.webContents.on('did-finish-load', function () {
    mainWindow.webContents.send('channelCanBeAnything', 'message');
});
Joshua
  • 5,032
  • 2
  • 29
  • 45
  • 2
    makes sense. so the `did-finish-load` event listens for `index.html` (not `index.js`) to be loaded? it's just super strange since the `console.log` in the `forEach` loop in `index.js` spits out all the values, but i guess `index.html` hasn't loaded yet and therefore can't listen for or accept the values being passed to it? – oldboy Dec 13 '18 at 08:49
  • 1
    @Anthony Yes, that's exactly it. – Joshua Dec 13 '18 at 10:20
  • you did my day! – Ponzio Pilato Mar 23 '20 at 12:03
  • 1
    @PonzioPilato Glad I could help :) – Joshua Mar 24 '20 at 00:11