我有大麻烦了。我检查了其他解决方案,但没有任何帮助。我不明白为什么“发送”方法在这里不起作用。没有例外,没有消息或其他任何东西。
我尝试将 send 方法包装在另一种方法中,但失败了。我尝试使用“ sendToFrame ”方法,但也失败了。
主要的:
const { app, BrowserWindow, ipcMain } = require('electron')
let win;
function createWindow () {
win = new BrowserWindow({
width: 800,
height: 600,
frame: true,
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: true,
allowRunningInsecureContent: true,
contextIsolation: false, // false if you want to run 2e2 test with Spectron
enableRemoteModule: true,
}
});
win.loadFile('src/home.html');
win.webContents.openDevTools();
ipcMain.on('main', (event, msg) => {
sendData() // Does not work.
event.reply('new-client', 'res') // It works.
})
function sendData() {
win.webContents.send('new-client', {wsh: 'wshsdqsdqs'});
}
};
app.whenReady().then(createWindow);
下面,“ipcRenderer.send”方法有效。当我使用“webContents.send”方法(在主进程中)时,它将数据发送到主进程但没有收到任何响应。
新客户端.js:
const { ipcRenderer } = require('electron');
const {resolve} = require('path');
const {Message} = require(resolve('src/js/shared/class/message/message.js'));
ipcRenderer.on('new-client', (event, arg) => {
console.log(event)
console.log(arg)
})
async function send() {
const msg = new Message(
'new-client',
'clients',
true
);
ipcRenderer.send('main', msg);
}
编辑:
我忘记了……我将数据发送到了错误的窗口。
您可以使用BrowserWindow.getAllWindows,然后将数据发送到特定窗口。
就个人而言,我在窗口打开时添加了一个事件,这样我可以正确发送数据和管理窗口。