Lesson 10-Practical Application – Developing a Web Screenshot Tool

This article provides a step-by-step guide to developing a practical web screenshot browser extension, supporting full-page screenshots, region screenshots, and annotation features, covering the entire process from requirements analysis to final release.

Requirements Analysis and Feature Planning

Core Feature List

  1. Full-Page Screenshot: Capture the entire webpage content, including scrollable areas.
  2. Visible Area Screenshot: Capture the currently visible portion of the screen.
  3. Region Screenshot: Select a specific area via mouse drag.
  4. Basic Annotation Tools: Support rectangle, arrow, and text annotations.
  5. One-Click Download: Save screenshots to the local device.

Technology Stack

  • Frontend Technologies: HTML5 Canvas + SVG (for annotation features).
  • Browser APIs: chrome.tabs.captureVisibleTab (for basic screenshot functionality).
  • Extension Architecture: Manifest V3 + Content Scripts + Background Service.

Project Initialization and Setup

Create Project Directory Structure

web-screenshot-extension/
├── manifest.json          # Extension configuration file
├── popup/                 # Popup UI
│   ├── popup.html
│   ├── popup.css
│   └── popup.js
├── content-scripts/       # Content scripts
│   ├── screenshot.js      # Core screenshot logic
│   └── annotation.js      # Annotation functionality
├── icons/                 # Extension icons
│   ├── icon16.png
│   ├── icon48.png
│   └── icon128.png
└── assets/                # Static resources
    └── annotation-icons/  # Annotation tool icons

Write Basic manifest.json

{
  "manifest_version": 3,
  "name": "Web Screenshot Tool",
  "version": "1.0.0",
  "description": "Capture webpage content with one click and support annotations",
  "permissions": [
    "activeTab",
    "scripting",
    "downloads"
  ],
  "host_permissions": [
    "<all_urls>"
  ],
  "action": {
    "default_popup": "popup/popup.html",
    "default_icon": {
      "16": "icons/icon16.png",
      "48": "icons/icon48.png",
      "128": "icons/icon128.png"
    }
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content-scripts/screenshot.js"],
      "css": ["content-scripts/screenshot.css"]
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["assets/annotation-icons/*"],
      "matches": ["<all_urls>"]
    }
  ]
}

Core Feature Implementation

Full-Page Screenshot Functionality

content-scripts/screenshot.js

// Listen for messages from popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'capture-fullpage') {
    captureFullPage().then(sendResponse);
    return true; // Keep message channel open
  }
  if (message.type === 'capture-visible') {
    captureVisibleArea().then(sendResponse);
    return true;
  }
});

// Full-page screenshot implementation
async function captureFullPage() {
  try {
    // 1. Get total page height
    const totalHeight = document.body.scrollHeight;

    // 2. Set canvas dimensions
    const canvas = document.createElement('canvas');
    canvas.width = window.innerWidth;
    canvas.height = totalHeight;
    const ctx = canvas.getContext('2d');

    // 3. Capture and stitch segments
    let currentPosition = 0;
    const viewportHeight = window.innerHeight;

    while (currentPosition < totalHeight) {
      // Scroll to current position
      window.scrollTo(0, currentPosition);

      // Wait for scroll to complete
      await new Promise(resolve => setTimeout(resolve, 200));

      // Capture current viewport
      const viewportCanvas = await chrome.runtime.sendMessage({
        type: 'capture-viewport'
      });

      // Draw to main canvas
      ctx.drawImage(viewportCanvas, 0, currentPosition);

      // Update position
      currentPosition += viewportHeight;
    }

    // 4. Convert to Blob and download
    return new Promise(resolve => {
      canvas.toBlob(blob => {
        resolve(blob);
      }, 'image/png');
    });
  } catch (error) {
    console.error('Full-page screenshot failed:', error);
    throw error;
  }
}

// Visible area screenshot implementation
function captureVisibleArea() {
  return new Promise(resolve => {
    chrome.runtime.sendMessage({ type: 'capture-viewport' }, (response) => {
      if (response && response.blob) {
        resolve(response.blob);
      } else {
        throw new Error('Failed to capture viewport');
      }
    });
  });
}

background.js

