![](/img/trans.png)
[英]Issue while sending message from preload.js to main.js using ipcRenderer and ipcmain
[英]How to move ipcMain.on calls outside the main.js file
我正在使用 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 });
});
我嘗試過的事情
這已解決。 我使用事件 object 從 ipcMain 發送響應。
ipcMain.on(SIGNIN_REQUEST, async (event, data) => {
const user = await AuthController.userSignin({ ...data });
event.sender.send(SIGNIN_RESPONSE, user);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.