Lesson 03-Development of Basic Browser Extension Functions

Browser extensions provide developers with powerful capabilities to customize browser functionality, from simple page enhancements to complex cross-platform tools. Extensions have become a vital part of the modern web ecosystem. This tutorial systematically explains browser extension development techniques, covering the complete process from configuration to core feature implementation, helping developers master the key skills for building efficient and secure extensions.

Manifest File Configuration

The Manifest file is the core configuration of a browser extension, defining its basic information, permission requirements, and functional components. With the evolution of browser technologies, Manifest V3 has become the standard for modern extension development, introducing stricter security models and performance optimization mechanisms.

Key Differences Between Manifest V2 and V3

Manifest V3 introduces several key changes compared to V2. Google replaced persistent background scripts with Service Workers, enabling finer-grained permission control and resource management. In V3, permissions are split into permissions for API access and host_permissions for network request permissions. Additionally, V3 restricts dynamic injection of content scripts, requiring all injection rules to be pre-declared in the manifest, enhancing security but reducing flexibility.

Basic Field Configuration

Basic fields define the extension’s identity and metadata:

  • name: Specifies the display name, ideally concise and descriptive.
  • version: Follows semantic versioning (MAJOR.MINOR.PATCH).
  • description: A brief 1-2 sentence summary of the extension’s functionality.
  • icons: Specifies paths to icon files in standard sizes (16×16, 48×48, 128×128).
{
  "name": "Page Enhancement Tool",
  "version": "1.0.0",
  "description": "Provides page content analysis and optimization features",
  "icons": {
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  }
}

Permission Declarations

Permissions are critical to the extension’s security model. The permissions field declares required API permissions, such as tabs, storage, or bookmarks. The host_permissions field manages network request permissions, supporting wildcard patterns for specific domains. Adhering to the principle of least privilege minimizes security risks.

{
  "permissions": ["storage", "tabs"],
  "host_permissions": [
    "https://*.example.com/*",
    "http://localhost:*"
  ]
}

Script and Resource Declarations

These define the extension’s functional components:

  • background: Configures the background service. In V3, service_worker replaces persistent scripts.
  • content_scripts: Specifies scripts to inject into pages and their matching rules.
  • web_accessible_resources: Lists resources accessible to web pages, requiring careful configuration to prevent XSS vulnerabilities.
{
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "content_scripts": [
    {
      "matches": ["https://*.example.com/*"],
      "js": ["content.js"],
      "css": ["styles.css"]
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["inject.js"],
      "matches": ["<all_urls>"]
    }
  ]
}

Browser Compatibility Configuration

To ensure cross-browser compatibility, the browser_specific_settings field allows tailored configurations for different browser engines, such as gecko (Firefox) or chromium (Chrome/Edge), enabling conditional feature loading or fallbacks.

{
  "browser_specific_settings": {
    "gecko": {
      "id": "extension@example.com",
      "strict_min_version": "78.0"
    },
    "chrome": {
      "minimum_chrome_version": "88"
    }
  }
}

Background Script Development

Background scripts serve as the central nervous system of an extension, handling global event listening, state management, and component coordination. In Manifest V3, background scripts are implemented as Service Workers, offering more efficient memory usage and stricter lifecycle management.

Role of Background Scripts

Background scripts handle:

  • Event Listening: Respond to browser events like tab updates or extension installation.
  • State Management: Maintain persistent state across sessions.
  • Cross-Component Communication: Coordinate between content scripts, popup, and other components.

Unlike V2, V3 background scripts follow the Service Worker lifecycle, terminating when idle to save resources.

Event Listening

Key events include:

  • runtime.onInstalled: Triggered on first install or update, ideal for initialization tasks.
  • tabs.onUpdated: Monitors tab state changes, useful for page access tracking or conditional content injection.
// background.js
chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === 'install') {
    console.log('Extension installed for the first time');
    chrome.storage.local.set({ isFirstRun: true });
  } else if (details.reason === 'update') {
    console.log('Extension updated to version:', chrome.runtime.getManifest().version);
  }
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete' && tab.url.includes('example.com')) {
    console.log('Target page loaded:', tab.url);
    // Prepare for page analysis or content injection
  }
});
JavaScript

Long-Running Task Management

V3’s Service Worker lifecycle poses challenges for long-running tasks, as scripts may terminate when idle. Solutions include:

  • Using chrome.alarms for scheduled tasks.
  • Persisting task state with chrome.storage for continuation after termination.
  • Breaking complex tasks into event-driven subtasks.
