Screenshot API: Capture Any Website Programmatically — TongoRender Blog
Back to Blog
tutorialsscreenshotautomationmonitoring

Screenshot API: Capture Any Website Programmatically

Learn how to capture full-page screenshots of any website using an API. Explore use cases like monitoring, testing, archiving, and social proof with practical code examples.

TongoRender TeamMarch 15, 20269 min

Capturing website screenshots programmatically is a surprisingly common need. Developers use screenshot APIs for visual regression testing, uptime monitoring dashboards, generating thumbnails for link previews, archiving web pages for compliance, and creating social proof galleries. In this guide, we will explore the major use cases and show you how to capture pixel-perfect screenshots with the TongoRender Screenshot API.

Why Use a Screenshot API?

You could run a headless browser locally with Puppeteer or Playwright, but a dedicated API offers significant advantages:

  • No infrastructure to manage — No Chromium installations, no memory management, no zombie process cleanup.
  • Consistent rendering — The API uses standardized browser versions and font sets, so screenshots look the same every time.
  • Global availability — Edge rendering means low latency regardless of where your server is located.
  • Built-in features — Viewport control, device emulation, element selection, full-page capture, and format options (PNG, JPEG, WebP) come out of the box.

Use Case 1: Visual Regression Testing

Before deploying a new release, capture screenshots of key pages and compare them against baseline images to detect unintended visual changes:

const fetch = require('node-fetch');
const { compare } = require('resemblejs');
const fs = require('fs');

async function captureScreenshot(url, viewport = { width: 1280, height: 720 }) {
  const response = await fetch('https://api.tongorender.io/v1/screenshot', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': process.env.TONGORENDER_API_KEY,
    },
    body: JSON.stringify({
      url,
      viewport,
      fullPage: false,
      format: 'png',
    }),
  });

  if (!response.ok) throw new Error(`Screenshot failed: ${response.statusText}`);
  return Buffer.from(await response.arrayBuffer());
}

async function visualRegressionTest(pageName, url) {
  const current = await captureScreenshot(url);
  const baselinePath = `baselines/${pageName}.png`;

  if (!fs.existsSync(baselinePath)) {
    fs.writeFileSync(baselinePath, current);
    console.log(`Baseline created for ${pageName}`);
    return;
  }

  const baseline = fs.readFileSync(baselinePath);
  const diff = await compare(baseline, current);

  if (diff.misMatchPercentage > 0.1) {
    fs.writeFileSync(`diffs/${pageName}-diff.png`, diff.getBuffer());
    throw new Error(`Visual regression detected on ${pageName}: ${diff.misMatchPercentage}% mismatch`);
  }

  console.log(`${pageName} passed visual regression test`);
}

Use Case 2: Uptime Monitoring Dashboard

Combine screenshot capture with uptime checks to build a visual monitoring dashboard. If a page returns a 200 but looks broken (blank page, error message), the screenshot tells the full story:

async function monitorSite(url) {
  const start = Date.now();
  const screenshot = await captureScreenshot(url, { width: 1440, height: 900 });
  const loadTime = Date.now() - start;

  await uploadToS3(screenshot, `monitoring/${Date.now()}.png`);

  return {
    url,
    timestamp: new Date().toISOString(),
    loadTimeMs: loadTime,
    screenshotSize: screenshot.length,
  };
}

// Run every 5 minutes for critical pages
const sites = ['https://app.example.com', 'https://checkout.example.com'];
for (const site of sites) {
  await monitorSite(site);
}

Use Case 3: Link Preview Thumbnails

When users share links in your platform, generate thumbnail previews automatically:

async function generateThumbnail(url) {
  const response = await fetch('https://api.tongorender.io/v1/screenshot', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': process.env.TONGORENDER_API_KEY,
    },
    body: JSON.stringify({
      url,
      viewport: { width: 1200, height: 630 },
      fullPage: false,
      format: 'jpeg',
      quality: 80,
    }),
  });

  return Buffer.from(await response.arrayBuffer());
}

Use Case 4: Web Archiving for Compliance

Financial services, healthcare, and legal industries often require archiving web content for regulatory compliance. A screenshot API lets you capture timestamped snapshots:

async function archivePage(url, caseId) {
  const screenshot = await captureScreenshot(url, { width: 1280, height: 0 }); // fullPage
  const metadata = {
    url,
    caseId,
    capturedAt: new Date().toISOString(),
    hash: crypto.createHash('sha256').update(screenshot).digest('hex'),
  };

  await storage.save(`archives/${caseId}/${Date.now()}.png`, screenshot);
  await db.insert('archive_records', metadata);

  return metadata;
}

Advanced Options

TongoRender's screenshot endpoint supports several advanced options for fine-grained control:

  • Device emulation — Capture as iPhone, iPad, or any custom device with specific user agents and pixel ratios.
  • Element capture — Use a CSS selector to screenshot a specific element instead of the full page.
  • Wait strategies — Wait for network idle, a specific element, or a custom JavaScript expression before capturing.
  • Clip region — Define a specific rectangle (x, y, width, height) to capture.
  • Dark mode — Emulate prefers-color-scheme: dark for dark mode screenshots.
// Capture a specific element on mobile
const response = await fetch('https://api.tongorender.io/v1/screenshot', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': process.env.TONGORENDER_API_KEY,
  },
  body: JSON.stringify({
    url: 'https://example.com/dashboard',
    selector: '#revenue-chart',
    device: 'iPhone 14 Pro',
    waitForSelector: '.chart-loaded',
    format: 'webp',
  }),
});

Whether you need screenshots for testing, monitoring, archiving, or content generation, a dedicated API removes the complexity of browser management and lets you focus on building features.

Try TongoRender's Screenshot API — 100 free captures per month, no credit card required.

Share this articleShare on Twitter