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

Electron中remote模块已废弃,开发录屏应用时可使用什么模块替代?

解决方案

你遇到的是Electron高版本remote模块废弃导致的功能异常,ipcRenderer和ipcMain完全适用,且是官方推荐的跨进程通信方案。以下提供两种可直接落地的修复方式:


方案1:快速修复,适配现有@electron/remote写法

适合个人小型项目,改动量最小:

  1. 首先安装依赖:
    npm install @electron/remote
  2. 修改主进程index.js配置:
const { app, BrowserWindow } = require('electron')
// 初始化remote模块
require('@electron/remote/main').initialize()

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    }
  })
  // 给当前窗口启用remote权限
  require('@electron/remote/main').enable(win.webContents)
  win.loadFile('index.html')
}
app.whenReady().then(createWindow)

修改完成后你现有的渲染进程代码即可正常运行,该方案关闭了部分安全配置,不适合上线公开的正式项目。


方案2:官方推荐IPC方案,安全性更高

不需要依赖remote模块,符合Electron最新安全规范:

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

const { app, BrowserWindow, ipcMain, Menu, desktopCapturer, path } = require('electron')
let mainWindow

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 开启默认安全配置
      nodeIntegration: false,
      contextIsolation: true,
      // 引入预加载脚本
      preload: path.join(__dirname, 'preload.js')
    }
  })
  mainWindow.loadFile('index.html')
}

// 监听渲染进程的视频源选择请求
ipcMain.handle('get-video-sources', async () => {
  const inputSources = await desktopCapturer.getSources({
    types: ['window', 'screen']
  })
  return new Promise(resolve => {
    // 菜单构建逻辑移到主进程执行
    const videoOptionsMenu = Menu.buildFromTemplate(
      inputSources.map(source => ({
        label: source.name,
        click: () => resolve(source)
      }))
    )
    videoOptionsMenu.popup()
  })
})

app.whenReady().then(createWindow)

步骤2:新增preload.js预加载脚本

const { contextBridge, ipcRenderer } = require('electron')
// 向渲染进程暴露安全的IPC调用方法
contextBridge.exposeInMainWorld('electronAPI', {
  getVideoSources: () => ipcRenderer.invoke('get-video-sources')
})

步骤3:修改渲染进程代码(你的app.js)

//Buttons
const videoElement = document.querySelector('video');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const videoSelectBtn = document.getElementById('videoSelectBtn');
videoSelectBtn.onclick = getVideoSources;

// 移除原有remote、desktopCapturer导入
async function getVideoSources() {
  const selectedSource = await window.electronAPI.getVideoSources()
  // 直接调用你原有逻辑中的selectSource方法即可
  selectSource(selectedSource)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 01:06:00