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

Electron子窗口启用@electron/remote失败,抛出WebContents禁用错误

解决Electron子窗口中@electron/remote启用失败的问题

错误根源

  • @electron/remote/main是主进程专属模块,你在渲染进程(renderer.js)中调用的require("@electron/remote/main").enable(con.webContents)完全无效,该模块仅能在主进程中运行。
  • 子窗口的remote模块启用操作必须在主进程中执行,且要在窗口加载页面之前完成。

修复步骤

1. 重构主进程代码(main.js)

在主进程中初始化remote模块,并通过IPC监听处理子窗口创建逻辑,确保在加载页面前启用子窗口的remote功能:

const { app, BrowserWindow, ipcMain } = require('electron');
const remoteMain = require('@electron/remote/main');

// 初始化remote模块
remoteMain.initialize();

// 创建主窗口
function createMainWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true,
      enableRemoteModule: true
    }
  });

  // 启用主窗口的remote功能
  remoteMain.enable(mainWindow.webContents);
  mainWindow.loadFile('index.html'); // 替换为你的主页面路径
}

// 监听渲染进程的子窗口创建请求
ipcMain.on('create-child-window', (event) => {
  const parentWindow = BrowserWindow.fromWebContents(event.sender);
  const childWindow = new BrowserWindow({
    width: 429,
    height: 781,
    parent: parentWindow,
    autoHideMenuBar: true,
    transparent: true,
    frame: false,
    resizable: false,
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true,
      enableRemoteModule: true,
      webviewTag: true
    }
  });

  // 关键:在加载页面之前启用子窗口的remote功能
  remoteMain.enable(childWindow.webContents);
  childWindow.loadFile('emulator.exe/emulator.html');
});

app.whenReady().then(createMainWindow);

2. 修改渲染进程代码(renderer.js)

移除直接创建子窗口和调用主进程模块的代码,改为通过IPC通知主进程创建子窗口:

const { ipcRenderer, remote } = require('electron');
const currentWindow = remote.getCurrentWindow();

btn.onclick = () => {
  // 发送IPC消息请求主进程创建子窗口
  ipcRenderer.send('create-child-window');
};

3. 子窗口代码(mobile.js)保持不变

只要主进程正确启用了子窗口的remote功能,原代码即可正常运行:

const { ipcRenderer } = require('electron');
const remote = require("@electron/remote");
const windows = remote.getCurrentWindow();
alert(windows);

额外注意事项

  • 确保@electron/remote版本与Electron版本兼容,建议使用官方匹配的最新版本。
  • 生产环境中建议开启contextIsolation: true,通过预加载脚本(preload)暴露必要API,避免直接启用nodeIntegration带来的安全风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:55:03