> ## Documentation Index
> Fetch the complete documentation index at: https://docs.browsertest.in/llms.txt
> Use this file to discover all available pages before exploring further.

# ScreenshotAPI

> Methods for capturing website screenshots

## Overview

The `ScreenshotAPI` provides methods for capturing screenshots of websites with various options and configurations.

## Methods

### take()

Captures a screenshot with full configuration options.

```typescript theme={null}
take(options: ScreenshotOptions): Promise<ScreenshotResult>
```

#### Parameters

| Parameter | Type                | Required | Description                      |
| --------- | ------------------- | -------- | -------------------------------- |
| `options` | `ScreenshotOptions` | Yes      | Screenshot configuration options |

#### ScreenshotOptions

```typescript theme={null}
interface ScreenshotOptions {
  /** URL to screenshot */
  url: string;
  /** Capture full page (default: false) */
  fullPage?: boolean;
  /** Viewport width (default: 1280) */
  width?: number;
  /** Viewport height (default: 720) */
  height?: number;
  /** Image format: 'png' | 'jpeg' (default: 'png') */
  format?: 'png' | 'jpeg';
  /** Image quality for JPEG (default: 80) */
  quality?: number;
  /** Wait time in milliseconds before screenshot (default: 0) */
  waitFor?: number;
  /** CSS selector for element screenshot (optional) */
  selector?: string | null;
  /** Request timeout in milliseconds (default: 10000) */
  timeout?: number;
  /** Block ads and trackers (default: true) */
  blockAds?: boolean;
}
```

#### Returns

`Promise<ScreenshotResult>` - Screenshot result with data and metadata

#### ScreenshotResult

```typescript theme={null}
interface ScreenshotResult {
  success: boolean;
  data: {
    screenshot: string; // base64 encoded image
    url: string;
    title: string;
    width: number;
    height: number;
    format: string;
    fullPage: boolean;
  };
  meta: {
    timeMs: number;
    size: number;
  };
}
```

#### Examples

```javascript theme={null}
// Basic screenshot
const result = await bt.screenshot.take({
  url: 'https://example.com'
});

// Full page screenshot
const fullPage = await bt.screenshot.take({
  url: 'https://example.com',
  fullPage: true
});

// Custom viewport
const mobile = await bt.screenshot.take({
  url: 'https://example.com',
  width: 375,
  height: 667
});

// High-quality JPEG
const jpeg = await bt.screenshot.take({
  url: 'https://example.com',
  format: 'jpeg',
  quality: 95
});

// Element screenshot
const element = await bt.screenshot.take({
  url: 'https://example.com',
  selector: '.hero-section'
});
```

### takeBatch()

Captures multiple screenshots in batch.

```typescript theme={null}
takeBatch(options: BatchScreenshotOptions): Promise<BatchScreenshotResult>
```

#### Parameters

| Parameter | Type                     | Required | Description                    |
| --------- | ------------------------ | -------- | ------------------------------ |
| `options` | `BatchScreenshotOptions` | Yes      | Batch screenshot configuration |

#### BatchScreenshotOptions

```typescript theme={null}
interface BatchScreenshotOptions extends Omit<ScreenshotOptions, 'url'> {
  /** Array of URLs to screenshot */
  urls: string[];
}
```

#### Returns

`Promise<BatchScreenshotResult>` - Batch screenshot results

#### BatchScreenshotResult

```typescript theme={null}
interface BatchScreenshotResult {
  success: boolean;
  results: Array<{
    url: string;
    success: boolean;
    data?: ScreenshotResult['data'];
    error?: string;
  }>;
  meta: {
    total: number;
    successful: number;
    timeMs: number;
  };
}
```

#### Examples

```javascript theme={null}
// Batch multiple URLs
const batch = await bt.screenshot.takeBatch({
  urls: [
    'https://site1.com',
    'https://site2.com',
    'https://site3.com'
  ],
  fullPage: true
});

console.log(`${batch.meta.successful}/${batch.meta.total} screenshots captured`);

// Batch with individual options
const mixedBatch = await bt.screenshot.takeBatch({
  requests: [
    { url: 'https://mobile.com', width: 375, height: 667 },
    { url: 'https://desktop.com', width: 1920, height: 1080 },
    { url: 'https://tablet.com', width: 768, height: 1024 }
  ]
});
```

### screenshot()

