Electron应用打开浏览器链接报错:window.require不是函数求解决方案
解决Electron中
window.require is not a function错误的可行思路 核心问题定位
你当前的BrowserWindow配置存在**重复定义webPreferences**的问题,后面的配置会完全覆盖前面的,导致你设置的nodeIntegration: true根本没有生效。此外,Electron 12+版本默认开启contextIsolation(上下文隔离),即使手动开启nodeIntegration,渲染进程也无法直接通过window.require访问Electron模块,这是出于安全机制的设计。
正确解决步骤
1. 修复BrowserWindow的webPreferences配置
将重复的webPreferences合并为一个,推荐使用preload脚本(官方安全最佳实践),而非直接开启nodeIntegration:
const mainWindow = new BrowserWindow({ width: 1280, height: 720, autoHideMenuBar: true, resizable: false, webPreferences: { preload: path.join(__dirname, 'preload.js'), contextIsolation: true, // 默认开启,保障安全 nodeIntegration: false // 默认关闭,无需手动开启 } })
2. 编写preload脚本暴露API
在preload.js中使用contextBridge安全地向渲染进程暴露shell.openExternal方法:
const { contextBridge, shell } = require('electron'); // 向渲染进程暴露名为electronAPI的全局对象 contextBridge.exposeInMainWorld('electronAPI', { openExternal: (url) => shell.openExternal(url) });
3. 修改渲染进程代码调用API
无需再使用window.require,直接调用preload暴露的全局API:
const test = () => { window.electronAPI.openExternal("https://google.com"); }
额外说明
你之前修改的webpack.config.js配置和当前window.require的问题无关,若没有其他模块加载问题,可以保持现有配置不变。
内容的提问来源于stack exchange,提问作者Diize
相关产品推荐
相关产品推荐