// Schedule periodic tasks with alarms
chrome.runtime.onInstalled.addListener(() => {
  chrome.alarms.create('dataSync', { periodInMinutes: 60 });
});

chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === 'dataSync') {
    syncDataWithServer();
  }
});

async function syncDataWithServer() {
  const data = await chrome.storage.local.get('pendingChanges');
  if (data.pendingChanges) {
    await fetch('https://api.example.com/sync', {
      method: 'POST',
      body: JSON.stringify(data.pendingChanges)
    });
    await chrome.storage.local.remove('pendingChanges');
  }
}
JavaScript

Communication with Content Scripts

The Message Passing API enables communication. Messages can be one-way (no response expected) or request-response based. Structured message formats and error handling are recommended.

// background.js: Send message to content script
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
  chrome.tabs.sendMessage(tabs[0].id, {
    type: 'ANALYZE_PAGE',
    payload: { criteria: 'performance' }
  }, (response) => {
    if (chrome.runtime.lastError) {
      console.error('Message sending failed:', chrome.runtime.lastError);
    } else {
      console.log('Received response from content script:', response);
    }
  });
});

// content.js: Receive message
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'ANALYZE_PAGE') {
    const analysisResult = performPageAnalysis(message.payload);
    sendResponse({ success: true, data: analysisResult });
  }
  return true; // Keep message channel open for async responses
});
JavaScript

Background Task Optimization

Balancing energy efficiency and performance is crucial. Use chrome.idle to detect user activity and execute non-critical tasks during idle periods. Implement a task priority queue to prioritize high-priority operations, such as user-triggered requests.

// Task scheduling based on user activity
chrome.idle.onStateChanged.addListener((newState) => {
  if (newState === 'idle') {
    processLowPriorityTasks();
  } else if (newState === 'active') {
    prioritizeUserRequests();
  }
});

// Task priority management example
const taskQueue = {
  high: [],
  medium: [],
  low: [],

  addTask(task, priority = 'medium') {
    this[priority].push(task);
    this.processNext();
  },

  processNext() {
    if (this.high.length > 0) {
      this.executeTask(this.high.shift());
    } else if (this.medium.length > 0) {
      this.executeTask(this.medium.shift());
    } else if (this.low.length > 0) {
      this.executeTask(this.low.shift());
    }
  },

  executeTask(task) {
    task().finally(() => {
      this.processNext();
    });
  }
};
JavaScript

Content Script Development

Content scripts act as a bridge between extensions and web content, executing JavaScript in the context of specific pages to perform DOM manipulation, data extraction, and page enhancements.

Scope and Execution Timing

The scope of content scripts is controlled by the matches field, supporting patterns for protocols, domains, paths, and wildcards. The run_at field determines injection timing (document_start, document_end, or document_idle), with document_end as the default, executing after DOM loading.

DOM Manipulation and Event Listening

Content scripts share the page’s DOM but operate in an isolated global scope, allowing direct use of standard DOM APIs. Event listeners should be managed to prevent memory leaks by removing unneeded handlers.

// Content script example: Enhance page interaction
function enhancePage() {
  // Create floating button
  const floatBtn = document.createElement('button');
  floatBtn.textContent = 'Analyze';
  floatBtn.style.position = 'fixed';
  floatBtn.style.bottom = '20px';
  floatBtn.style.right = '20px';
  document.body.appendChild(floatBtn);

  // Add click event listener
  floatBtn.addEventListener('click', () => {
    const analysisResult = analyzePageContent();
    showAnalysisOverlay(analysisResult);
  });

  // Listen for scroll events (optimized for performance)
  let scrollHandler = throttle(() => {
    updateFloatingPosition();
  }, 100);

  window.addEventListener('scroll', scrollHandler);

  // Cleanup function
  return () => {
    window.removeEventListener('scroll', scrollHandler);
    floatBtn.remove();
  };
}

