使用 ipcRenderer 时出现错误(typeerror cannot read properties of undefined (reading 'send'))

I am getting an error when using ipcRenderer (typeerror cannot read properties of undefined (reading 'send'))

我在使用 ipcRenderer 时遇到错误(typeerror 无法读取未定义的属性(读取 'send'))。我觉得错误在 (const mainWindowTemplate) 中,我不知道为什么会弹出这个错误,因为其他时候我使用 ipcRenderer 这从未发生过。我也在 preload.js 中使用 ipcMain.on 时遇到错误。我还看到了由这两个引起的更多错误的屏幕截图。

main.js

const electron = require("electron");
const url  = require("url");
const path = require('path');
const { ipcRenderer } = electron;
const {app , BrowserWindow , Menu , IpcMain} = electron;



require('electron-reloader')(module)

let mainWindow;
let windowForAnswer;


function createWindow(){
    mainWindow = new BrowserWindow({
        title: "Aspire Education",
        titleBarStyle: "hiddenInset",
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
            preload: path.join(app.getAppPath(), 'preload.js'),
        }
    });
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname , "mainWindow.html"),
        protocol: 'file:',
        slashes: true
    }))
}

app.on('ready' , function(){
    console.log("ready");
    createWindow();
})

function createWindowQuiz(){
    windowForAnswer = new BrowserWindow({
        title: "Quiz",
        titleBarStyle: "hiddenInset",
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
            preload: path.join(__dirname, 'mainWindow.js'),
        }
    });
    windowForAnswer.loadURL(url.format({
        pathname: path.join(__dirname , "windowForAnswer.html"),
        protocol: 'file:',
        slashes: true
    }))
    
}



const mainMenuTemplate = [
    {
    label: 'File',
    submenu:[
        {
            label:'Start Quiz',
            click(){
              createWindowQuiz();
              ipcRenderer.send("send-questions")
            }
          },
    ]
      
    }   
]




// Add developer tools option if in dev
if(process.env.NODE_ENV !== 'production'){
    mainMenuTemplate.push({
      label: 'Developer Tools',
      submenu:[
        {
          role: 'reload'
        },
        {
          label: 'Toggle DevTools',
          accelerator:process.platform == 'darwin' ? 'Command+I' : 'Ctrl+I',
          click(item, focusedWindow){
            focusedWindow.toggleDevTools();
          }
        }
      ]
    });
  }

menu = Menu.buildFromTemplate(mainMenuTemplate)
Menu.setApplicationMenu(menu)

preload.js

const electron = require('electron')
const url = require('url')
const path = require('path')
const { ipcMain } = require('electron')
const {app , BrowserWindow} = electron

let questions = []
        function Submit() {
            clicked = true
            let question = document.getElementById('question').value;
            let answer = document.getElementById('answer').value;
            if (question.trim() == "" || answer.trim() == "") {
                alert("Question or answer can't be blank")
            } else {
                console.log(question);
                console.log(answer);
                questions.push(question.trim())
                questions.push(answer.trim())
                console.log(questions)
            }
            document.getElementById('question').value = "";
            document.getElementById('answer').value = "";
            return false;
        }

ipcMain.on('send-questions' , () => {
    console.log("Hello World!")
})

您正试图在预加载脚本中访问 ipcMain。

ipcMain 仅在主进程中可用。

https://www.electronjs.org/docs/latest/api/ipc-main/

这就是为什么 ipcMain 未定义并且您收到错误无法读取 属性 on of undefined 的原因。

您可能正在寻找类似使用 ipcRenderer 向主进程发送消息然后在主进程中使用 ipcMain.on 访问它的方法。

因此在您的预加载脚本中:

ipcRenderer.send('send-questions', {data: questions});

在你的主进程中:

ipcMain.on('send-questions', (msg) => {
    console.log(msg.data);
});