webContents.send 和 ipcRenderer.on 不工作 [英] webContents.send and ipcRenderer.on Not Working

查看:24
本文介绍了webContents.send 和 ipcRenderer.on 不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 NodeJS 还很陌生,但我确实对 vanilla JS 有相当多的经验.

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?

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

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

这与 readdir 是异步的有什么关系吗?

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

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 包含所有代码.

Here is a CODEPEN with ALL of the code.

事实证明,将 webContents.send 包装在另一个函数中就可以了.但是,我不确定为什么会这样.

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

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

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

推荐答案

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

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.

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

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

这篇关于webContents.send 和 ipcRenderer.on 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