Lesson 04-Basic Application of Browser Extension

Browser extensions, as powerful enhancements to browser functionality, have evolved from simple tools into critical technologies for boosting productivity, ensuring privacy, and enhancing web experiences. This tutorial delves into the development of browser extensions across three core application areas, providing systematic knowledge and practical code examples to help developers master the skills needed to build useful extensions.

Productivity Tools Development

Tab Management (Create, Close, Group)

Tab management is one of the most common use cases for browser extensions. Using the chrome.tabs API, developers can achieve comprehensive control over tabs, including creation, closure, movement, and grouping.

Advanced tab creation supports preloading URLs and setting window properties:

// Create a new tab and inject an initialization script
chrome.tabs.create({
  url: 'https://example.com',
  active: true,
  openerTabId: currentTabId // Associate with parent tab
}, (newTab) => {
  // Inject content script after tab creation
  chrome.scripting.executeScript({
    target: { tabId: newTab.id },
    files: ['content-init.js']
  });
});

// Batch create tabs (tab group)
async function createTabGroup(tabsData) {
  const tabIds = [];
  for (const data of tabsData) {
    const tab = await chrome.tabs.create({ url: data.url });
    tabIds.push(tab.id);
  }

  // Group the created tabs
  await chrome.tabs.group({ tabIds });
  await chrome.tabGroups.update(groupId, {
    title: 'Work Project',
    color: 'blue'
  });
}

Tab grouping involves creating tabs first and then grouping them using the tabGroups API to set group properties:

// Complete workflow for creating and grouping tabs
async function setupWorkspace() {
  // 1. Create multiple tabs
  const tab1 = await chrome.tabs.create({ url: 'https://mail.example.com' });
  const tab2 = await chrome.tabs.create({ url: 'https://calendar.example.com' });
  const tab3 = await chrome.tabs.create({ url: 'https://drive.example.com' });

  // 2. Group the tabs
  const groupId = await chrome.tabs.group({ tabIds: [tab1.id, tab2.id, tab3.id] });

  // 3. Configure group visual properties
  await chrome.tabGroups.update(groupId, {
    title: 'Work Suite',
    color: 'green'
  });
}

// Optimized tab closure strategy
function smartCloseTabs() {
  // Get all tabs
  chrome.tabs.query({}, (tabs) => {
    // Filter tabs safe to close (non-pinned and idle for over 30 minutes)
    const closableTabs = tabs.filter(tab => 
      !tab.pinned && 
      (Date.now() - new Date(tab.lastAccessed).getTime()) > 30 * 60 * 1000
    );

    // Batch close
    if (closableTabs.length > 0) {
      chrome.tabs.remove(closableTabs.map(tab => tab.id));
    }
  });
}

Keyboard Shortcut Binding and Custom Actions

Keyboard shortcuts are key to improving extension usability. Shortcuts are declared in manifest.json and handled using the chrome.commands API for custom action responses.

Example shortcut configuration in manifest.json:

{
  "commands": {
    "toggle-feature": {
      "suggested_key": {
        "default": "Ctrl+Shift+Y",
        "mac": "Command+Shift+Y"
      },
      "description": "Toggle core feature"
    },
    "next-tab": {
      "suggested_key": {
        "default": "Ctrl+Tab",
        "mac": "Command+Option+Right"
      },
      "description": "Switch to next tab"
    }
  }
}

Shortcut event handling implementation:

// Listen for shortcut commands
chrome.commands.onCommand.addListener((command) => {
  switch(command) {
    case 'toggle-feature':
      toggleExtensionFeature();
      break;
    case 'next-tab':
      navigateToNextTab();
      break;
    // Handle other commands...
  }
});

// Advanced tab navigation implementation
function navigateToNextTab() {
  chrome.tabs.query({ currentWindow: true }, (tabs) => {
    if (tabs.length < 2) return;

    const currentTab = tabs.find(tab => tab.active);
    const currentIndex = tabs.indexOf(currentTab);
    const nextIndex = (currentIndex + 1) % tabs.length;

    // Activate the next tab
    chrome.tabs.update(tabs[nextIndex].id, { active: true });

    // Optional: Focus the window
    chrome.windows.update(tabs[nextIndex].windowId, { focused: true });
  });
}

// Dynamically remap shortcuts (requires additional permissions)
function remapShortcut(commandName, newKey) {
  // Note: Requires "commands" permission and chrome.runtime.onStartup listener
  // Actual implementation may use chrome.runtime.requestUpdateCheck or similar APIs
}

Clipboard Management (Read/Write Clipboard)

Clipboard operations are a vital way for extensions to interact with users. Modern browsers provide secure clipboard access through the clipboard API, supporting text and image data read/write.

Text clipboard operation example:

