用纯js构建 Electron 应用程序。我有一个带有单个webContents的mainWindow(已通过webContents.getAllWebContents()检查)。在主窗口中,我有两个不同的文件,一个从头开始加载(mainWindow.js
),另一个从头开始动态加载(customerList.js
)。
因此,在主要过程中,我正在运行mainWindow.webContents.send('customer:display', customerObject);
。然后在customerList.js
中我有
const customerElectron = require('electron');
customerElectron.ipcRenderer.on('customer:display', (e, customer) => {
console.log('customer: ', customer);
};
这没有被调用。为了检查它是否被调用,我将其添加到了
mainWindow.js
中:const mainElectron = require('electron');
mainElectron.ipcRenderer.on('customer:display', (e, customer) => {
console.log(customer, 'customer');
};
这将被调用并记录正确的客户对象。由于只有一个webContents,因此我假设ipcRenderer只是将事件添加到其中。另外,我通过将监听器包装在
console.log(JSON.stringify(customerElectron.ipcRenderer))
中来检查是否添加了事件。在创建监听器之前,它具有0个事件,之后具有1个事件。因此,肯定会调用添加监听器的代码。由于js脚本属于动态加载的内容,并且当前需要在将内容加载到DOM之后加载,因此我不能仅在
mainWindow.js
中添加监听器。有解决这个问题的方法吗?总的来说,对于一个渲染器进程有多个js文件,以及在这些渲染器中需要多个 Electron ,这是否是一个问题?
最佳答案
我找到了解决问题的方法:
首先,在mainWindow.js
中,我使用var在全局范围内声明了 Electron :
var electron = require('electron');
这使其在其他脚本中可用。我还向脚本添加了onload事件,以等待脚本被加载。在mainWindow.js中:
// loading dynamic content here
callback = _ => { ipcRenderer.send('content:added', '') };
// script contains the script node
script.onload = callback;
在customerList.js中:
electron.ipcRenderer.on('customer:display', customer => {
console.log('Customer: ', customer);
});
然后在main.js中:
// customerObject is a defined customerObject
ipcMain.on('content:added', _ => {
mainWindow.webContents.send('customer:display', customerObject);
};
最后,这会在
customerList.js
和mainWindow中调用该事件,并记录正确的客户对象。
关于javascript - 多个js文件中的ipcRenderer监听器未调用一个渲染器进程/主窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60592911/