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

Electron渲染进程中desktopCapturer为undefined的问题求助

Electron渲染进程desktopCapturer为undefined问题排查与修复

问题根源分析

  • desktopCapturer是Electron主进程专属模块,无法在渲染进程直接通过require('electron')获取,即使开启nodeIntegration: true
  • Remote模块的导入和初始化方式错误,导致Menu无法正常使用
  • 按钮点击事件绑定错误,直接执行了函数而非绑定函数引用

分步修复方案

1. 主进程(index.js)配置修正

需要先初始化Remote模块,确保渲染进程能正常调用:

const { app, BrowserWindow } = require('electron');
const path = require('path');
// 导入并初始化remote模块
const { initialize } = require('@electron/remote/main');
initialize();

if (require('electron-squirrel-startup')) {
  app.quit();
}

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    width: 1280,
    height: 720,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
    },
  });

  // 为当前窗口启用remote
  require('@electron/remote/main').enable(mainWindow.webContents);

  mainWindow.loadFile(path.join(__dirname, 'index.html'));
  mainWindow.webContents.openDevTools();
};

app.on('ready', createWindow);

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

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

2. 渲染进程(renderer.js)修正

通过@electron/remote获取desktopCapturer和Menu,同时修复按钮点击事件绑定:

const videoElement = document.querySelector('video');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const videoSelectionBtn = document.getElementById('videoSelectionBtn');

// 从remote获取desktopCapturer和Menu
const { desktopCapturer } = require('@electron/remote');
const { Menu } = require('@electron/remote');

// 绑定函数引用,而非直接执行函数
videoSelectionBtn.onclick = getVideoSrcs;

async function getVideoSrcs(){
    console.log(desktopCapturer);
    const inputSources = await desktopCapturer.getSources({
        types:['window', 'screen']
    });

    const videoOptionsMenu = Menu.buildFromTemplate(
        inputSources.map(source =>{
            return{
                label: source.name,
                click: () => selectSource(source)
            };
        })
    );
    console.log(inputSources);
    videoOptionsMenu.popup();
}

// 实现缺失的selectSource函数
function selectSource(source) {
    videoSelectionBtn.innerText = source.name;
    // 可在此添加视频源播放逻辑
}

3. 安装必要依赖

确保已安装@electron/remote:

npm install @electron/remote

关键说明

  • 开启nodeIntegration: true和contextIsolation: false是快速修复方案,但从Electron安全最佳实践出发,更推荐使用预加载脚本通过contextBridge暴露所需API,而非完全开启Node集成。
  • Remote模块在Electron 14+版本需要手动安装并初始化,这是旧教程未覆盖的版本差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:05:20