How to Build a Chrome Mock Extension with Manifest V3 for API Interception

This article walks through the design and implementation of a Chrome extension that mocks API responses by intercepting network requests using Manifest V3, covering architecture differences, core configuration, request‑blocking techniques, script injection, project structure, rule creation, whitelist management, and future enhancements.

DeWu Technology
DeWu Technology
DeWu Technology
How to Build a Chrome Mock Extension with Manifest V3 for API Interception

Introduction

During development, missing backend APIs or problematic environments often require developers to mock responses. To address this, a browser extension‑based mock tool was created, focusing on API request interception and data simulation to improve development efficiency.

Browser Extension Overview

Browser extensions (or add‑ons) are lightweight modules that run inside the browser process, providing deep integration with browser capabilities via standardized APIs such as WebExtensions. Unlike web apps or native apps, extensions are deployed without complex installation and can control tabs, intercept network requests, and access local storage.

Manifest V3 Architecture

Manifest V3 restructures the extension architecture, introducing a static declaration model and a service‑worker‑based background script. This redesign impacts background execution, network request control, and the security model.

Core Configuration Differences

// V2 persistent background page configuration
"background": {
  "scripts": ["background.js"],
  "persistent": true
}

// V3 service worker configuration
"background": {
  "service_worker": "background.js",
  "type": "module"
}

Mock Extension Implementation

Request Interception Core Principle

Since Manifest V3 removes the blocking capability of webRequest, the extension uses declarativeNetRequest for rule‑based filtering and rewrites native APIs (e.g., fetch and XMLHttpRequest) in the page context to return mock data.

const originalFetch = window.fetch;
window.fetch = async function(url, options = {}) {
  // 1. Send intercepted request to content script
  const response = await sendMockRequest(url, options);

  // 2. If a matching mock rule exists, return mock data
  if (response.shouldMock) {
    return new Response(JSON.stringify(response.mockData), {
      status: response.status,
      headers: response.headers
    });
  }

  // 3. Otherwise perform the original request
  return originalFetch.call(this, url, options);
};

Script Injection

The extension injects scripts using a multi‑strategy approach (inline, external, and simple injection) to bypass Content‑Security‑Policy restrictions.

async function injectScript() {
  // Strategy 1: Inline script injection
  try {
    await injectInlineScript();
    if (await checkScriptActivation()) return;
  } catch (e) {
    console.warn('Inline injection failed:', e);
  }

  // Strategy 2: External script injection
  try {
    await injectExternalScript();
    if (await checkScriptActivation()) return;
  } catch (e) {
    console.warn('External injection failed:', e);
  }

  // Strategy 3: Simple injection
  await attemptSimpleInjection();
}

Overall Architecture and Flow

Project Structure

chrome-mock/
├── build-script/        # Rollup build scripts
├── static/              # Static assets (e.g., mockjs)
├── debug/               # Local debugging pages
├── manifest.json        # Extension manifest
├── background.js        # Core logic
├── content.js           # Script injection & messaging
├── injected.js          # Request interception implementation
├── options.html         # Management UI
├── options.js
├── options.css
├── popup.html
├── popup.js
├── popup.css
└── icons/               # Icon resources

Key Features

Project structure design

Feature overview (request interception, script injection, whitelist, logging)

Overall workflow diagram

Creating Mock Rules

Mock rules can be added via two main methods:

Quick operation popup: import rules from an external API management platform.

Management page: manually create rules for specific URLs, supporting JSON‑Schema‑based mock data generation.

Page Whitelist Management

To avoid performance degradation, a whitelist controls on which pages the mock functionality is active. Users can enable the whitelist, add domain patterns (e.g., *.example.com, http://localhost:3000), and toggle global mode.

# Supported formats
- http://localhost:3000      # Full URL
- *.example.com               # Wildcard domain
- dev.company.com             # Specific domain
- http://dev.company.com      # URL with protocol

Request Logging

The extension records detailed information for each mocked request, aiding debugging and analysis.

Summary and Future Outlook

The development process deepened understanding of browser extension capabilities and Manifest V3. Future work includes expanding mock handling for complex business scenarios, adding UI to mock any request from history, and integrating AI to generate mock data based on user prompts.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontend developmentChrome Extensionbrowser extensionAPI mockingManifest V3request-interception
DeWu Technology
Written by

DeWu Technology

A platform for sharing and discussing tech knowledge, guiding you toward the cloud of technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.