ajax-hooker is a powerful AJAX interception library that seamlessly integrates with native XMLHttpRequest and Fetch APIs. It simplifies the interception process by normalizing both into a coherent lifecycle, allowing for efficient request mutation and response handling. With support for streaming and chunk-level interception, it is ideal for browser-side request governance and debugging.
ajax-hooker is a powerful library designed for seamless AJAX interception on the browser side. It provides deep integration by intercepting both XMLHttpRequest and fetch requests, allowing for a unified lifecycle that simplifies interception logic across both request types.
ajax-hooker stands out in terms of native XHR and Fetch coverage, offering a unified hook lifecycle and streaming chunk interception. Other solutions like Axios interceptors or handwritten monkey patches may serve specific use cases but lack the comprehensive coverage and functionality provided by ajax-hooker.
To get started, ajax-hooker can be installed via npm. The library supports both XMLHttpRequest and fetch, enabling a single point of governance for all AJAX requests:
import AjaxInterceptor from 'ajax-hooker';
const interceptor = AjaxInterceptor.getInstance();
interceptor.inject();
interceptor.hook((request) => {
request.headers.set('Authorization', 'Bearer token');
request.response = async (response) => {
console.log('Status:', response.status);
console.log('Data:', response.json || response.response);
};
return request;
});
The API offers several key functions:
getInstance(): Retrieve the singleton instance for consistent usage across different parts of your application.inject(type?): Start the interception process for either XHR, fetch, or both types of requests.uninject(type?): Stop the interception and restore the native behavior of XMLHttpRequest and fetch.hook(fn, type?): Add a hook function to modify the request or capture the response.unhook(fn?, type?): Remove a specific hook or clear all hooks.The library also provides significant flexibility with a clearly defined request and response object, making it easy to work with and understand the data flow.
For complete examples showcasing usage scenarios and more advanced features, visit the Examples Index.
ajax-hooker simplifies and enriches AJAX request management in web applications, making it an essential tool for developers looking to achieve deeper control over their network requests.
No comments yet.
Sign in to be the first to comment.