Electron中require未定义及getSources调用失败问题求助
Electron录屏开发错误排查
1. renderer.js 出现 Uncaught ReferenceError: require is not defined
- 原因:Electron 5+ 版本默认启用上下文隔离(Context Isolation),同时禁用 Node.js 集成,renderer 进程无法直接使用
require或访问 Electron 核心 API,这是 Electron 安全机制的要求。 - 解决:不能在 renderer.js 中直接调用
require('electron'),所有需要访问 Electron API 的逻辑必须通过preload 脚本实现,并通过上下文桥暴露给 renderer 进程。
2. preload.js 出现 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getSources')
这个错误核心是你调用的 getSources 所属模块未正确引入,或未通过上下文桥正确暴露,分三种情况排查:
(1)API 导入路径错误
getSources 是 desktopCapturer 模块的方法,preload.js 中必须正确导入该模块:
// preload.js 正确写法 const { desktopCapturer, contextBridge } = require('electron')
如果误写成 require('electron').getSources 或其他错误路径,会导致调用对象为 undefined。
(2)未通过 contextBridge 暴露 API
preload 脚本不能直接在全局作用域执行 API 调用,必须通过 contextBridge 将能力安全暴露给 renderer 进程,示例代码:
// preload.js const { desktopCapturer, contextBridge } = require('electron') // 向 renderer 进程暴露名为 electronAPI 的全局对象 contextBridge.exposeInMainWorld('electronAPI', { getScreenSources: async () => { return await desktopCapturer.getSources({ types: ['window', 'screen'] }) } })
之后在 renderer.js 中这样调用:
// renderer.js async function fetchSources() { try { const sources = await window.electronAPI.getScreenSources() // 处理获取到的屏幕/窗口源 } catch (err) { console.error(err) } }
(3)主进程 BrowserWindow 配置错误
需确保主进程(main.js)中创建窗口时,正确指定 preload 脚本路径,且保持上下文隔离开启(默认启用,不要手动关闭):
// main.js const { app, BrowserWindow } = require('electron') const path = require('path') function createWindow() { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { // 正确拼接 preload 脚本的绝对路径 preload: path.join(__dirname, 'preload.js'), // 保持默认配置,不要开启 nodeIntegration 或关闭 contextIsolation // nodeIntegration: true <-- 禁用 // contextIsolation: false <-- 禁用 } }) mainWindow.loadFile('index.html') } app.whenReady().then(createWindow) app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit() }) app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow() })
内容的提问来源于stack exchange,提问作者Ctmax
相关产品推荐
相关产品推荐