// Handle screenshot requests from content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'capture-viewport') {
    captureViewport(sender.tab.id).then(blob => {
      sendResponse({ blob });
    }).catch(error => {
      console.error('Screenshot failed:', error);
      sendResponse({ error: error.message });
    });
    return true; // Keep message channel open
  }
});

// Perform viewport capture
async function captureViewport(tabId) {
  try {
    // Use Chrome API to capture visible area
    const [dataUrl] = await chrome.tabs.captureVisibleTab(tabId, {
      format: 'png'
    });

    // Convert DataURL to Blob
    return dataURLToBlob(dataUrl);
  } catch (error) {
    console.error('Viewport capture failed:', error);
    throw error;
  }
}

// Utility function to convert DataURL to Blob
function dataURLToBlob(dataUrl) {
  const arr = dataUrl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }

  return new Blob([u8arr], { type: mime });
}

Region Screenshot Functionality

popup.js

document.addEventListener('DOMContentLoaded', () => {
  const captureFullBtn = document.getElementById('capture-full');
  const captureVisibleBtn = document.getElementById('capture-visible');
  const captureAreaBtn = document.getElementById('capture-area');

  captureFullBtn.addEventListener('click', () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.tabs.sendMessage(tabs[0].id, { type: 'capture-fullpage' });
    });
  });

  captureVisibleBtn.addEventListener('click', () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.tabs.sendMessage(tabs[0].id, { type: 'capture-visible' });
    });
  });

  captureAreaBtn.addEventListener('click', () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      // Inject region capture script
      chrome.scripting.executeScript({
        target: { tabId: tabs[0].id },
        files: ['content-scripts/area-capture.js']
      });
    });
  });
});

content-scripts/area-capture.js

// Create screenshot overlay
function createCaptureOverlay() {
  const overlay = document.createElement('div');
  overlay.className = 'area-capture-overlay';

  // Create selection box
  const selectionBox = document.createElement('div');
  selectionBox.className = 'selection-box';
  selectionBox.style.position = 'absolute';
  selectionBox.style.border = '2px dashed #fff';
  selectionBox.style.backgroundColor = 'rgba(0, 123, 255, 0.2)';

  // Create control points
  const controls = [
    { position: 'nw' }, // Top-left
    { position: 'ne' }, // Top-right
    { position: 'sw' }, // Bottom-left
    { position: 'se' }  // Bottom-right
  ];

  controls.forEach(control => {
    const ctrl = document.createElement('div');
    ctrl.className = `control-point ${control.position}`;
    ctrl.style.position = 'absolute';
    ctrl.style.width = '10px';
    ctrl.style.height = '10px';
    ctrl.style.backgroundColor = '#fff';
    ctrl.style.border = '1px solid #007bff';
    selectionBox.appendChild(ctrl);
  });

  overlay.appendChild(selectionBox);
  document.body.appendChild(overlay);

  return { overlay, selectionBox };
}

// Initialize region capture
function initAreaCapture() {
  const { overlay, selectionBox } = createCaptureOverlay();

  let isSelecting = false;
  let startX, startY;
  let currentX, currentY;

  // Mouse down event
  document.addEventListener('mousedown', (e) => {
    if (e.target === overlay) {
      isSelecting = true;
      startX = e.clientX;
      startY = e.clientY;

      // Reset selection box position
      selectionBox.style.left = `${startX}px`;
      selectionBox.style.top = `${startY}px`;
      selectionBox.style.width = '0';
      selectionBox.style.height = '0';
    }
  });

  // Mouse move event
  document.addEventListener('mousemove', (e) => {
    if (!isSelecting) return;

    currentX = e.clientX;
    currentY = e.clientY;

    // Calculate selection box dimensions
    const width = currentX - startX;
    const height = currentY - startY;

    // Update selection box position and size
    selectionBox.style.left = `${Math.min(startX, currentX)}px`;
    selectionBox.style.top = `${Math.min(startY, currentY)}px`;
    selectionBox.style.width = `${Math.abs(width)}px`;
    selectionBox.style.height = `${Math.abs(height)}px`;
  });

  // Mouse up event
  document.addEventListener('mouseup', async (e) => {
    if (!isSelecting) return;
    isSelecting = false;

    const width = currentX - startX;
    const height = currentY - startY;

    // Validate selection area
    if (Math.abs(width) < 10 || Math.abs(height) < 10) {
      overlay.remove();
      return;
    }

    // Calculate screenshot parameters
    const x = Math.min(startX, currentX);
    const y = Math.min(startY, currentY);

    // Remove overlay
    overlay.remove();

    // Perform actual screenshot
    await captureSelectedArea(x, y, Math.abs(width), Math.abs(height));
  });
}

