「Electron|问题记录」解决应用启动后窗口没有渲染相关js的问题,错误信息:Uncaught ReferenceError: require is not defined

本文主要记录在使用新版本的electron过程遇到的显示不符合预期的问题。渲染的js文件种的逻辑不生效,调试窗口提示Uncaught ReferenceError: require is not defined

背景信息

版本信息

nodev16.18.1
npm8.19.2
electronv22.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()
});

修改后重新运行,问题解决~

如果对你有帮助,就点个赞吧~👇

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明仔的阳光午后

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值