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

Electron.js点击按钮打开新窗口报require/remote未定义,求最新版最佳方案

问题根因

  • Electron v14及以上版本已经移除了内置的remote模块,即便配置enableRemoteModule: true也无法直接使用,需要额外安装第三方兼容包,且remote本身存在安全隐患,官方已不推荐使用。
  • 你当前开启nodeIntegration: true、关闭contextIsolation: false的配置存在严重安全风险,不符合Electron官方的安全规范,也不是最新版本的推荐配置。

最新版本最佳实现方案(基于IPC通信,符合官方安全规范)

该方案不需要开启nodeIntegration,也不需要依赖remote模块,通过「渲染进程发请求-主进程创建窗口」的逻辑实现,是目前官方推荐的标准做法。

步骤1:修改主进程main.js

调整窗口安全配置,新增IPC监听逻辑处理创建新窗口的请求:

const { app, BrowserWindow, Menu, ipcMain } = require("electron"); // 新增引入ipcMain
const { shell } = require("electron/common");
const path = require("path");

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      devTools: true,
      nodeIntegration: false, // 关闭node集成,保障安全
      contextIsolation: true, // 开启上下文隔离,必须开启
      // 删除enableRemoteModule配置,已无作用
    },
  });

  win.loadFile("src/index.html");
  win.webContents.openDevTools();

  const menu = Menu.buildFromTemplate([
    {
      label: "Menu",
      submenu: [
        { label: "option 1" },
        { label: "option 2" },
        {
          label: "Link",
          click() {
            shell.openExternal("https://www.google.com");
          },
        },
        { type: "separator" },
        {
          label: "Exit",
          click() {
            app.quit();
          },
        },
      ],
    },
    { label: "Info" },
  ]);
  Menu.setApplicationMenu(menu);
}

// 新增:监听渲染进程的创建新窗口请求
ipcMain.on('open-new-window', () => {
  const win = new BrowserWindow({
    height: 200,
    width: 300,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true
    }
  });
  win.loadFile("add.html");
})

app.whenReady().then(() => {
  createWindow();
});

app.on("window-all-closed", function () {
  if (process.platform !== "darwin") app.quit();
});

步骤2:新增/修改preload.js脚本

通过contextBridge将创建窗口的方法暴露给渲染进程:

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electronAPI', {
  openNewWindow: () => ipcRenderer.send('open-new-window')
})

步骤3:修改渲染进程index.js

直接调用preload暴露的方法即可,不需要再引入electron相关模块:

const button = document.getElementById("notifyBtn");
button.addEventListener("click", () => {
  window.electronAPI.openNewWindow();
});

补充说明

如果确实需要继续使用remote模块,可手动安装@electron/remote包并按照官方文档配置,但该方案存在安全风险,仅建议用于内部测试场景,生产环境务必使用上述IPC通信方案。

内容的提问来源于stack exchange,提问作者Syed Muhammad Moiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:36:07