【问题标题】:How to move ipcMain.on calls outside the main.js file如何将 ipcMain.on 调用移到 main.js 文件之外
【发布时间】:2021-01-02 21:22:50
【问题描述】:

我正在使用 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 中访问它。 - 这也会返回一条未定义的消息。

【问题讨论】:

    标签: javascript electron ipcrenderer ipcmain


    【解决方案1】:

    这个问题已经解决了。我使用事件对象从 ipcMain 发送响应。

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

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 2021-09-11
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多