Convenience method for basic screenshots.

```typescript theme={null}
screenshot(url: string, options?: Partial<ScreenshotOptions>): Promise<ScreenshotResult>
```

#### Parameters

| Parameter | Type                         | Required | Description                 |
| --------- | ---------------------------- | -------- | --------------------------- |
| `url`     | `string`                     | Yes      | URL to screenshot           |
| `options` | `Partial<ScreenshotOptions>` | No       | Optional screenshot options |

#### Returns

`Promise<ScreenshotResult>` - Screenshot result

#### Example

```javascript theme={null}
const screenshot = await bt.screenshot.screenshot('https://example.com');
const fullPage = await bt.screenshot.screenshot('https://example.com', { fullPage: true });
```

### fullPage()

Convenience method for full-page screenshots.

```typescript theme={null}
fullPage(url: string, options?: Partial<ScreenshotOptions>): Promise<ScreenshotResult>
```

#### Parameters

| Parameter | Type                         | Required | Description                                                         |
| --------- | ---------------------------- | -------- | ------------------------------------------------------------------- |
| `url`     | `string`                     | Yes      | URL to screenshot                                                   |
| `options` | `Partial<ScreenshotOptions>` | No       | Optional screenshot options (fullPage is automatically set to true) |

#### Returns

`Promise<ScreenshotResult>` - Full-page screenshot result

#### Example

```javascript theme={null}
const fullPage = await bt.screenshot.fullPage('https://example.com');
const fullPageHighQuality = await bt.screenshot.fullPage('https://example.com', {
  quality: 95,
  format: 'png'
});
```

### element()

Convenience method for element screenshots.

```typescript theme={null}
element(url: string, selector: string, options?: Partial<ScreenshotOptions>): Promise<ScreenshotResult>
```

#### Parameters

| Parameter  | Type                         | Required | Description                  |
| ---------- | ---------------------------- | -------- | ---------------------------- |
| `url`      | `string`                     | Yes      | URL to screenshot            |
| `selector` | `string`                     | Yes      | CSS selector for the element |
| `options`  | `Partial<ScreenshotOptions>` | No       | Optional screenshot options  |

#### Returns

`Promise<ScreenshotResult>` - Element screenshot result

#### Example

```javascript theme={null}
// Screenshot a specific element
const hero = await bt.screenshot.element('https://example.com', '.hero-section');

// Screenshot with custom options
const button = await bt.screenshot.element('https://example.com', '.cta-button', {
  width: 1200,
  height: 800,
  waitFor: 2000
});
```

## Advanced Usage

### Custom Timing

```javascript theme={null}
// Wait for dynamic content
const dynamicContent = await bt.screenshot.take({
  url: 'https://example.com',
  waitFor: 3000, // Wait 3 seconds for content to load
  selector: '.dynamic-content'
});

// Wait for specific element
const loadedContent = await bt.screenshot.take({
  url: 'https://example.com',
  selector: '.loaded-data',
  timeout: 15000 // Longer timeout for slow APIs
});
```

### Performance Optimization

```javascript theme={null}
// Optimized for speed
const fastScreenshot = await bt.screenshot.take({
  url: 'https://example.com',
  blockAds: true, // Reduce network requests
  timeout: 5000,  // Shorter timeout
  format: 'jpeg', // Smaller file size
  quality: 70    // Lower quality
});

// Optimized for quality
const qualityScreenshot = await bt.screenshot.take({
  url: 'https://example.com',
  format: 'png',   // Lossless
  quality: 100,    // Highest quality
  timeout: 20000,  // Longer timeout
  waitFor: 1000    // Wait for content
});
```

### Error Handling

```javascript theme={null}
async function robustScreenshot(url, options = {}) {
  try {
    const result = await bt.screenshot.take({
      url,
      timeout: 15000,
      ...options
    });

    return {
      success: true,
      data: result.data,
      size: result.meta.size
    };

  } catch (error) {
    console.error(`Screenshot failed for ${url}:`, error.message);

    return {
      success: false,
      error: error.message,
      url
    };
  }
}

// Usage
const results = await Promise.all([
  robustScreenshot('https://site1.com'),
  robustScreenshot('https://site2.com'),
  robustScreenshot('https://site3.com')
]);
```

### Batch Processing with Progress

```javascript theme={null}
async function batchWithProgress(urls, options = {}) {
  const total = urls.length;
  let completed = 0;
  const results = [];

  console.log(`Starting batch screenshot of ${total} URLs`);

  for (const url of urls) {
    try {
      const result = await bt.screenshot.take({
        url,
        ...options
      });

      results.push({
        url,
        success: true,
        data: result.data,
        size: result.meta.size
      });

    } catch (error) {
      results.push({
        url,
        success: false,
        error: error.message
      });
    }

    completed++;
    const progress = ((completed / total) * 100).toFixed(1);
    console.log(`Progress: ${completed}/${total} (${progress}%)`);
  }

  const successful = results.filter(r => r.success).length;
  console.log(`Batch complete: ${successful}/${total} successful`);

  return results;
}
```

## File Format Details

### PNG Format

* **Lossless compression**: No quality loss
* **Supports transparency**: Alpha channel
* **Larger file sizes**: Better for screenshots with text
* **Default choice**: Best quality for most use cases

### JPEG Format

* **Lossy compression**: Smaller file sizes
* **No transparency**: White background for transparent elements
* **Quality range**: 0-100 (default: 80)
* **Best for**: Photographs, gradients, when file size matters

```javascript theme={null}
// PNG for quality (default)
const png = await bt.screenshot.take({
  url: 'https://example.com',
  format: 'png'
});

// JPEG for smaller files
const jpeg = await bt.screenshot.take({
  url: 'https://example.com',
  format: 'jpeg',
  quality: 85
});
```

## Viewport Considerations

### Common Viewports

```javascript theme={null}
const viewports = {
  mobile: { width: 375, height: 667 },
  mobileLarge: { width: 414, height: 896 },
  tablet: { width: 768, height: 1024 },
  tabletLarge: { width: 1024, height: 1366 },
  desktop: { width: 1920, height: 1080 },
  desktopLarge: { width: 2560, height: 1440 }
};

async function responsiveScreenshots(url) {
  const results = {};

  for (const [name, viewport] of Object.entries(viewports)) {
    results[name] = await bt.screenshot.take({
      url,
      ...viewport,
      fullPage: true,
      format: 'png'
    });
  }

  return results;
}
```

### Device Pixel Ratio

```javascript theme={null}
// High DPI screenshots
const retina = await bt.screenshot.take({
  url: 'https://example.com',
  width: 750,  // 375 * 2
  height: 1334, // 667 * 2
  // DPR is handled automatically by the browser
});
```

## Best Practices

### Performance

1. **Use appropriate formats**: PNG for quality, JPEG for size
2. **Set reasonable timeouts**: Don't wait unnecessarily long
3. **Batch when possible**: Reduce overhead
4. **Cache results**: Avoid redundant screenshots

### Error Handling

```javascript theme={null}
class ScreenshotService {
  constructor(bt) {
    this.bt = bt;
  }

  async takeScreenshot(url, options = {}) {
    const maxRetries = 3;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        const result = await this.bt.screenshot.take({
          url,
          timeout: 15000,
          ...options
        });

        return result;

      } catch (error) {
        console.warn(`Screenshot attempt ${attempt} failed:`, error.message);

        if (attempt === maxRetries) {
          throw new Error(`Screenshot failed after ${maxRetries} attempts`);
        }

        // Wait before retry
        await new Promise(resolve => setTimeout(resolve, 1000));
      }
    }
  }

  async takeMultipleScreenshots(urls, options = {}) {
    const results = await Promise.allSettled(
      urls.map(url => this.takeScreenshot(url, options))
    );

    return results.map((result, index) => ({
      url: urls[index],
      success: result.status === 'fulfilled',
      data: result.status === 'fulfilled' ? result.value.data : null,
      error: result.status === 'rejected' ? result.reason.message : null
    }));
  }
}
```

### Resource Management

```javascript theme={null}
// Memory-efficient batch processing
async function processLargeBatch(urls, batchSize = 5) {
  const results = [];

  for (let i = 0; i < urls.length; i += batchSize) {
    const batch = urls.slice(i, i + batchSize);
    console.log(`Processing batch ${Math.floor(i / batchSize) + 1}`);

    const batchResults = await bt.screenshot.takeBatch({
      urls: batch,
      fullPage: true
    });

    results.push(...batchResults.results);

    // Allow garbage collection
    if (global.gc) global.gc();
  }

  return results;
}
```
