首页 > 解决方案 > 如何将 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 });
});

我尝试过的事情

标签: javascriptelectronipcrendereripcmain

解决方案


这已解决。我使用事件对象从 ipcMain 发送响应。

ipcMain.on(SIGNIN_REQUEST, async (event, data) => {
  const user = await AuthController.userSignin({ ...data });
  event.sender.send(SIGNIN_RESPONSE, user);
});

推荐阅读