// Perform region screenshot
async function captureSelectedArea(x, y, width, height) {
  try {
    // Use Canvas for region screenshot
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d');

    // Draw webpage content to Canvas
    // Note: Special handling needed for cross-origin content
    // Simplified example using html2canvas
    html2canvas(document.body, {
      x,
      y,
      width,
      height,
      scrollX: -window.scrollX,
      scrollY: -window.scrollY
    }).then(canvas => {
      canvas.toBlob(blob => {
        downloadBlob(blob, 'area-screenshot.png');
      });
    });

    // Chrome API cannot directly capture specific regions
    // Use html2canvas as a fallback
    await injectHtml2Canvas();

    // Call html2canvas for screenshot
    const result = await chrome.scripting.executeScript({
      target: { tabId: chrome.tabs.getCurrent().id },
      func: () => {
        return new Promise(resolve => {
          html2canvas(document.body, {
            x: window.selectionX,
            y: window.selectionY,
            width: window.selectionWidth,
            height: window.selectionHeight,
            scrollX: -window.scrollX,
            scrollY: -window.scrollY
          }).then(canvas => {
            canvas.toBlob(blob => {
              resolve(blob);
            });
          });
        });
      }
    });

    if (result && result[0].result) {
      downloadBlob(result[0].result, 'area-screenshot.png');
    }
  } catch (error) {
    console.error('Region screenshot failed:', error);
    alert('Region screenshot failed, please try again');
  }
}

// Inject html2canvas library
async function injectHtml2Canvas() {
  await chrome.scripting.executeScript({
    target: { tabId: chrome.tabs.getCurrent().id },
    files: ['https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js']
  });
}

// Download Blob file
function downloadBlob(blob, filename) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

// Initialize
initAreaCapture();

Annotation Functionality

content-scripts/annotation.js

// Annotation tool manager
class AnnotationManager {
  constructor() {
    this.tools = {
      rectangle: this.drawRectangle.bind(this),
      arrow: this.drawArrow.bind(this),
      text: this.drawText.bind(this)
    };

    this.currentTool = null;
    this.isDrawing = false;
    this.startX = 0;
    this.startY = 0;
    this.currentElement = null;

    this.initToolbar();
    this.initCanvas();
  }

  // Initialize toolbar
  initToolbar() {
    const toolbar = document.createElement('div');
    toolbar.className = 'annotation-toolbar';

    const tools = [
      { id: 'rectangle', icon: 'assets/annotation-icons/rectangle.svg', name: 'Rectangle' },
      { id: 'arrow', icon: 'assets/annotation-icons/arrow.svg', name: 'Arrow' },
      { id: 'text', icon: 'assets/annotation-icons/text.svg', name: 'Text' }
    ];

    tools.forEach(tool => {
      const btn = document.createElement('button');
      btn.className = 'tool-btn';
      btn.dataset.tool = tool.id;
      btn.innerHTML = `<img src="${tool.icon}" alt="${tool.name}">`;
      btn.addEventListener('click', () => this.setTool(tool.id));
      toolbar.appendChild(btn);
    });

    document.body.appendChild(toolbar);
  }

  // Initialize canvas
  initCanvas() {
    this.canvas = document.createElement('canvas');
    this.canvas.className = 'annotation-canvas';
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    this.ctx = this.canvas.getContext('2d');

    // Set canvas styles
    this.canvas.style.position = 'fixed';
    this.canvas.style.top = '0';
    this.canvas.style.left = '0';
    this.canvas.style.pointerEvents = 'none'; // Allow click-through

    document.body.appendChild(this.canvas);

    // Listen for mouse events
    this.canvas.addEventListener('mousedown', this.handleMouseDown.bind(this));
    this.canvas.addEventListener('mousemove', this.handleMouseMove.bind(this));
    this.canvas.addEventListener('mouseup', this.handleMouseUp.bind(this));
  }

  // Set current tool
  setTool(toolId) {
    this.currentTool = this.tools[toolId];
    console.log(`Current tool: ${toolId}`);
  }

