Skip to content

Instantly share code, notes, and snippets.

@muthuishere
Created May 31, 2024 06:42
Show Gist options
  • Save muthuishere/832f6791148d48d5e1499ce29ef4f69a to your computer and use it in GitHub Desktop.
Save muthuishere/832f6791148d48d5e1499ce29ef4f69a to your computer and use it in GitHub Desktop.
Intercept AJax , websocket requests from browser
(function() {
// Save the original WebSocket constructor
const OriginalWebSocket = window.WebSocket;
// Define a new constructor that modifies the WebSocket behavior
window.WebSocket = function(url, protocols) {
const ws = new OriginalWebSocket(url, protocols);
// Store the original send method
const originalSend = ws.send;
// Override the send method to intercept messages
ws.send = function(data) {
console.log("WebSocket Sending:", data);
originalSend.call(this, data);
};
// Set up an event listener to intercept incoming messages
ws.addEventListener('message', function(event) {
console.log("WebSocket Receiving:", event.data);
});
return ws;
};
// Save a reference to the original XMLHttpRequest send and open functions
const originalXHROpen = XMLHttpRequest.prototype.open;
const originalXHRSend = XMLHttpRequest.prototype.send;
// Override the open method
XMLHttpRequest.prototype.open = function(method, url) {
this._url = url;
return originalXHROpen.apply(this, arguments);
};
// Override the send method
XMLHttpRequest.prototype.send = function(data) {
console.log('XHR Request URL:', this._url);
console.log('XHR Request Body:', data);
this.addEventListener('load', () => {
console.log('XHR Response URL:', this._url);
console.log('XHR Response Status:', this.status);
console.log('XHR Response Body:', this.responseText);
});
return originalXHRSend.apply(this, arguments);
};
// Save the original fetch function
const originalFetch = window.fetch;
// Override the fetch function
window.fetch = function(url, options) {
console.log('Fetch Request URL:', url);
console.log('Fetch Request Options:', options);
return originalFetch(url, options).then(response => {
const clonedResponse = response.clone();
console.log('Fetch Response Status:', clonedResponse.status);
clonedResponse.text().then(text => {
console.log('Fetch Response Body:', text);
});
return response;
});
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment