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

标签 javascript electron ipc

用纯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/

相关文章:

javascript - VueJS 2 - 无法在 App.vue 文件中使用导入文件中的变量

node.js - 使用带有 Node.js 工具的 Visual Studio(不是 VSCode)创建一个 Electron 应用程序

electron - 如何向 Electron 应用程序添加图标

C# 内存在两个进程之间共享,无法从一侧获取读取流

c - 在单个进程中使用命名管道

javascript - 针对 ngFor 变量的 Angular2 ngModel

javascript - Angularjs 进度圈不适用于动态输入

JavaScript:如何在调用 new 后对类进行字符串化

javascript - 如何读取ag-grid中每个单元格的样式(或获取html元素)

html - window.open() 打开一个新的 Electron 浏览器窗口而不是原生浏览器窗口