  // Handle mouse down event
  handleMouseDown(e) {
    if (!this.currentTool) return;

    this.isDrawing = true;
    this.startX = e.clientX;
    this.startY = e.clientY;

    // Create temporary drawing element
    this.currentElement = document.createElement('div');
    this.currentElement.className = 'annotation-element';
    this.currentElement.style.position = 'absolute';
    this.currentElement.style.left = `${this.startX}px`;
    this.currentElement.style.top = `${this.startY}px`;
    document.body.appendChild(this.currentElement);
  }

  // Handle mouse move event
  handleMouseMove(e) {
    if (!this.isDrawing || !this.currentTool) return;

    // Clear previous drawing
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    // Call current tool's drawing method
    this.currentTool(this.startX, this.startY, e.clientX, e.clientY);
  }

  // Handle mouse up event
  handleMouseUp(e) {
    if (!this.isDrawing || !this.currentTool) return;

    // Complete drawing
    this.isDrawing = false;

    // Add logic to save annotations here
    console.log('Annotation completed');

    // Remove temporary element
    if (this.currentElement) {
      this.currentElement.remove();
      this.currentElement = null;
    }
  }

  // Draw rectangle
  drawRectangle(x1, y1, x2, y2) {
    const width = x2 - x1;
    const height = y2 - y1;

    this.ctx.strokeStyle = '#ff0000';
    this.ctx.lineWidth = 2;
    this.ctx.strokeRect(x1, y1, width, height);
  }

  // Draw arrow
  drawArrow(x1, y1, x2, y2) {
    const headlen = 10; // Arrowhead length
    const angle = Math.atan2(y2 - y1, x2 - x1);

    // Draw line
    this.ctx.beginPath();
    this.ctx.moveTo(x1, y1);
    this.ctx.lineTo(x2, y2);
    this.ctx.strokeStyle = '#ff0000';
    this.ctx.lineWidth = 2;
    this.ctx.stroke();

    // Draw arrowhead
    this.ctx.beginPath();
    this.ctx.moveTo(x2, y2);
    this.ctx.lineTo(
      x2 - headlen * Math.cos(angle - Math.PI / 6),
      y2 - headlen * Math.sin(angle - Math.PI / 6)
    );
    this.ctx.lineTo(
      x2 - headlen * Math.cos(angle + Math.PI / 6),
      y2 - headlen * Math.sin(angle + Math.PI / 6)
    );
    this.ctx.closePath();
    this.ctx.fillStyle = '#ff0000';
    this.ctx.fill();
  }

  // Draw text
  drawText(x1, y1, x2, y2) {
    // Simplified implementation: actual text annotation requires more complex logic
    console.log('Text annotation requires more complex implementation');
  }
}

// Initialize annotation tool
const annotationManager = new AnnotationManager();

Packaging and Release Process

Local Testing of the Extension

  1. Open Chrome browser and navigate to chrome://extensions/.
  2. Enable “Developer mode”.
  3. Click “Load unpacked” and select the project root directory web-screenshot-extension.

Packaging the Extension

  1. In the Extensions management page, click “Pack extension”.
  2. Select the extension root directory.
  3. Set the private key file (generated automatically on first pack).
  4. Click “Pack” button.
  5. Obtain the generated .crx and .pem files.

Publishing to Chrome Web Store

  1. Register a Google Developer account ($5 one-time fee).
  2. Go to the Chrome Developer Console.
  3. Create a new project.
  4. Upload the packaged .crx file.
  5. Provide extension details:
    • Detailed description.
    • High-quality screenshots (at least 4).
    • Feature icons (16×16, 48×48, 128×128).
    • Category selection.
  6. Submit for review (typically takes 1-7 days).

Advanced Optimization Directions

  1. Performance Optimization:
    • Use Web Workers for processing large screenshots.
    • Implement screenshot caching mechanism.
    • Optimize annotation drawing performance.
  2. Feature Enhancements:
    • Add cloud storage functionality.
    • Support OCR text recognition.
    • Implement screenshot sharing features.
  3. User Experience Improvements:
    • Add keyboard shortcut support.
    • Implement annotation history records.
    • Support multilingual interfaces.

Through this practical project, you not only master the core technologies of browser extension development but also learn how to break down complex functionalities into manageable modules. The key to extension development lies in balancing feature richness with performance while focusing on user experience details.

Share your love