Skip to main content

Overview

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

Methods

take()

Captures a screenshot with full configuration options.
take(options: ScreenshotOptions): Promise<ScreenshotResult>

Parameters

ParameterTypeRequiredDescription
optionsScreenshotOptionsYesScreenshot configuration options

ScreenshotOptions

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

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

// 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.
takeBatch(options: BatchScreenshotOptions): Promise<BatchScreenshotResult>

Parameters

ParameterTypeRequiredDescription
optionsBatchScreenshotOptionsYesBatch screenshot configuration

BatchScreenshotOptions

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

Returns

Promise<BatchScreenshotResult> - Batch screenshot results

BatchScreenshotResult

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

Examples

// 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.
screenshot(url: string, options?: Partial<ScreenshotOptions>): Promise<ScreenshotResult>

Parameters

ParameterTypeRequiredDescription
urlstringYesURL to screenshot
optionsPartial<ScreenshotOptions>NoOptional screenshot options

Returns

Promise<ScreenshotResult> - Screenshot result

Example

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.
fullPage(url: string, options?: Partial<ScreenshotOptions>): Promise<ScreenshotResult>

Parameters

ParameterTypeRequiredDescription
urlstringYesURL to screenshot
optionsPartial<ScreenshotOptions>NoOptional screenshot options (fullPage is automatically set to true)

Returns

Promise<ScreenshotResult> - Full-page screenshot result

Example

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.
element(url: string, selector: string, options?: Partial<ScreenshotOptions>): Promise<ScreenshotResult>

Parameters

ParameterTypeRequiredDescription
urlstringYesURL to screenshot
selectorstringYesCSS selector for the element
optionsPartial<ScreenshotOptions>NoOptional screenshot options

Returns

Promise<ScreenshotResult> - Element screenshot result

Example

// 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

// 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

// 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

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

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
// 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

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

// 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

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

// 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;
}