|
| 1 | +import { Page } from '@browserbasehq/stagehand'; |
1 | 2 | import { existsSync, cpSync, mkdirSync } from 'fs'; |
2 | 3 | import { platform } from 'os'; |
3 | 4 | import { join } from 'path'; |
@@ -101,3 +102,44 @@ export function prepareChromeProfile() { |
101 | 102 | } |
102 | 103 | } |
103 | 104 | } |
| 105 | + |
| 106 | + // Use CDP to take screenshot directly |
| 107 | +export async function takeScreenshot(page: Page) { |
| 108 | + const currentPath = process.cwd(); |
| 109 | + const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); |
| 110 | + const screenshotPath = `${currentPath}/agent/browser_screenshots/screenshot-${timestamp}.png`; |
| 111 | + |
| 112 | + const context = page.context(); |
| 113 | + const client = await context.newCDPSession(page); |
| 114 | + const screenshotResult = await client.send('Page.captureScreenshot', { |
| 115 | + format: 'png', |
| 116 | + quality: 100, |
| 117 | + fromSurface: false |
| 118 | + }); |
| 119 | + |
| 120 | + // Save the base64 screenshot data to file with resizing if needed |
| 121 | + const fs = await import('fs'); |
| 122 | + const sharp = (await import('sharp')).default; |
| 123 | + const buffer = Buffer.from(screenshotResult.data, 'base64'); |
| 124 | + |
| 125 | + // Check image dimensions |
| 126 | + const image = sharp(buffer); |
| 127 | + const metadata = await image.metadata(); |
| 128 | + const { width, height } = metadata; |
| 129 | + |
| 130 | + let finalBuffer: Buffer = buffer; |
| 131 | + |
| 132 | + // Only resize if image exceeds 2000x2000 |
| 133 | + if (width && height && (width > 2000 || height > 2000)) { |
| 134 | + finalBuffer = await sharp(buffer) |
| 135 | + .resize(2000, 2000, { |
| 136 | + fit: 'inside', |
| 137 | + withoutEnlargement: true |
| 138 | + }) |
| 139 | + .png() |
| 140 | + .toBuffer(); |
| 141 | + } |
| 142 | + |
| 143 | + fs.writeFileSync(screenshotPath, finalBuffer); |
| 144 | + return screenshotPath; |
| 145 | +} |
0 commit comments