本文主要记录在使用新版本的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()
});
修改后重新运行,问题解决~
如果对你有帮助,就点个赞吧~👇