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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:15:39