Build a Chrome Extension to Mock API Calls Without Memory Bloat
This guide explains how to create a lightweight Chrome extension that intercepts fetch and AJAX requests, lets you define mock rules without installing heavy clients, and dramatically reduces memory usage during front‑end development.
Effect Demonstration
The extension intercepts fetch and XMLHttpRequest calls, matches them against user‑defined rules, and returns custom JSON data when a rule matches.
Core Principle: Hijacking Browser Network Methods
Before the page loads, the extension replaces the native fetch and XMLHttpRequest with wrappers that first check whether the request should be mocked. If a rule matches, a fake Response with the mock JSON is returned; otherwise the original request proceeds.
// Save original method
const originalFetch = window.fetch;
// Replace with our wrapper
window.fetch = function(url) {
// Check if URL matches a mock rule
if (url.includes('/api/user')) {
console.log('Intercepted! Returning mock data');
return Promise.resolve({
json: () => ({ name: 'Mock User' })
});
}
// Fallback to real fetch
return originalFetch(url);
};Key Points
Save the original method; otherwise real requests cannot be sent.
Inject the script at document_start so early requests are captured.
Rewrite both fetch and XMLHttpRequest (methods open and send).
Project Structure
quick-mock/
├── manifest.json # Extension configuration
├── popup.html # UI shown when the extension icon is clicked
├── popup.css
├── popup.js # UI logic, stores mock rules in chrome.storage
├── content.js # Content script, reads rules, communicates via postMessage
└── injected.js # Runs in page context, actually rewrites fetch/xhrQuick Start
Clone the repository: https://github.com/Teernage/quick-mock
Open chrome://extensions/ in Chrome.
Enable "Developer mode".
Click "Load unpacked" and select the quick-mock folder.
The extension is installed and ready to use.
Deep Dive: How the Scripts Work Together
Popup (UI Layer)
popup.htmlprovides inputs for adding or removing mock rules. popup.js stores the rules in chrome.storage.local.
Content Script (Bridge Layer)
content.jsruns in an isolated sandbox, can access Chrome APIs, reads stored rules, and communicates with injected.js via window.postMessage. It cannot modify page JavaScript directly.
Injected Script (Intercept Layer)
injected.jsruns in the page's JavaScript environment, allowing it to overwrite window.fetch and XMLHttpRequest. It receives mock‑decision messages from content.js and returns either mock data or forwards the request.
Why Two Scripts?
Content scripts have Chrome API access but are sandboxed; injected scripts can modify page code but lack Chrome API access. postMessage bridges the gap, enabling secure communication without exposing Chrome APIs to the page.
Important Manifest Settings
run_at: "document_start"– ensures the script runs before any page JavaScript executes. web_accessible_resources – makes injected.js loadable by the page.
When to Use This Extension
Front‑end development when back‑end APIs are not ready.
Debugging live bugs by temporarily altering responses.
Demoing features without a real server.
Automated testing that requires stable mock data.
Exploring API contracts before they are finalized.
Conclusion
The extension demonstrates a practical client‑side API mocking approach: hijack network methods early, keep mock logic separate from the page, and use Chrome storage plus postMessage for configuration. This reduces memory consumption compared to heavyweight mock clients and provides a smooth developer experience.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