// Throttle function implementation
function throttle(func, limit) {
  let lastFunc;
  let lastRan;
  return function() {
    const context = this;
    const args = arguments;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(function() {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  }
}
JavaScript

Interaction with Page Scripts

Interaction with page scripts uses window.postMessage for cross-scope communication, which is safer than directly accessing page variables. Both sides should agree on message formats and include validation.

// content.js: Communicate with page script
// Send message to page script
window.postMessage({
  type: 'EXTENSION_MESSAGE',
  payload: { action: 'getData', id: 'user-profile' }
}, '*');

// Receive messages from page script
window.addEventListener('message', (event) => {
  // Optional: Validate message source
  // if (event.source !== window) return;

  if (event.data && event.data.type === 'PAGE_MESSAGE') {
    handlePageMessage(event.data.payload);
  }
});

// Corresponding page script implementation
window.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'EXTENSION_MESSAGE') {
    if (event.data.payload.action === 'getData') {
      const data = collectRequiredData(event.data.payload.id);
      window.postMessage({
        type: 'PAGE_MESSAGE',
        payload: { requestId: event.data.payload.id, data: data }
      }, '*');
    }
  }
});
JavaScript

Cross-Origin Request Limitations

Due to the same-origin policy, content scripts cannot directly make cross-origin requests. Solutions include:

  • Forwarding requests to the background script (which has broader permissions) via chrome.runtime.sendMessage.
  • Using page scripts as proxies for indirect cross-origin access.
// Proxy cross-origin requests via background script
function fetchCrossDomainData(url) {
  return new Promise((resolve, reject) => {
    chrome.runtime.sendMessage({
      type: 'PROXY_REQUEST',
      payload: { url: url }
    }, (response) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError);
      } else {
        resolve(response.data);
      }
    });
  });
}

// background.js: Handle proxy requests
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'PROXY_REQUEST') {
    fetch(message.payload.url)
      .then(response => response.json())
      .then(data => sendResponse({ data: data }))
      .catch(error => sendResponse({ error: error.message }));
    return true; // Keep message channel open for async responses
  }
});
JavaScript

Isolation and Security

Content scripts share the page’s DOM but have isolated global and JavaScript execution environments. To prevent XSS attacks, avoid using innerHTML for untrusted content; use textContent or libraries like DOMPurify for safe processing.

// Safe DOM manipulation example
function safeInsertContent(container, htmlContent) {
  // Unsafe approach (prone to XSS)
  // container.innerHTML = htmlContent;

  // Safe approach
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = htmlContent;

  // Sanitize with DOMPurify
  const cleanHTML = DOMPurify.sanitize(tempDiv.innerHTML);

  // Safe insertion
  container.innerHTML = cleanHTML;

  // Alternatively, use text-only insertion
  // container.textContent = plainTextContent;
}
JavaScript

The popup page is the user interaction entry point for an extension, providing a concise control panel and status display. Good popup design follows minimalism, ensuring fast loading and intuitive operation while maintaining tight integration with other components.

Structure and Styling

Popup design should prioritize user experience. Use Flexbox or Grid for responsive layouts to ensure usability across screen sizes. Styling should align with Material Design or custom themes for visual consistency.

<!-- popup.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Extension Control Panel</title>
  <link rel="stylesheet" href="popup.css">
</head>
<body>
  <div class="container">
    <header>
      <h1>Page Analysis Tool</h1>
      <div class="status-indicator"></div>
    </header>

    <main>
      <section class="control-group">
        <button id="analyze-btn">Analyze Current Page</button>
        <button id="export-btn">Export Results</button>
      </section>

      <section class="results-panel">
        <h2>Recent Analyses</h2>
        <ul id="results-list"></ul>
      </section>
    </main>

    <footer>
      <p>Version: <span id="version"></span></p>
    </footer>
  </div>
  <script src="popup.js"></script>
</body>
</html>
HTML
/* popup.css */
.container {
  width: 300px;
  padding: 16px;
  font-family: 'Segoe UI', sans-serif;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #ccc;
}

.status-indicator.active {
  background-color: #4caf50;
}

.control-group {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

button {
  flex: 1;
  padding: 8px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #1976d2;
}

.results-panel {
  max-height: 200px;
  overflow-y: auto;
}

#results-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

#results-list li {
  padding: 8px;
  border-bottom: 1px solid #eee;
}
CSS

Communication with Background Scripts

Popup scripts communicate with background scripts via the chrome.runtime API, using sendMessage for requests and handling responses via callbacks or Promises. Implement request timeouts and error handling for better user experience.

// popup.js
document.addEventListener('DOMContentLoaded', () => {
  // Display extension version
  const manifestVersion = chrome.runtime.getManifest().version;
  document.getElementById('version').textContent = manifestVersion;

  // Update status indicator
  updateStatusIndicator();

  // Handle analyze button click
  document.getElementById('analyze-btn').addEventListener('click', () => {
    analyzeCurrentPage();
  });

  // Handle export button click
  document.getElementById('export-btn').addEventListener('click', () => {
    exportAnalysisResults();
  });
});