// Write to clipboard
async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    console.log('Text copied to clipboard');
  } catch (err) {
    console.error('Copy failed:', err);
    // Fallback: Use document.execCommand (deprecated but supports older browsers)
    const textarea = document.createElement('textarea');
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();
    const success = document.execCommand('copy');
    document.body.removeChild(textarea);
    if (!success) throw new Error('Fallback also failed');
  }
}

// Read from clipboard (requires user gesture)
async function pasteFromClipboard() {
  try {
    const text = await navigator.clipboard.readText();
    console.log('Read from clipboard:', text);
    return text;
  } catch (err) {
    console.error('Read failed:', err);
    // Fallback: Create temporary input field
    return new Promise((resolve) => {
      const input = document.createElement('input');
      input.style.position = 'fixed';
      input.style.opacity = '0';
      document.body.appendChild(input);
      input.focus();
      input.onpaste = (e) => {
        const text = (e.clipboardData || window.clipboardData).getData('text');
        document.body.removeChild(input);
        resolve(text);
      };
      // Timeout handling
      setTimeout(() => {
        document.body.removeChild(input);
        resolve('');
      }, 1000);
    });
  }
}

// Clipboard integration in extension
chrome.commands.onCommand.addListener((command) => {
  if (command === 'copy-selection') {
    // Requires content script to get selected text
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.scripting.executeScript({
        target: { tabId: tabs[0].id },
        func: () => window.getSelection().toString()
      }, (results) => {
        if (results && results[0].result) {
          copyToClipboard(results[0].result);
        }
      });
    });
  }
});

Image clipboard operations require more complex handling:

// Read image from clipboard and insert into page
async function pasteImageToPage() {
  try {
    const items = (await navigator.clipboard.read()).filter(
      item => item.types.includes('image/png')
    );

    if (items.length === 0) {
      throw new Error('No image in clipboard');
    }

    const blob = await items[0].getType('image/png');
    const imageUrl = URL.createObjectURL(blob);

    // Create image element and insert into page
    const img = document.createElement('img');
    img.src = imageUrl;
    document.body.appendChild(img);

    // Optional: Upload to server
    uploadImage(blob);
  } catch (err) {
    console.error('Image paste failed:', err);
  }
}

// Note: Image clipboard API requires HTTPS context and secure origin

Notes and Data Synchronization (Storage API, IndexedDB)

Extension data management requires balancing usability and functionality. The Chrome Storage API is ideal for simple key-value storage, while complex data structures benefit from IndexedDB.

Storage API basic usage:

// Store extension settings
async function saveSettings(settings) {
  await chrome.storage.local.set({
    userPreferences: settings,
    lastUpdated: Date.now()
  });

  // Listen for settings changes (useful for multi-device sync)
  chrome.storage.onChanged.addListener((changes, area) => {
    if (area === 'local' && changes.userPreferences) {
      updateUIWithNewSettings(changes.userPreferences.newValue);
    }
  });
}

// Retrieve stored notes data
async function loadNotes() {
  const result = await chrome.storage.local.get('notes');
  return result.notes || [];
}

// Batch update operation
async function batchUpdateNotes(updates) {
  const currentNotes = await loadNotes();
  const updatedNotes = applyUpdates(currentNotes, updates);
  await chrome.storage.local.set({ notes: updatedNotes });
}

IndexedDB integration example (suitable for large structured data):

// IndexedDB wrapper class
class NotesDatabase {
  constructor() {
    this.dbName = 'ExtensionNotes';
    this.dbVersion = 1;
    this.db = null;
  }

  async open() {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.dbVersion);

      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        if (!db.objectStoreNames.contains('notes')) {
          const store = db.createObjectStore('notes', { keyPath: 'id' });
          store.createIndex('by_timestamp', 'timestamp', { unique: false });
        }
      };

      request.onsuccess = (event) => {
        this.db = event.target.result;
        resolve(this.db);
      };

      request.onerror = (event) => {
        reject('Database open failed: ' + event.target.errorCode);
      };
    });
  }

  async addNote(note) {
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(['notes'], 'readwrite');
      const store = transaction.objectStore('notes');

      const request = store.add({
        ...note,
        id: Date.now().toString(),
        timestamp: new Date().toISOString()
      });

      request.onsuccess = () => resolve();
      request.onerror = (event) => reject(event.target.error);
    });
  }

  // Other CRUD operations...
}

// Usage example
async function saveNoteToIndexedDB(noteContent) {
  const db = await new NotesDatabase().open();
  await db.addNote({
    content: noteContent,
    tags: ['important']
  });

  // Optional: Sync to cloud
  syncNotesToCloud();
}

Multi-device synchronization strategy:

// Cloud-based synchronization scheme
async function syncDataAcrossDevices() {
  // 1. Get local data
  const localData = await loadNotes();

  // 2. Fetch latest cloud data
  const cloudData = await fetchCloudData();

  // 3. Conflict resolution strategy (simple: prioritize last modified)
  const mergedData = mergeData(localData, cloudData);

  // 4. Update local and cloud storage
  await Promise.all([
    chrome.storage.local.set({ notes: mergedData }),
    updateCloudData(mergedData)
  ]);
}

