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