本文主要记录在使用新版本的electron过程遇到的显示不符合预期的问题。渲染的js文件种的逻辑不生效,调试窗口提示
Uncaught ReferenceError: require is not defined
背景信息
版本信息
| node | v16.18.1 |
| npm | 8.19.2 |
| electron | v22.0.0 |
问题说明
写了如下函数,用于获取html中id为timer-container的元素,然后将其文本内容替换为倒计时内容:
function updateTime(ms) {
let timerContainer = document.getElementById("timer-container")
let total_seconds = (ms / 1000).toFixed(0)
let seconds = total_seconds % 60
let minutes = (total_seconds / 60).toFixed(0)
timerContainer.innerText = `${minutes.toString().padStart(2, 0)}:${seconds.toString().padStart(2, 0)}`
}
在electron的入口js文件中有创建窗口并加载本地HTML文件的代码如下:
app.on("ready", () => {
win = new BrowserWindow({
width: 300,
height: 300,
webPreferences: {
nodeIntegration: true,
}
})
win.loadFile("./index.html")
win.webContents.openDevTools()
handlerIPC()
});
- 已经确保函数调用没有问题。
- 已经针对Eelectron 5 之后版本
nodeIntegration默认为false的情况,将webPreference中的nodeIntegration置为true - 通过开发者调试工具界面获取到错误信息如下:


问题原因及解决
除了要考虑Electron 5 之后nodeIntegration默认为false的问题,还需要考虑Electron 12 之后contextIsolation默认为true的特性;
所以需要在webPreference中将contextIsolation置为false,如下:
app.on("ready", () => {
win = new BrowserWindow({
width: 300,
height: 300,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
})
win.loadFile("./index.html")
win.webContents.openDevTools()
handlerIPC()
});
修改后重新运行,问题解决~
如果对你有帮助,就点个赞吧~👇
本文介绍在Electron v22.0.0环境下,解决渲染进程JS逻辑不生效的问题。通过调整webPreferences配置项,启用nodeIntegration并禁用contextIsolation,成功修复了倒计时功能。
1万+

被折叠的 条评论
为什么被折叠?



