You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron 14报错:TypeError: Cannot read properties of undefined (reading 'on')——切换BrowserWindow时反复触发该错误的技术求助

解决Electron主进程中TypeError: Cannot read properties of undefined (reading 'on')的问题

你的问题根源很清晰:ipcRenderer是专门给渲染进程使用的API,主进程里需要用ipcMain来监听渲染进程发送的消息。你在主进程的main.js里导入并调用了ipcRenderer.on(),但ipcRenderer在主进程环境中是undefined,这直接触发了这个读取属性失败的错误。

下面是修正后的代码和关键说明:

修正后的main.js代码

const { app, BrowserWindow, ipcMain } = require("electron") // 把ipcRenderer替换为ipcMain
var mainWindow = null
app.on("ready", () => {
    mainWindow = new BrowserWindow({
        width: 500,
        height: 500,
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
        },
        opacity: 0.7,
    })
    mainWindow.loadFile("src/html/welcome.html")
})

// 用ipcMain监听渲染进程发来的"update"消息
ipcMain.on("update", (event, args) => {
    // 增加判断避免mainWindow未初始化的极端情况
    if (mainWindow) {
        mainWindow.loadFile("src/html/update.html")
    }
})

渲染进程代码(无需修改)

const { ipcRenderer } = require("electron")
ipcRenderer.send("update")

额外注意点:

  1. 进程职责边界:Electron的IPC机制分工明确,ipcMain负责在主进程侧监听消息,ipcRenderer负责在渲染进程侧发送/监听消息,绝对不能在错误的进程环境中混用两者。
  2. 安全优化提示:你当前开启的nodeIntegration: true和contextIsolation: false虽然能快速跑通代码,但存在安全风险。如果是面向用户的生产环境应用,建议开启contextIsolation并通过preload脚本实现IPC通信,这是更规范的做法。

内容的提问来源于stack exchange,提问作者BladeOfLightX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 12:07:49