为什么 Electron 的 send 方法在主进程中不起作用?

问题描述

我遇到了大麻烦。我检查了其他解决方案,但没有任何帮助。 我不明白为什么“send方法在这里不起作用。没有例外,没有消息或其他任何东西。

我尝试将 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”方法(在主进程中)时,它向主进程发送数据但没有收到任何响应。

new-client.js:

const { ipcRenderer } = require('electron');
const {resolve} = require('path');
const {Message} = require(resolve('src/js/shared/class/message/message.js'));


ipcRenderer.on('new-client',arg) => {
    console.log(event)
    console.log(arg)
})

async function send() {
    const msg = new Message(
        'new-client','clients',true
    );
    ipcRenderer.send('main',msg);
}

编辑:

我忘记了... 我将数据发送到错误的窗口。

您可以使用 BrowserWindow.getAllWindows,然后将数据发送到特定窗口。

就我个人而言,我在windows打开时添加一个事件,这样我就可以正常发送数据和管理windows了。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)