w

Examples

This section provides practical examples of how to use the Screenshot Tool in various scenarios.

Basic Usage Examples

Simple Screenshot Capture

// Capture a visible area screenshot
async function captureVisibleArea() {
  try {
    const result = await captureScreenshot({
      mode: 'visible',
      format: 'png',
    });

    console.log('Screenshot captured:', result.dimensions);
    return result;
  } catch (error) {
    console.error('Capture failed:', error);
  }
}

Full Screen Capture

// Capture the entire screen
async function captureFullScreen() {
  try {
    const result = await captureScreenshot({
      mode: 'fullscreen',
      format: 'jpeg',
      quality: 90,
    });

    console.log('Full screen captured:', result.size);
    return result;
  } catch (error) {
    console.error('Full screen capture failed:', error);
  }
}

High Quality Screenshot

// Capture with maximum quality
async function captureHighQuality() {
  try {
    const result = await captureScreenshot({
      mode: 'visible',
      format: 'png', // PNG for lossless quality
      includeCursor: false,
    });

    console.log('High quality screenshot captured');
    return result;
  } catch (error) {
    console.error('High quality capture failed:', error);
  }
}

Download Examples

Download with Custom Filename

// Download screenshot with timestamp
async function downloadWithTimestamp() {
  try {
    const result = await captureScreenshot({ mode: 'visible' });
    const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
    const filename = `screenshot-${timestamp}.png`;

    downloadScreenshot(result.dataUrl, filename);
    console.log(`Downloaded: ${filename}`);
  } catch (error) {
    console.error('Download failed:', error);
  }
}

Batch Download

// Download multiple screenshots
async function batchDownload() {
  const formats = ['png', 'jpeg', 'webp'];
  const results = [];

  for (const format of formats) {
    try {
      const result = await captureScreenshot({
        mode: 'visible',
        format: format,
      });

      const filename = `screenshot-${format}.${format}`;
      downloadScreenshot(result.dataUrl, filename);
      results.push({ format, filename, size: result.size });
    } catch (error) {
      console.error(`Download failed for ${format}:`, error);
    }
  }

  return results;
}

Clipboard Examples

Copy to Clipboard

// Copy screenshot to clipboard
async function copyToClipboard() {
  try {
    const result = await captureScreenshot({ mode: 'visible' });
    const success = await copyToClipboard(result.dataUrl);

    if (success) {
      console.log('Screenshot copied to clipboard');
    } else {
      console.error('Failed to copy to clipboard');
    }
  } catch (error) {
    console.error('Clipboard operation failed:', error);
  }
}

Copy with Notification

// Copy with user notification
async function copyWithNotification() {
  try {
    const result = await captureScreenshot({ mode: 'visible' });
    const success = await copyToClipboard(result.dataUrl);

    if (success) {
      // Show success notification
      showNotification('Screenshot copied to clipboard!', 'success');
    } else {
      showNotification('Failed to copy screenshot', 'error');
    }
  } catch (error) {
    showNotification('Clipboard operation failed', 'error');
  }
}

function showNotification(message, type) {
  // Implementation depends on your notification system
  console.log(`${type.toUpperCase()}: ${message}`);
}

History Management Examples

View History

// Display screenshot history
function displayHistory() {
  const history = getScreenshotHistory();

  if (history.length === 0) {
    console.log('No screenshots in history');
    return;
  }

  console.log(`Found ${history.length} screenshots:`);
  history.forEach((item, index) => {
    console.log(`${index + 1}. ${item.filename} (${item.dimensions}, ${item.size})`);
  });
}

Clear Old Screenshots

// Clear screenshots older than 7 days
function clearOldScreenshots() {
  const history = getScreenshotHistory();
  const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;

  let removedCount = 0;

  history.forEach((item) => {
    if (item.timestamp < sevenDaysAgo) {
      const success = removeFromHistory(item.id);
      if (success) {
        removedCount++;
      }
    }
  });

  console.log(`Removed ${removedCount} old screenshots`);
}

Export History

// Export history as JSON
function exportHistory() {
  const history = getScreenshotHistory();
  const exportData = {
    exportDate: new Date().toISOString(),
    screenshotCount: history.length,
    screenshots: history.map((item) => ({
      id: item.id,
      filename: item.filename,
      dimensions: item.dimensions,
      size: item.size,
      format: item.format,
      timestamp: item.timestamp,
    })),
  };

  const dataStr = JSON.stringify(exportData, null, 2);
  const dataBlob = new Blob([dataStr], { type: 'application/json' });

  const link = document.createElement('a');
  link.href = URL.createObjectURL(dataBlob);
  link.download = 'screenshot-history.json';
  link.click();

  console.log('History exported successfully');
}

Advanced Examples

Screenshot Comparison

// Compare two screenshots
async function compareScreenshots() {
  try {
    // Capture first screenshot
    const screenshot1 = await captureScreenshot({
      mode: 'visible',
      format: 'png',
    });

    // Wait for user to make changes
    await new Promise((resolve) => setTimeout(resolve, 2000));

    // Capture second screenshot
    const screenshot2 = await captureScreenshot({
      mode: 'visible',
      format: 'png',
    });

    // Compare dimensions
    if (
      screenshot1.dimensions.width !== screenshot2.dimensions.width ||
      screenshot1.dimensions.height !== screenshot2.dimensions.height
    ) {
      console.log('Screenshots have different dimensions');
      return;
    }

    // Compare file sizes
    const size1 = parseInt(screenshot1.size);
    const size2 = parseInt(screenshot2.size);
    const sizeDiff = Math.abs(size1 - size2);

    console.log(`Size difference: ${sizeDiff} bytes`);

    return { screenshot1, screenshot2, sizeDiff };
  } catch (error) {
    console.error('Comparison failed:', error);
  }
}

