[未调用一个渲染器进程/主窗口的多个js文件中的ipcRenderer侦听器

问题描述 投票:0回答:1

[用普通的js构建电子应用程序。我有一个带有单个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文件,以及在这些渲染器中需要多个电子,这是一个问题吗?

javascript electron ipc
1个回答
0
投票

我找到了解决问题的方法:

首先在mainWindow.js中,我用var声明了全局范围内的电子:

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中调用了该事件,记录了正确的客户对象。

© www.soinside.com 2019 - 2024. All rights reserved.