Pri*_*Nom 6 events ipc node.js electron
我对 NodeJS 很陌生,但我对 vanilla JS 有很多经验。
在下面的代码中,我到底做错了什么?
它console.log在应用程序的开发者控制台中没有任何内容,所以我假设通信渠道以某种方式中断了?
它与readdir异步的事实有什么关系吗?
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)
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)
| 归档时间: |
|
| 查看次数: |
6571 次 |
| 最近记录: |