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

Electron 5.0.4文本编辑器点击保存按钮报Uncaught TypeError求助

Electron 5.0.4 桌面文本编辑器保存功能报错解决

问题背景

基于Windows系统、VS Code开发环境,使用Electron 5.0.4构建简易桌面文本编辑器,点击保存按钮后DevTools抛出以下错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'send')
at saveText (index.html:69:37)
at HTMLButtonElement.onclick (index.html:38:77)

报错指向saveText函数中ipcRenderer.send('save', text)的调用,期望点击保存时textarea内容能输出到控制台。曾尝试在页面<script>标签内使用const electron = require('electron')但出现require错误,也尝试过重启VS Code等常规操作。

错误原因分析

查看提供的index.html代码,发现渲染进程脚本中存在明显语法错误:

const electron = ('electron') // 缺少require关键字,导致electron变量为字符串而非模块对象
const {ipcRenderer} = electron

这会导致ipcRenderer未被正确获取,调用send方法时自然报错。此外,虽然主进程已开启nodeIntegration: true,但渲染进程未正确引入Electron模块也会引发require错误。

修复步骤

1. 修正渲染进程的模块引入

修改index.html中的<script>代码,补充require关键字:

<script>
const electron = require('electron') // 修复require缺失问题
const {ipcRenderer} = electron

let textarea = document.querySelector('textarea')
let defaultFontSize = 20

function increaseFont(){
    textarea.style.fontSize = `${++defaultFontSize}px`
}

function decreaseFont(){
    textarea.style.fontSize = `${--defaultFontSize}px`        
}

function saveText(){
    let text = textarea.value
    console.log(text)
    ipcRenderer.send('save', text)
}
</script>

2. 确认主进程配置正确性

主进程main.js中已正确设置nodeIntegration: true,这在Electron 5.0.4版本中是允许渲染进程使用Node.js API的必要配置,无需修改:

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

app.on('ready', ()=>{
    let win = new BrowserWindow({
        webPreferences:{
            nodeIntegration: true
        }
    })
    win.loadFile('index.html')
})

ipcMain.on('save', (event, text)=>{
    console.log(text)
})

3. 验证修复效果

重启Electron应用,在textarea中输入内容后点击保存按钮:

  • 渲染进程DevTools控制台会输出textarea内容
  • 主进程控制台(启动应用的终端窗口)也会收到并输出该内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 16:30:10