【发布时间】:2022-10-14 09:22:09
【问题描述】:
我创建了一个主进程,使用webContents.send向渲染进程传递数据,但它似乎只工作一次,即渲染进程只在程序启动和结束时接收数据;但是我创建的子进程确实可以与主进程通信(log_child.on('message'))
main.js
const win = new BrowserWindow({
width: 900,
height: 600,
resizable: false,
webPreferences: {
preload: path.join(__dirname, './preload/preload.js')
}
});
//This is a subprocess that monitors the log file content in real time and returns data
log_child = spawn('node', ['./assets/js/logs_process.js'], {
stdio: ['pipe', 'ipc', err],
cwd: path.join(__dirname),
env: process.env
});
log_child.on('message', function (data) {
console.log('log_child message: ', data);//The console will print the data returned by the subprocess in real time
win.webContents.send("log_req", data?.logars); //X
});
preload.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
log: (response) => ipcRenderer.on('log_req',response),
})
index.js //rendering process
electronAPI.log((event,detail)=>{
console.log(detail); //Only one time
})
【问题讨论】:
-
不,
send应该发送多次。您确定您在进程中的data事件会触发多次吗? -
您的 preload.js 逻辑有点奇怪。每次调用
log函数时,您都会添加一个事件处理程序。那是你要的吗?您是否只致电log一次? -
@pushkin 是的,“log_child.on('message')”被多次触发,我可以看到“console.log('log_child message:', data);”的输出在控制台中;那么“webContents.send”不应该触发多次吗?那么我的“index.js”中的“electronAPI.log”不应该多次触发吗?我不太明白为什么它不会多次触发,但从逻辑上讲应该是这样,还是我写错了?
标签: electron