Automated Screenshot Series

// Capture a series of screenshots with delays
async function captureSeries() {
  const delays = [1000, 2000, 3000]; // 1s, 2s, 3s delays
  const results = [];

  for (let i = 0; i < delays.length; i++) {
    try {
      // Wait for the specified delay
      await new Promise((resolve) => setTimeout(resolve, delays[i]));

      // Capture screenshot
      const result = await captureScreenshot({
        mode: 'visible',
        format: 'png',
      });

      results.push({
        index: i + 1,
        delay: delays[i],
        screenshot: result,
      });

      console.log(`Screenshot ${i + 1} captured after ${delays[i]}ms delay`);
    } catch (error) {
      console.error(`Screenshot ${i + 1} failed:`, error);
    }
  }

  return results;
}

Quality Comparison

// Compare different quality settings
async function compareQuality() {
  const qualities = [30, 50, 70, 90, 100];
  const results = [];

  for (const quality of qualities) {
    try {
      const result = await captureScreenshot({
        mode: 'visible',
        format: 'jpeg',
        quality: quality,
      });

      results.push({
        quality: quality,
        size: result.size,
        dimensions: result.dimensions,
      });

      console.log(`Quality ${quality}%: ${result.size}`);
    } catch (error) {
      console.error(`Quality ${quality}% failed:`, error);
    }
  }

  return results;
}

Integration Examples

React Component Integration

import React, { useState } from 'react';

function ScreenshotComponent() {
  const [screenshot, setScreenshot] = useState(null);
  const [isCapturing, setIsCapturing] = useState(false);

  const captureScreenshot = async () => {
    setIsCapturing(true);
    try {
      const result = await captureScreenshot({
        mode: 'visible',
        format: 'png',
      });
      setScreenshot(result);
    } catch (error) {
      console.error('Capture failed:', error);
    } finally {
      setIsCapturing(false);
    }
  };

  const downloadScreenshot = () => {
    if (screenshot) {
      downloadScreenshot(screenshot.dataUrl, 'my-screenshot.png');
    }
  };

  return (
    <div>
      <button onClick={captureScreenshot} disabled={isCapturing}>
        {isCapturing ? 'Capturing...' : 'Capture Screenshot'}
      </button>

      {screenshot && (
        <div>
          <img src={screenshot.dataUrl} alt="Screenshot" />
          <button onClick={downloadScreenshot}>Download</button>
        </div>
      )}
    </div>
  );
}

Vue.js Integration

<template>
  <div>
    <button @click="captureScreenshot" :disabled="isCapturing">
      {{ isCapturing ? 'Capturing...' : 'Capture Screenshot' }}
    </button>

    <div v-if="screenshot">
      <img :src="screenshot.dataUrl" alt="Screenshot" />
      <button @click="downloadScreenshot">Download</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      screenshot: null,
      isCapturing: false,
    };
  },
  methods: {
    async captureScreenshot() {
      this.isCapturing = true;
      try {
        const result = await captureScreenshot({
          mode: 'visible',
          format: 'png',
        });
        this.screenshot = result;
      } catch (error) {
        console.error('Capture failed:', error);
      } finally {
        this.isCapturing = false;
      }
    },
    downloadScreenshot() {
      if (this.screenshot) {
        downloadScreenshot(this.screenshot.dataUrl, 'my-screenshot.png');
      }
    },
  },
};
</script>

Node.js Integration

// Server-side screenshot processing
const express = require('express');
const app = express();

app.post('/api/screenshot', async (req, res) => {
  try {
    const { mode, format, quality } = req.body;

    // Note: This would require a headless browser like Puppeteer
    // for server-side screenshot capture
    const result = await captureScreenshot({
      mode: mode || 'visible',
      format: format || 'png',
      quality: quality || 90,
    });

    res.json({
      success: true,
      data: result,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
    });
  }
});

Error Handling Examples

Comprehensive Error Handling

async function robustCapture() {
  try {
    const result = await captureScreenshot({
      mode: 'visible',
      format: 'png',
    });

    return result;
  } catch (error) {
    switch (error.name) {
      case 'CaptureError':
        console.error('Screenshot capture failed:', error.message);
        break;
      case 'FormatError':
        console.error('Unsupported format:', error.message);
        break;
      case 'StorageError':
        console.error('Storage operation failed:', error.message);
        break;
      default:
        console.error('Unknown error:', error.message);
    }

    // Fallback action
    return null;
  }
}

Retry Logic

async function captureWithRetry(maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const result = await captureScreenshot({
        mode: 'visible',
        format: 'png',
      });

      console.log(`Capture successful on attempt ${attempt}`);
      return result;
    } catch (error) {
      console.error(`Attempt ${attempt} failed:`, error.message);

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

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

These examples demonstrate various ways to use the Screenshot Tool API effectively. Choose the examples that best fit your use case and adapt them to your specific requirements.

Was this page helpful?