A lightweight utility for intercepting and mocking fetch
and XMLHttpRequest
responses using wildcard URL matching.
Just load this script into the webpage on which you want to mock the API response. You can inject the script into the dom with the javascript like this
const script = document.createElement('script');
script.src = 'interceptor.js';
script.onload = () => console.log('Interceptor loaded');
document.head.appendChild(script);
NOTE : If you are using this in a browser extension, this code must be executed in your webpage context (Content script running in MAIN
world) otherwise it won't work
Interceptor.fetch.mock('https://*.example.com/api/*', async (req, res) => {
const data = await res.json();
data.injected = true;
return new Response(JSON.stringify(data), res);
});
Interceptor.xhr.mock('https://xyz.example.com/api/*', async (req, res) => {
const obj = await res.json();
obj.hijacked = true;
return obj; // will be JSON-stringified under the hood
});
// Later, if you need to undo all mocking:
Interceptor.fetch.restore();
Interceptor.xhr.restore();
Supports *
to match URLs, e.g.:
'https://api.example.com/*'
'https://*.example.com/data/*'
.url
β full URL.method
β HTTP method (GET, POST, etc.).body
β request body (for XHR only)
.json()
β parses original JSON body.text()
β returns original response as string
For fetch
, this is the actual Response
object. For xhr
, it's a wrapper.
Feature | Behavior |
---|---|
Methods Supported | All (GET , POST , PATCH , etc.) |
Wildcard * matching |
β Yes (pattern β RegExp) |
Response override type | Response , JSON object, or string |
.restore() supported |
β Restores native behavior |
All status codes are intercepted unless filtered:
if (!res.ok) return res; // Optional: skip on 404/500 etc.
These return no body by design. Ensure your handler doesnβt assume one.
Extend the facade if you need res.blob()
or res.arrayBuffer()
for XHR.
Thatβs your streamlined, mock-it-anywhere kit. Let me know if you want a bundlable version or automatic test snapshot hooks!
This gist comprise of lot's of energy, brainstroming, coding, testing and time. If this project has helped you in any way, please consider giving it a β to show your support and help it grow!