@elliotdong/ajax-interceptor
v0.1.2
Published
🪝 A lib for hook ajax, support XMLHttpRequest and Fetch
Downloads
10
Maintainers
Readme
ajax-interceptor
is a library to intercept XMLHttpRequest
and Fetch
. We can use it to change request header, method, even destination. It has the below props:
- 🍃 No Inject. It doesn't change any business code, we can provide external script to intercept request.
Usage
You can see the examples from examples
Install
- CDN Import
This will import a global object - interceptor.<script src="https://unpkg.com/@elliotdong/ajax-interceptor@latest/dist/index.umd.cjs"></script>
- NPM Install
npm install @elliotdong/ajax-interceptor // or yarn add @elliotdong/ajax-interceptor // or pnpm install @elliotdong/ajax-interceptor
API
Start Intercept
// CDN import
interceptor.intercept();
// npm install
import { intercept } from '@elliotdong/ajax-interceptor';
intercept()
Stop Intercept
// CDN import
interceptor.unIntercept();
// npm install
import { unIntercept } from '@elliotdong/ajax-interceptor';
unIntercept();
Use BeforeRequest Interceptor
import { addBeforeRequestInterceptor, defineRequestInit } from '@elliotdong/ajax-interceptor';
addBeforeRequestInterceptor(async (requestInit: {
method?: string, // default: GET
url?: string,
body?: XMLHttpRequestBodyInit | null | Document,
credentials?: "include" | "omit" | "same-origin",
headers?: Record<string, string>;
}) => {
console.log({requestInit});
if(requestInit.method === 'get') {
// if you want to change request, use `defineRequestInit`
return defineRequestInit({
method?: string,
url?: string,
body?: XMLHttpRequestBodyInit | null | Document,
credentials?: RequestCredentials,
headers?: Record<string, string>;
})
}
// or not, return void
})
Use AfterResponse Interceptor
import { addAfterResponseInterceptor, defineResponse } from '@elliotdong/ajax-interceptor';
addAfterResponseInterceptor(async (response: {
headers?: Record<string, string>;
status?: number;
statusText?: string;
response?: Blob;
}, requestInit) => {
console.log({response});
// if you want to change request, use `defineResponse`
return defineResponse({
method?: string,
url?: string,
body?: XMLHttpRequestBodyInit | null | Document,
credentials?: RequestCredentials,
headers?: Record<string, string>;
})
})
Use ReceiveError Interceptor
import { addReceiveErrorInterceptor, defineResponse } from '@elliotdong/ajax-interceptor';
addReceiveErrorInterceptor(async (error: {
type: 'error' | 'timeout' | 'abort' | 'fetch',
cause?: Error
}, requestInit) => {
console.log({response});
if(requestInit.url.startWith('www.baidu.com')) {
// if you want to change err to response, use `defineResponse`
return defineResponse({
method?: string,
url?: string,
body?: XMLHttpRequestBodyInit | null | Document,
credentials?: RequestCredentials,
headers?: Record<string, string>;
})
}
})
TODO
test