javascript - 如何将 ipcMain.on 调用移到 main.js 文件之外
问题描述
我正在使用 Electron 和 React 开展一个项目。我将通过 ipcMain 和 ipcRenderer 对数据库进行多次调用,因此我将对 ipcMain 的调用移至另一个文件(ipcMainHandler.js)。
我现在面临的挑战是如何将响应发送回 ipcRenderer。我无法从该文件中访问 mainWindow。
这是我的主文件的代码。
const url = require('url');
const { app, BrowserWindow } = require('electron');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
preload: __dirname + '/preload.js'
},
});
const startUrl =
process.env.ELECTRON_START_URL ||
url.format({
pathname: path.join(__dirname, './build/index.html'),
protocol: 'file:',
slashes: true,
});
mainWindow.loadURL(startUrl);
mainWindow.webContents.openDevTools();
mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
if (mainWindow === null) {
createWindow();
}
});
require('./src/server/helpers/ipcMainHandler.js');
ipcMainHandler.js 文件
const { SIGNIN_REQUEST, SIGNIN_RESPONSE } = require('../../common/events.js');
const { ipcMain } = require('electron');
ipcMain.on(SIGNIN_REQUEST, (event, data) => {
const user = AuthController.userSignin({ ...data });
});
我尝试过的事情
- 从远程访问 currentWindow - 引发远程未定义错误
- 将 mainWindow 添加到全局变量并尝试在 ipcHander 中访问它。- 这也返回一个未定义的消息。
解决方案
这已解决。我使用事件对象从 ipcMain 发送响应。
ipcMain.on(SIGNIN_REQUEST, async (event, data) => {
const user = await AuthController.userSignin({ ...data });
event.sender.send(SIGNIN_RESPONSE, user);
});
推荐阅读
- javascript - 在测试中使用回调排序
- botframework - 如何跟踪 QnAMaker 中提出的问题类型?
- unity3d - 为什么 Animator Controller 中的 Preview 窗口是空的?
- scripting - 相关记录的google app maker链接字段
- jquery - 向下滚动时元素被删除(Jquery)
- python - 1064:执行 PyMySQL 查询的 SQL 语法错误
- android - 检测设备是否连接到哪个网络然后从服务器发送数据取决于连接的网络
- android - 使用bounding box时不显示地图;setScrollableAreaLimitDouble
- android - 查询结果是延迟设置应用程序变量
- c# - 驱动程序为空,不知道出了什么问题。Selenium C#:控制台应用程序 (.Net Core 2.0)