async function updateStatusIndicator() {
  try {
    const { isActive } = await chrome.runtime.sendMessage({
      type: 'GET_STATUS'
    });
    document.querySelector('.status-indicator').className = 
      `status-indicator ${isActive ? 'active' : ''}`;
  } catch (error) {
    console.error('Status check failed:', error);
  }
}

function analyzeCurrentPage() {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.runtime.sendMessage({
      type: 'ANALYZE_PAGE',
      payload: { tabId: tabs[0].id }
    }, (response) => {
      if (chrome.runtime.lastError) {
        showError('Analysis request failed');
        return;
      }

      if (response.success) {
        showResults(response.data);
      } else {
        showError(response.error || 'Error during analysis');
      }
    });
  });
}

// Other UI interaction functions...
JavaScript

User Input Handling and State Management

Handle user input with data validation and error feedback. Use debouncing for frequently triggered events (e.g., input fields) to avoid performance issues. State management can use a simple front-end state machine or lightweight libraries.

// User input handling example
const searchInput = document.getElementById('search-input');
let searchTimeout;

searchInput.addEventListener('input', (event) => {
  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => {
    const query = event.target.value.trim();
    if (query.length > 2) {
      performSearch(query);
    }
  }, 300); // 300ms debounce delay
});

function performSearch(query) {
  // Show loading state
  setLoading(true);

  // Execute search (using chrome.runtime communication)
  chrome.runtime.sendMessage({
    type: 'SEARCH_CONTENT',
    payload: { query: query }
  }, (response) => {
    setLoading(false);

    if (chrome.runtime.lastError) {
      showError('Search request failed');
      return;
    }

    displaySearchResults(response.results || []);
  });
}

function setLoading(isLoading) {
  document.getElementById('loading-indicator').style.display = 
    isLoading ? 'block' : 'none';
}
JavaScript

Key to popup performance is maintaining lightweight design and fast response:

  • Reduce DOM node count and avoid complex CSS selectors.
  • Use hardware-accelerated animations.
  • Implement lazy loading for non-critical resources.
// Lightweight design examples
// 1. Dynamic loading of heavy components
function loadHeavyComponent() {
  if (needsHeavyComponent) {
    import('./heavy-component.js').then(module => {
      module.init();
    });
  }
}

// 2. Image lazy loading
const lazyImages = document.querySelectorAll('img[data-src]');
const imageObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src;
      imageObserver.unobserve(img);
    }
  });
});

lazyImages.forEach(img => imageObserver.observe(img));

// 3. Minimize reflows
function updateResultsList(items) {
  const list = document.getElementById('results-list');
  // Use document fragment to reduce reflows
  const fragment = document.createDocumentFragment();

  items.forEach(item => {
    const li = document.createElement('li');
    li.textContent = item.title;
    fragment.appendChild(li);
  });

  // Update DOM in one go
  list.innerHTML = '';
  list.appendChild(fragment);
}
JavaScript

Ensure compatibility across browsers and screen sizes:

  • Use feature detection instead of browser sniffing.
  • Provide fallbacks for critical features.
  • Implement responsive design for usability on various devices.
// Compatibility adaptation examples
// 1. Feature detection
if ('storage' in chrome && 'local' in chrome.storage) {
  // Use chrome.storage API
  chrome.storage.local.get('settings', (data) => {
    applySettings(data.settings);
  });
} else {
  // Fallback: Use localStorage
  const settings = JSON.parse(localStorage.getItem('settings') || '{}');
  applySettings(settings);
}

// 2. Responsive layout adjustments
function adjustLayout() {
  const width = window.innerWidth;
  const container = document.querySelector('.container');

  if (width < 350) {
    container.style.flexDirection = 'column';
    document.querySelector('.control-group').style.flexDirection = 'column';
  } else {
    container.style.flexDirection = 'row';
    document.querySelector('.control-group').style.flexDirection = 'row';
  }
}

window.addEventListener('resize', throttle(adjustLayout, 100));
adjustLayout(); // Initial adjustment
JavaScript

By systematically learning and applying these techniques, developers can build feature-rich, high-performance browser extensions with excellent user experiences. From carefully designed manifest files to efficient component collaboration, every aspect significantly impacts the final product’s quality. Staying updated with browser platform changes and evolving best practices will help developers remain competitive in extension development.

Share your love