Skip to main content

Chrome Extension Architecture

Overview

The YouTube Copy Link Chrome Extension is built using Manifest V3 and consists of four main components that work together to provide seamless YouTube video collection functionality. The extension follows modern Chrome extension best practices with a service worker architecture.

Component Structure

1. Manifest Configuration (manifest.json)

The manifest file defines the extension's capabilities and structure:

{
"name": "Youtube Links Copy",
"description": "Help you classify youtube links for download later",
"version": "1.1",
"manifest_version": 3,
"permissions": ["activeTab","contextMenus", "storage", "unlimitedStorage"],
"background": {
"service_worker": "background.js",
"type": "module"
},
"action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["https://www.youtube.com/*"],
"js": ["js/content.js"],
"run_at": "document_idle"
}
]
}

Key Features:

  • Manifest V3: Uses the latest Chrome extension standard with service workers
  • Permissions: Requests minimal necessary permissions for tab access, context menus, and storage
  • Content Script Injection: Automatically runs on YouTube pages when the DOM is ready
  • Action Popup: Provides a popup interface accessible from the browser toolbar

2. Service Worker (background.js)

The background script manages the extension's core functionality and handles events:

Context Menu Management

function buildContextMenu() {
const params = chrome.storage.sync.get("params", function (promise) {
const params = promise.params;
if (params === undefined) return;
let paramsArr = [...new Set(params.split('\n').filter(Boolean))]
paramsArr.sort((a, b) => a.localeCompare(b, 'en', { numeric: true }));
for (const param of paramsArr) {
chrome.contextMenus.create({
id: param,
title: param,
type: 'normal',
contexts: ['all']
});
}
});
}

Responsibilities:

  • Dynamic Context Menu Creation: Builds right-click menu items based on user-defined parameters
  • Storage Event Handling: Listens for changes to user parameters and updates context menus accordingly
  • Link Processing: Extracts and normalizes YouTube video URLs when context menu items are clicked
  • Data Persistence: Stores collected video links and IDs in Chrome's storage APIs

URL Processing Logic

The service worker includes sophisticated URL handling:

  • Extracts 11-character YouTube video IDs using regex patterns
  • Normalizes URLs to standard YouTube watch format
  • Maintains a deduplicated list of video IDs for tracking purposes

3. Content Script (js/content.js)

The content script runs on YouTube pages and provides visual feedback:

Visual Indicators

const square = document.createElement('div');
square.style.width = '50px';
square.style.height = '50px';
square.style.backgroundColor = 'rgba(0, 128, 0, 0.5)';
square.style.position = 'absolute';
square.style.top = '0';
square.style.left = '0';
square.style.zIndex = '9999';

Key Features:

  • DOM Monitoring: Uses MutationObserver to detect when YouTube's dynamic content changes
  • Visual Feedback: Adds green overlay squares to video thumbnails that have been previously collected
  • Performance Optimization: Implements throttling to prevent excessive function calls during rapid DOM changes
  • Storage Integration: Retrieves the list of seen video IDs from local storage

DOM Change Detection

The script uses the modern MutationObserver API to handle YouTube's single-page application behavior:

const observer = new MutationObserver(mutationCallback);
observer.observe(document.documentElement, { childList: true, subtree: true });

4. Popup Interface (popup.html + js/popup.js)

The popup provides the main user interface for managing the extension:

User Interface Elements

  • Parameters Textarea: Where users define custom category labels
  • Links Display: Shows collected videos organized by category
  • Control Buttons: Save, Clear, and Copy functionality
  • IDs Management: Displays and manages the list of seen video IDs

Data Management Logic

const newText = Object.entries(listObj)
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
.map(([key, value]) => `${key}\n${value.filter(Boolean).join('\n')}`)
.join('\n');

Functionality:

  • Real-time Updates: Automatically loads and displays current data from storage
  • Data Formatting: Converts internal storage format to user-friendly display format
  • Export Capability: Formats collected links for easy copying to the Java downloader
  • Data Validation: Ensures data integrity when saving user inputs

Data Flow Architecture

Storage Strategy

The extension uses two Chrome storage APIs:

  • chrome.storage.sync: For user preferences and collected links (synced across devices)
  • chrome.storage.local: For video ID tracking (device-specific)

Event-Driven Communication

  1. User defines parameters → Popup saves to sync storage → Background script updates context menus
  2. User right-clicks video → Context menu click → Background script processes URL and stores data
  3. YouTube page loads → Content script checks for seen videos → Visual indicators added
  4. User opens popup → Interface loads current data → User can copy formatted output

Technical Considerations

Performance Optimizations

  • Debouncing: Content script limits DOM observation frequency
  • Deduplication: Uses Set operations to prevent duplicate entries
  • Lazy Loading: Only processes data when needed

Browser Compatibility

  • Manifest V3: Ensures future compatibility with Chrome's extension platform
  • Modern APIs: Uses contemporary web APIs like MutationObserver and Clipboard API
  • Error Handling: Includes fallbacks for storage and clipboard operations

Security Features

  • Minimal Permissions: Requests only necessary permissions
  • Content Security: Runs content scripts only on YouTube domains
  • Data Isolation: Uses Chrome's secure storage APIs instead of localStorage

This architecture provides a robust, efficient, and user-friendly system for collecting and organizing YouTube video links while maintaining good performance and security practices.