如何使用ElectronJS、NextJS(Nextron)捕获全屏截图
在Nextron项目中实现全屏截图(基于Electron desktopCapturer)
1. 明确Nextron主进程文件位置
Nextron没有传统Electron的main.js,主进程代码默认放在main/目录下,通常是main/index.js(默认模板结构),所有需要调用desktopCapturer这类Electron主进程API的逻辑,都要写在这个目录的文件里。
2. 主进程编写截图逻辑
在main/index.js中实现截图功能,并通过IPC(进程间通信)暴露给渲染进程:
import { app, BrowserWindow, desktopCapturer, ipcMain, screen } from 'electron'; import fs from 'fs'; import path from 'path'; // 监听渲染进程的截图请求 ipcMain.handle('capture-full-screen', async () => { const displays = screen.getAllDisplays(); const screenshotPromises = displays.map(async display => { const sources = await desktopCapturer.getSources({ types: ['screen'], thumbnailSize: display.size }); const screenSource = sources.find(source => source.display_id === display.id.toString()); if (!screenSource) return null; // 将截图转为Buffer并保存 const imageBuffer = screenSource.thumbnail.toPNG(); const savePath = path.join(app.getPath('pictures'), `screenshot-${Date.now()}-${display.id}.png`); fs.writeFileSync(savePath, imageBuffer); return savePath; }); const results = await Promise.all(screenshotPromises); return results.filter(Boolean); });
3. 渲染进程(home.jsx)调用截图功能
在React组件中通过ipcRenderer调用主进程的方法,Nextron中可直接通过window.electron.ipcRenderer访问:
import { useState } from 'react'; export default function Home() { const [screenshotPaths, setScreenshotPaths] = useState([]); const captureScreen = async () => { try { const paths = await window.electron.ipcRenderer.invoke('capture-full-screen'); setScreenshotPaths(paths); alert(`截图已保存到:${paths.join(', ')}`); } catch (error) { console.error('截图失败:', error); alert('截图失败,请查看控制台日志'); } }; return ( <div> <button onClick={captureScreen}>捕获全屏截图</button> {screenshotPaths.length > 0 && ( <div> <h3>已保存的截图路径:</h3> <ul> {screenshotPaths.map((path, idx) => ( <li key={idx}>{path}</li> ))} </ul> </div> )} </div> ); }
4. 解决fs模块找不到的问题
fs是Node.js内置模块,无需执行npm i fs,直接在主进程导入即可。- 渲染进程(
home.jsx这类React组件)默认不能直接访问Node.js模块和Electron主进程API,必须通过IPC让主进程处理文件写入等操作,不能在渲染进程中直接调用fs。
5. 确认Nextron配置有效性
检查nextron.config.js(若存在),确保Node集成未被禁用,默认模板通常已开启:
module.exports = { electron: { nodeIntegration: true, contextIsolation: false // 保证window.electron能正常访问,若开启contextIsolation则需通过preload脚本暴露API } };
内容的提问来源于stack exchange,提问作者Ganning Xu
相关产品推荐
相关产品推荐