// Incremental synchronization optimization
async function incrementalSync() {
  const lastSyncTime = await getLastSyncTimestamp();
  const changes = await getChangesSince(lastSyncTime);

  if (changes.length > 0) {
    applyChanges(changes);
    await setLastSyncTimestamp(Date.now());
  }
}

Multi-Device Sync and Cross-Browser Compatibility

Achieving multi-device synchronization requires addressing data consistency, conflict resolution, and network reliability. Modern extensions often combine cloud storage services with browser sync APIs.

Firebase-based synchronization example:

// Firebase initialization and data sync
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, onSnapshot, doc, setDoc } from 'firebase/firestore';

// Firebase configuration (obtained from extension background)
const firebaseConfig = {
  apiKey: chrome.runtime.getManifest().firebase.apiKey,
  projectId: chrome.runtime.getManifest().firebase.projectId,
  // Other configuration...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

// Sync notes collection
function setupRealtimeSync(userId) {
  const notesRef = collection(db, `users/${userId}/notes`);

  // Listen for real-time updates
  onSnapshot(notesRef, (snapshot) => {
    snapshot.docChanges().forEach((change) => {
      if (change.type === 'added' || change.type === 'modified') {
        const note = change.doc.data();
        updateLocalNote(note.id, note);
      } else if (change.type === 'removed') {
        removeLocalNote(change.doc.id);
      }
    });
  });
}

// Push local changes to cloud
async function pushNoteToCloud(note) {
  try {
    await setDoc(doc(db, `users/${currentUser.id}/notes`, note.id), note);
  } catch (error) {
    console.error('Sync failed:', error);
    // Implement retry logic
    queueForRetry(note);
  }
}

// Cross-browser compatibility layer
function getCrossBrowserStorage() {
  // Detect browser type
  if (typeof chrome !== 'undefined' && chrome.storage) {
    return {
      get: (keys) => new Promise(resolve => chrome.storage.local.get(keys, resolve)),
      set: (items) => new Promise(resolve => chrome.storage.local.set(items, resolve))
    };
  } else if (typeof browser !== 'undefined' && browser.storage) {
    return browser.storage.local;
  } else {
    // Fallback to localStorage
    return {
      get: (keys) => Promise.resolve(JSON.parse(localStorage.getItem('extensionData') || '{}')),
      set: (items) => Promise.resolve(localStorage.setItem('extensionData', JSON.stringify(items)))
    };
  }
}

Ad Blocking and Privacy Protection

Ad Blocking Rule Matching (Regular Expressions, DOM Scanning)

Modern ad-blocking extensions use sophisticated rule systems combining DOM scanning and regular expressions for efficient detection.

Request Interception and Redirection (webRequest API)

The webRequest API allows extensions to intercept and modify requests between sending and receiving, a core technology for ad blocking and privacy protection.

Basic request interception example:

// Intercept requests matching specific URL patterns
chrome.webRequest.onBeforeRequest.addListener(
  (details) => {
    // Check if request matches ad rules
    if (isAdRequest(details.url)) {
      console.log('Blocked ad request:', details.url);
      return { cancel: true }; // Cancel request
    }
    // Optional: Redirect to local resource
    // return { redirectUrl: 'https://localhost/block.html' };
  },
  { urls: ['<all_urls>'] }, // Monitor all URLs
  ['blocking'] // Requires blocking permission
);

// Complex rule matching function
function isAdRequest(url) {
  // 1. Check known ad domains
  if (knownAdDomains.some(domain => url.includes(domain))) {
    return true;
  }

  // 2. Check URL parameter patterns
  if (adUrlParams.some(param => url.includes(param))) {
    return true;
  }

  // 3. Check path patterns
  if (adPathPatterns.some(pattern => new RegExp(pattern).test(url))) {
    return true;
  }

  return false;
}

// Dynamic rule update system
async function updateBlockingRules() {
  // Fetch latest rules from remote server
  const response = await fetch('https://rules.example.com/latest.json');
  const newRules = await response.json();

  // Update in-memory rule set
  Object.assign(adRules, newRules);

  // Notify content scripts of rule update
  chrome.tabs.query({}, (tabs) => {
    tabs.forEach(tab => {
      chrome.tabs.sendMessage(tab.id, { 
        type: 'RULES_UPDATED',
        rules: newRules
      });
    });
  });
}

Advanced redirection techniques:

// Intelligent redirection based on user settings
chrome.webRequest.onBeforeRequest.addListener(
  (details) => {
    const url = details.url;

    // 1. Check if it's a tracking request
    if (isTrackingRequest(url)) {
      // Redirect to local empty resource
      return { redirectUrl: chrome.runtime.getURL('empty.html') };
    }

    // 2. Check if it's a known ad service
    if (isAdService(url)) {
      // Redirect to ad-blocked page
      return { redirectUrl: chrome.runtime.getURL('ad-blocked.html') };
    }

    // 3. Redirect specific services to alternatives
    if (url.includes('analytics.example.com')) {
      // Redirect to open-source alternative
      return { 
        redirectUrl: 'https://open-analytics.example.com/track?' + 
          new URL(url).search.substring(1)
      };
    }

    return { cancel: false };
  },
  { urls: ['<all_urls>'] },
  ['blocking']
);

// Request header modification example (for privacy protection)
chrome.webRequest.onBeforeSendHeaders.addListener(
  (details) => {
    // Remove or modify headers that may leak identity
    const newHeaders = details.requestHeaders.filter(header => {
      return !['Cookie', 'Referer'].includes(header.name);
    });

    // Add privacy protection header
    newHeaders.push({
      name: 'DNT',
      value: '1'
    });

    return { requestHeaders: newHeaders };
  },
  { urls: ['<all_urls>'] },
  ['blocking', 'requestHeaders']
);

Extensions can manage browser cookies and local storage to help users protect privacy or meet specific functional needs.

Extension Behavior in Privacy Mode

Privacy (incognito) mode imposes special restrictions on extension functionality, requiring developers to understand and design compatible solutions.

Privacy mode detection and adaptation:

// Detect if in privacy mode
function isIncognitoMode() {
  // Note: Direct privacy mode detection is limited
  // This method indirectly detects by attempting restricted API access
  return new Promise(resolve => {
    chrome.cookies.get({ url: 'http://example.com' }, cookie => {
      // In privacy mode, certain cookie operations may fail
      resolve(cookie === null); // Simple example, actual detection is more complex
    });
  });
}

// More reliable privacy mode detection (via runtime API)
chrome.runtime.getPlatformInfo(info => {
  // Certain platform features may differ in privacy mode
  // Note: Not an officially recommended method, just an example
});

// Privacy-safe storage solution
async function getPrivacySafeStorage() {
  // Detect privacy mode
  const incognito = await detectIncognito();

  if (incognito) {
    // Use in-memory storage in privacy mode
    return {
      data: {},
      setItem: (key, value) => { this.data[key] = value; },
      getItem: (key) => this.data[key],
      removeItem: (key) => delete this.data[key]
    };
  } else {
    // Use chrome.storage in normal mode
    return chrome.storage.local;
  }
}

// Best practices for handling sensitive data
async function handleSensitiveData(data) {
  // 1. Do not store in privacy mode
  if (await isIncognitoMode()) {
    processDataInMemory(data);
    return;
  }

  // 2. Use encrypted storage in normal mode
  const encrypted = await encryptData(data);
  await chrome.storage.local.set({ sensitiveData: encrypted });
}

// Privacy mode declaration in manifest
// manifest.json requires incognito permission
/*
{
  "optional_permissions": ["incognito"]
}
*/

User Data Encryption and Secure Storage

Protecting user data is a critical responsibility in extension development. Modern browsers offer secure storage mechanisms, but developers should implement additional encryption layers.

Web Enhancement and Automation In-Depth Tutorial

Web enhancement and automation extensions empower browsers with capabilities beyond native functionality through DOM manipulation, network request interception, and script injection. This section explores the implementation principles and development practices of five core enhancement techniques to help developers build professional-grade web optimization tools.

Dynamic DOM Element Modification (Style Injection, Content Replacement)

DOM manipulation is the foundation of web enhancement, enabling developers to achieve interface beautification, ad blocking, and functionality improvements through precise element control.

Style Injection Techniques

Style injection dynamically creates <style> tags or modifies existing element style attributes to adjust page visuals in real-time:

// Method 1: Create global style tag
function injectGlobalStyles(cssRules) {
  const styleElement = document.createElement('style');
  styleElement.textContent = cssRules;
  document.head.appendChild(styleElement);
}

// Usage example: Inject dark mode styles
injectGlobalStyles(`
  body {
    background-color: #1a1a1a !important;
    color: #e0e0e0 !important;
  }
  a {
    color: #4dabf7 !important;
  }
`);

// Method 2: Precisely control specific element styles
function modifyElementStyle(selector, styles) {
  const elements = document.querySelectorAll(selector);
  elements.forEach(element => {
    Object.assign(element.style, styles);
  });
}

// Usage example: Adjust all image sizes
modifyElementStyle('img', {
  maxWidth: '100%',
  height: 'auto',
  borderRadius: '8px'
});

Content Replacement Strategies

Content replacement involves complex DOM operations, handling text nodes, attribute modifications, and element replacements:

// Text content replacement
function replaceTextContent(selector, newText) {
  const elements = document.querySelectorAll(selector);
  elements.forEach(element => {
    element.textContent = newText;
  });
}

// HTML content replacement (XSS prevention)
function replaceHtmlContent(selector, newHtml) {
  const elements = document.querySelectorAll(selector);
  elements.forEach(element => {
    // Safe handling: Sanitize HTML with DOMPurify
    const cleanHtml = DOMPurify.sanitize(newHtml);
    element.innerHTML = cleanHtml;
  });
}

// Attribute value replacement
function modifyAttributes(selector, attributes) {
  const elements = document.querySelectorAll(selector);
  elements.forEach(element => {
    Object.entries(attributes).forEach(([name, value]) => {
      element.setAttribute(name, value);
    });
  });
}

// Complex content replacement example: Ad blocking
function blockAdElements() {
  // 1. Remove known ad elements
  document.querySelectorAll('iframe[src*="adserver"], div.ad-container').forEach(el => {
    el.remove();
  });

  // 2. Replace placeholder ad text
  replaceTextContent('[class*="ad-placeholder"]', '[Ad Blocked]');

  // 3. Hide ad elements (fallback)
  modifyAttributes('[id*="ad-"]', { style: 'display: none !important' });
}

Dynamic Style Manager

Implement a configurable style management system supporting real-time theme and style rule switching:

class StyleManager {
  constructor() {
    this.styleElement = null;
    this.activeRules = new Set();
  }

  // Initialize style tag
  init() {
    this.element = document.createElement('style');
    document.head.appendChild(this.element);
  }

  // Add style rule
  addRule(ruleName, cssRules) {
    this.activeRules.add({ ruleName, cssRules });
    this.updateStyles();
  }

  // Remove style rule
  removeRule(ruleName) {
    this.activeRules = this.activeRules.filter((rule => rule.ruleName !== ruleName));
    this.updateStyles();
    this.updateStyles();
  }

  // Update page styles
  updateStyles() {
    if (!this.styleElement)) return;

    const styles = this.activeRules
      .map((rule) => rule.cssRules)
      .cssRules)
      .join('\n');

    this.styleElement.textContent = styles;
    return;
  }

  // Toggle theme
  toggleTheme(themeName) {
    this.removeRule('current-theme');
    return this.rules.remove('current-theme');
    if (themeName === 'dark') {
      this.addRule('current-theme', `
        body { background: #121212; color: #ffffff; }
        a { color: #bb86fc; }
      `);
      return this.addRule('current-theme', { cssRules: 'body { background-color: #121212; color: #ffffff; }
        a { color: #bb86fc; }
      });
    });
  } else {
      this.addRule('current-theme', `
        body { background: #ffffff; color: #212121; }
        a { color: #64b5f6; }
      `);
      return this.addRule(this('current-theme', '`
        body { background-color: #ffffff; color: #333; }
        a { color: #64b5f6; }
      }
      `));
    }
  }
}

// Usage example
const styleManager = new StyleManager();
styleManager.init();
styleManager.toggleTheme('dark-mode');

Form Auto-Filling and Submission

Form automation significantly enhances user experience, particularly for login workflows, data entry, and testing scenarios.

Smart Form Detection

Automatically detect form elements on a page and extract structured information:

function detectForms() {
  const forms = document.querySelectorAll('form');
  return Array.from(forms).map((formElement) => {
    const inputs = form.querySelectorAll('input, textarea, select');
    return {
      element: formElement,
      fields: Array.from(inputs).map((inputfield => ({
        element: input,
        }) => ({
          name: input.name || input.id,
          type: input.type,
          required: input.required,
          value: input.value,
        }))
      });
}));
}

// Example usageexample:
const forms = detectForms();
forms.forEach((form => {
  console.log('Found 'Found' form: ', form.element.action);
  console.log(`Found form: ${formElement.action}`);
  form.fields.forEach((field => {
    console.log(`- Field: ${field.name}, Type: ${field.type},`);
  }));
});

Auto-Fill System

Fill forms automatically based on predefined rules or user profiles:

class FormFiller {
  constructor(profiles) {
    this.profiles = profiles; // User-defined fill templates
  }

  // Fill form by matching field names
  fillForm(formElement, profileName) {
    const profile = this.profiles[profileName];
    if (!profile) return false;

    const inputs = formElement.querySelectorAll('input, textarea, select');
    inputs.forEach((input => {
      const fieldName = input.name || input.id;
      if (fieldName && profile[fieldName]) {
        this.setFillValue(input, profile[fieldName]);
      }
    }));

    return true;
  }

  // Set value based on field type
  setFillValue(inputElement, value) {
    switch (inputElement.type) {
      case 'checkbox':
      case 'radio':
        inputElement.checked = !!value;
        break;
      case 'select-one':
      case 'select-multiple':
        this.setSelectValue(inputElement, value);
        break;
      default:
        inputElement.value = value.toString();
    }

    // Trigger change events
    triggerEvent(inputElement, 'input');
    triggerEvent(inputElement, 'change');
  }

  // Handle select elements
  setSelectValue(selectElement, value) {
    if (selectElement.multiple) {
      // Handle multiple selections
      const values = Array.isArray(value) ? value : [value];
      Array.from(selectElement.options).forEach((option => {
        option.selected = values.includes(option.value);
      }));
    } else {
      // Handle single selection
      selectElement.value = value.toString();
    }
  }
}

// Utility function to trigger events
function triggerEvent(element, eventName) {
  const event = new Event(eventName, { bubbles: true });
  element.dispatchEvent(event);
}

// Usage example:
const profiles = {
  'default': {
    'username': 'testuser',
    'password': 'securepassword123',
    'remember': true,
    'country': 'CN'
  }
};

const formFiller = new FormFiller(profiles);
const forms = detectForms();
forms.forEach((form => {
  formFiller.fillForm(form.element, 'default'));
}));

Form Submission Automation

Simulate user clicks on submit buttons or directly invoke form submission methods:

class FormSubmitter {
  // Regular form submission
  submitForm(formElement) {
    // Trigger validation if available
    if (typeof formElement.reportValidity === 'function') {
      if (!formElement.reportValidity()) {
        console.warn('Form validation failed');
        return false;
      }
    }

    // Create and trigger submit event
    const submitEvent = new Event('submit', { cancelable: true });
    if (!formElement.dispatchEvent(submitEvent)) {
      console.warn('Form submission prevented');
      return false;
    }

    // Perform actual submission
    formElement.submit();
    return true;
  }

  // AJAX form submission (for SPA applications)
  async submitFormAjax(formElement) {
    const formData = new FormData(formElement);
    const action = formElement.action;
    const method = formElement.method.toUpperCase();

    try {
      const response = await fetch(action, {
        method,
        body: method !== 'GET' ? formData : undefined,
        headers: method !== 'GET' ? { 'X-Requested-With': 'XMLHttpRequest' } : {}
      });

      if (!response.ok) throw new Error('Network response error');

      // Handle response data
      const data = await response.json();
      console.log('AJAX submission successful:', data);
      return data;
    } catch (error) {
      console.error('AJAX submission failed:', error);
      return null;
    }
  }

  // Smart submission strategy
  smartSubmit(formElement) {
    // Check if it's an AJAX form
    if (formElement.hasAttribute('data-ajax-submit')) {
      return this.submitFormAjax(formElement);
    }

    // Default to traditional submission
    return this.submitForm(formElement);
  }
}

// Usage example:
const formSubmitter = new FormSubmitter();
forms.forEach((form) => {
  formSubmitter.smartSubmit(form.element);
});

Web Page Screenshots and PDF Generation (Chrome API)

Modern browsers provide robust screenshot and PDF generation capabilities, which extensions can use to create professional-grade page capture tools.

Web Page Translation and Language Detection

Web translation extensions provide seamless cross-language browsing by integrating translation APIs and automatic language detection.

Language Detection Algorithm

Implement an efficient and accurate language detection system:

class LanguageDetector {
  constructor() {
    // Common language character profiles
    this.languageProfiles = {
      'en': { // English
        commonWords: ['the', 'and', 'of', 'to', 'in'],
        charRanges: [[0x0041, 0x005A], [0x0061, 0x007A]] // A-Z, a-z
      },
      'zh': { // Chinese
        commonWords: ['的', '是', '在', '和', '了'],
        charRanges: [[0x4E00, 0x9FFF]] // CJK Unified Ideographs
      },
      'ja': { // Japanese
        commonWords: ['の', 'に', 'は', 'を', 'た'],
        charRanges: [[0x3040, 0x309F], [0x30A0, 0x30FF], [0x4E00, 0x9FFF]] // Hiragana, Katakana, Kanji
      },
      'es': { // Spanish
        commonWords: ['el', 'de', 'que', 'y', 'a'],
        charRanges: [[0x0041, 0x005A], [0x0061, 0x007A], [0xD1, 0xF1]] // A-Z, a-z, Ññ
      }
    };
  }

  // Detect text language
  detectLanguage(text) {
    if (!text || text.length < 10) {
      return 'unknown'; // Text too short for accurate detection
    }

    // 1. Analyze character distribution
    const charStats = this.analyzeCharacterDistribution(text);

    // 2. Analyze word frequency
    const wordStats = this.analyzeWordFrequency(text);

    // 3. Calculate language match scores
    const scores = {};
    for (const [lang, profile] of Object.entries(this.languageProfiles)) {
      scores[lang] = this.calculateLanguageScore(charStats, wordStats, profile);
    }

    // 4. Return highest-scoring language
    let maxScore = -1;
    let detectedLang = 'unknown';
    for (const [lang, score] of Object.entries(scores)) {
      if (score > maxScore) {
        maxScore = score;
        detectedLang = lang;
      }
    }

    return maxScore > 0.5 ? detectedLang : 'unknown';
  }

  // Analyze character distribution
  analyzeCharacterDistribution(text) {
    const charCounts = {};
    for (const char of text) {
      const code = char.charCodeAt(0);
      charCounts[code] = (charCounts[code] || 0) + 1;
    }
    return charCounts;
  }

  // Analyze word frequency
  analyzeWordFrequency(text) {
    const words = text.toLowerCase().split(/\s+/);
    const wordCounts = {};
    for (const word of words) {
      // Simple tokenization (actual implementation should use advanced tokenizers)
      if (word.length > 2) { // Ignore short words
        wordCounts[word] = (wordCounts[word] || 0) + 1;
      }
    }
    return wordCounts;
  }

  // Calculate language match score
  calculateLanguageScore(charStats, wordStats, profile) {
    let score = 0;

    // 1. Character distribution match
    let charScore = 0;
    const totalChars = Object.values(charStats).reduce((sum, count) => sum + count, 0);
    for (const [rangeStart, rangeEnd] of profile.charRanges) {
      let rangeCount = 0;
      for (let code = rangeStart; code <= rangeEnd; code++) {
        rangeCount += charStats[code] || 0;
      }
      charScore += rangeCount / totalChars;
    }
    score += charScore * 0.6; // Character distribution weight

    // 2. Common word match
    let wordScore = 0;
    const totalWords = Object.values(wordStats).reduce((sum, count) => sum + count, 0);
    for (const word of profile.commonWords) {
      wordScore += (wordStats[word] || 0) / totalWords;
    }
    score += wordScore * 0.4; // Word frequency weight

    return Math.min(1, score); // Cap score at 1
  }
}

// Usage example:
const detector = new LanguageDetector();
const sampleText = 'This is a test text for demonstrating language detection. 这是一个用于测试语言检测功能的文本。';
const detectedLang = detector.detectLanguage(sampleText);
console.log('Detected language:', detectedLang); // Should output 'zh' or 'en' (depends on algorithm)

Translation API Integration

Integrate with mainstream translation services for real-time translation:

class TranslationService {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.supportedLanguages = {
      'en': 'English',
      'zh': 'Chinese',
      'ja': 'Japanese',
      'es': 'Spanish',
      'fr': 'French',
      'de': 'German'
    };
  }

  // Translate text
  async translateText(text, targetLang, sourceLang = 'auto') {
    if (!text || text.length === 0) {
      return text;
    }

    // 1. Check if translation is necessary (same language)
    if (sourceLang !== 'auto' && sourceLang === targetLang) {
      return text;
    }

    // 2. Call translation API
    try {
      const response = await this.callTranslationAPI(text, targetLang, sourceLang);
      return response.translatedText;
    } catch (error) {
      console.error('Translation failed:', error);
      return `[Translation error: ${error.message}] ${text}`;
    }
  }

  // Call Google Translate API (example)
  async callTranslationAPI(text, targetLang, sourceLang) {
    // Note: Actual implementation requires handling API keys and rate limits
    const apiUrl = `https://translation.googleapis.com/language/translate/v2`;

    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.apiKey}`
      },
      body: JSON.stringify({
        q: text,
        target: targetLang,
        source: sourceLang
      })
    });

    if (!response.ok) {
      throw new Error(`API request failed: ${response.status}`);
    }

    const data = await response.json();
    return {
      translatedText: data.data.translations[0].translatedText,
      detectedSourceLanguage: data.data.translations[0].detectedSourceLanguage
    };
  }

  // Translate entire page
  async translatePage(targetLang) {
    // 1. Detect page language
    const pageText = this.extractPageText();
    const detector = new LanguageDetector();
    const sourceLang = detector.detectLanguage(pageText);

    // 2. Skip if target and source languages are the same
    if (sourceLang === targetLang) {
      return { success: true, message: 'No translation needed' };
    }

    // 3. Translate page elements
    await this.translatePageElements(pageText, targetLang, sourceLang);

    return { success: true, message: `Translated to ${this.supportedLanguages[targetLang]}` };
  }

  // Extract main page text content
  extractPageText() {
    // Exclude non-translatable elements
    const excludedSelectors = [
      'script', 'style', 'noscript', 
      '[class*="no-translate"]', 
      '[id*="no-translate"]'
    ];

    // Get all text nodes
    let pageText = '';
    const walker = document.createTreeWalker(
      document.body,
      NodeFilter.SHOW_TEXT,
      {
        acceptNode: (node) => {
          // Check if node is within excluded elements
          let parent = node.parentNode;
          while (parent) {
            if (excludedSelectors.some(selector => 
              parent.matches(selector) || 
              parent.querySelector(selector)
            )) {
              return NodeFilter.FILTER_REJECT;
            }
            parent = parent.parentNode;
          }
          return NodeFilter.FILTER_TRUE;
        }
      }
    );

    while (walker.nextNode()) {
      const text = walker.currentNode.nodeValue.trim();
      if (text.length > 0) {
        pageText += text + '\n';
      }
    }

    return pageText;
  }

  // Translate page elements
  async translatePageElements(pageText, targetLang, sourceLang) {
    // 1. Identify translatable elements
    const translatableElements = this.identifyTranslatableElements();

    // 2. Batch translate element content
    for (const element of translatableElements) {
      if (element.textContent.trim().length > 0) {
        const translatedText = await this.translateText(
          element.textContent,
          targetLang,
          sourceLang,
          sourceLang
        );

        // Preserve original text for restoration
        if (!element.dataset.originalText) {
          element.dataset.originalText = element.textContent;
        }

        // Set translated text
        element.textContent = translatedText;

        // Add translation marker
        element.classList.add('translated');
      }
    }

    return;
  }

  // Identify translatable page elements
  identifyTranslatableElements() {
    // Common text-containing HTML elements
    const textElementSelectors = [
      'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
      'li', 'span', 'div', 'a', 'span', 'li', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
      'td', 'th',
      'caption', 'legend', 'label'
    ];

    // Exclude non-translatable elements
    const excludedSelectors = [
      'script', 'style', 'noscript',
      '[class*="no-translate"]',
      '[id*="no-translate"]'
    ];

    // Get all translatable elements
    let elements = [];
    textElementSelectors.forEach((selector => {
      elements = elements.concat([...document.querySelectorAll(selector)]);
    }));


    // Filter out excluded elements
    elements = elements.filter((element => {
      let parent = element.parentNode;
      while (parent) {
        if (excludedSelectors.some((selector => 
          parent.matches(selector) || 
          parent.querySelector(selector)
        )) {
          return false;
        }
        parent = parent.parentNode;
      }
      return true;
    }));

    return elements;
  }
}

// Usage example:
const translator = new TranslationService('YOUR_API_KEY');
translator.translatePage('zh').then((result => {
  console.log(result.message);
}));

// UI integration example:
document.getElementById('translate-btn').addEventListener('click', async () => {
  const targetLang = document.getElementById('language-select').value;
  const result = await translator.translatePage(targetLang);
  if (result.success) {
    showToast(result.message);
  }
});

Translation Cache System

Implement a local cache to reduce API calls:

class TranslationCache {
  constructor() {
    this.cache = new Map();
    this.maxSize = 1000; // Maximum cache entries
    this.loadFromStorage();
  }

  // Load cache from storage
  async loadFromStorage() {
    try {
      const cachedData = await chrome.storage.local.get('translationCache');
      if (cachedData.translationCache) {
        this.cache = new Map(JSON.parse(cachedData.translationCache));
      }
    } catch (error) {
      console.error('Load cache failed:', error);
    }
  }

  // Save cache to storage
  async saveToStorage() {
    try {
      await chrome.storage.local.set({
        translationCache: JSON.stringify([...this.cache])
      });
    } catch (error) {
      console.error('Save cache failed:', error);
    }
  }

  // Get cached translation
  getTranslation(text, targetLang, sourceLang) {
    const cacheKey = this.generateCacheKey(text, targetLang, sourceLang);
    return this.cache.get(cacheKey);
  }

  // Set cached translation
  setTranslation(text, targetLang, sourceLang, translatedText) {
    // Check if cache is full
    if (this.cache.size >= this.maxSize) {
      // Remove oldest entry (simplified; should use LRU algorithm)
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }

    const cacheKey = this.generateCacheKey(text, targetLang, sourceLang);
    this.cache.set(cacheKey, translatedText);
    this.saveToStorage();
  }

  // Generate cache key
  generateCacheKey(text, targetLang, sourceLang) {
    // Simple implementation: use text as key (may not suit long texts)
    // Actual implementation should use hashing for long texts
    return `${sourceLang || 'auto'}->${targetLang}:${text.substring(0, 100)}`;
  }

  // Clear cache
  clearCache() {
    this.cache.clear();
    chrome.storage.local.remove('translationCache');
  }
}

// Integrate cache with translation service
class CachedTranslationService extends TranslationService {
  constructor(apiKey) {
    super(apiKey);
    this.cache = new TranslationCache();
  }

  async translateText(text, targetLang, sourceLang = 'auto') {
    // 1. Check cache
    const cachedTranslation = this.cache.getTranslation(text, targetLang, sourceLang);
    if (cachedTranslation) {
      return cachedTranslation;
    }

    // 2. Call parent translation method
    const result = await super.translateText(text, targetLang, sourceLang);

    // 3. Cache result
    if (result) {
      this.cache.setTranslation(text, targetLang, sourceLang, result);
    }

    return result;
  }
}

// Usage example:
const cachedTranslator = new CachedTranslationService('YOUR_API_KEY');
cachedTranslator.translatePage('zh').then(result => {
  console.log(result.message);
});

Web Page Performance Monitoring and Optimization

Web performance extensions monitor key metrics in real-time and provide optimization suggestions to enhance browsing experiences.

Share your love