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

Electron集成React时window.require报错及无IPC窗口控制咨询

解决window.require is not a function错误及React控制Electron窗口方案

一、修复window.require报错的可靠方法

1. 适配Electron版本的窗口配置

Electron 12+版本默认禁用nodeIntegration,且默认开启contextIsolation(上下文隔离),后者会隔离渲染进程上下文,导致window.require无法访问。需同时调整这两个配置:

// 主进程代码(main.js)
const { BrowserWindow } = require('electron');

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false // 必须关闭上下文隔离,才能让window.require生效
    }
  });

  mainWindow.loadURL('你的React应用地址');
}

注意:此方案会降低应用安全性,若需兼顾安全,优先使用官方推荐的预加载脚本方案。

2. 官方推荐:预加载脚本(Preload Script)

无需关闭上下文隔离,通过预加载脚本安全暴露Electron API给React:

  • 创建预加载脚本preload.js:
const { ipcRenderer, contextBridge } = require('electron');

// 向渲染进程暴露经过安全过滤的API
contextBridge.exposeInMainWorld('electronAPI', {
  sendIPC: (channel, data) => ipcRenderer.send(channel, data),
  listenIPC: (channel, callback) => ipcRenderer.on(channel, (_, ...args) => callback(...args))
});
  • 主进程配置预加载脚本:
// main.js
const { BrowserWindow, path } = require('electron');

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'), // 指定预加载脚本路径
      contextIsolation: true, // 保持开启,保障安全
      nodeIntegration: false // 保持关闭,默认值
    }
  });

  mainWindow.loadURL('你的React应用地址');
}
  • React组件中调用暴露的API:
// React组件内
window.electronAPI.sendIPC('window-control', 'minimize');

// 监听主进程返回的消息
window.electronAPI.listenIPC('status-update', (data) => {
  console.log('主进程消息:', data);
});

二、不使用IPC控制Electron窗口的方式

可借助@electron/remote模块(原Electron内置remote模块,14+版本需单独安装)直接在React中控制窗口,但该模块存在性能与安全隐患,官方不推荐长期使用:

  1. 安装依赖:
npm install @electron/remote
  1. 主进程初始化remote模块:
// main.js
require('@electron/remote/main').initialize();

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  // 允许当前窗口使用remote模块
  require('@electron/remote/main').enable(mainWindow.webContents);

  mainWindow.loadURL('你的React应用地址');
}
  1. React中直接操作窗口:
// React组件内
const { BrowserWindow } = window.require('@electron/remote');
const currentWindow = BrowserWindow.getFocusedWindow();

// 执行窗口操作
currentWindow.minimize();
currentWindow.maximize();
currentWindow.close();

内容的提问来源于stack exchange,提问作者corche

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:35:28