如何将ipcMain.on调用移动到main.js文件之外



我正在与Electron and 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);
});

最新更新