intercepting XHR requests, javascript react - javascript

I have been trying to override the methods in order to intercept the xhr requests but seems like everything I do it only prinds '1' for this.readyState.
Does anyone have any idea why?
addInterceptorsToXHRRequests() {
const originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
const originalStateChangeHandler = this.onreadystatechange;
this.onreadystatechange = function() {
console.log(' ---> ',this.readyState);
if (originalStateChangeHandler instanceof Function) {
originalStateChangeHandler.apply(this, arguments);
console.log('Ready state: ' + this.readyState);
}
};
return originalOpen.apply(this, arguments);
};
}
I am calling this function from index.js, at the end of componentDidMount life cycle method. (pretty big project)

This happens because you bind a function on XMLHttpRequest.prototype.open .
open returns only state 1.
So, you need to attach the onreadystatechange function to the full xhr.
Example
// you probably want the original XMLHttpRequest here...
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
console.log(xhr.readyState);
};

Related

Intercept XHR and change request headers and url before send in JavaScript

I want to intercept all XHR requests being sent, and change their URL and headers before the request gets sent.
Found this similar question but there are no answers there.
I tried hooking XMLHttpRequest.prototype.open, But it only gives me access to the response:
(function () {
var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
console.log(arguments); // prints method ("GET"), URL
console.log(this); // prints response, responseText, responseURL, status, statusText, and onXXX handlers
origOpen.apply(this, arguments);
};
})();
Also tried hooking XMLHttpRequest.prototype.setRequestHeader, but it only gives me access to each header value being set, one by one, and I can't associate it to the URL of the request:
(function () {
var origSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
XMLHttpRequest.prototype.setRequestHeader = function (header, value) {
console.log("header", header);
console.log("value", value);
origSetRequestHeader.apply(this, arguments);
};
})();
I managed to hook XMLHttpRequest.prototype.send to set a custom header, but since I want to change an existing header key, it appends my new value instead of replacing the existing one. Other people encountered the same problem: 1, 2:
(function () {
var origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function () {
arguments[1] = myNewUrl; // arguments[1] holds the URL
this.setRequestHeader('existingHeaderKey', newHeaderValue)
origSend.apply(this, arguments);
};
})();
How can I accomplish this?
The XMLHttpRequest(xhr) interface exposes a very few things. So there is limitation on what you can intercept.
However, we can wrap the xhr objects in Proxy and collect data until send is called. And before sending the request we modify the data at one spot.
const OriginalXHR = XMLHttpRequest;
// wrap the XMLHttpRequest
XMLHttpRequest = function() {
return new Proxy(new OriginalXHR(), {
open(method, url, async, username = null, password = null) {
lg('open');
// collect URL and HTTP method
this.modMethod = method;
this.modUrl = url;
this.open(...arguments);
},
setRequestHeader(name, value) {
lg('set header');
if (!this.modReqHeaders) {
this.modReqHeaders = {};
}
// collect headers
this.modReqHeaders[name] = value;
// do NOT set headers here. Hold back!
// this.setRequestHeader(name, value);
},
send(body = null) {
lg('processing request...');
// do the final processing
// ...
// don't forget to set headers
for (const [name, value] of Object.entries(this.modReqHeaders)) {
this.setRequestHeader(name, value);
}
lg('sending request =>' +
'\n\t\tmethod: \t' + this.modMethod +
'\n\t\turl:\t\t' + this.modUrl +
'\n\t\theaders:\t' + JSON.stringify(this.modReqHeaders));
this.send(body);
},
get(xhr, key) {
if (!key in xhr) return undefined;
let value = xhr[key];
if (typeof value === "function") {
// if wrapped, use the function in proxy
value = this[key] || value;
return (...args) => value.apply(xhr, args);
} else {
//return properties
return value;
}
},
set(xhr, key, value) {
if (key in xhr) {
xhr[key] = value;
}
return value;
}
});
}
console.warn('XMLHttpRequest has been patched!\n XMLHttpRequest: ', XMLHttpRequest);
let url = 'https://baconipsum.com/api/?type=all-meat&sentences=1&start-with-lorem=1';
function getData() {
console.log('fetching lorem ipsum');
let xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerText = this.response[0];
}
};
xhr.open("GET", url, true);
xhr.setRequestHeader('Referer', 'www.google.com');
xhr.setRequestHeader('Accept-Encoding', 'x-compress; x-zip')
xhr.setRequestHeader('Accept-Language', 'de-US,en;q=0.5');
xhr.send();
}
//fancy logging, looks good in dark mode
function lg(msg) {
console.log('%c\t Proxy: ' + msg, 'background: #222; color: #bada55');
}
#demo {
min-height: 100px;
background-color: wheat;
}
<button onclick="getData()">Get data</button>
<div id="demo"></div>
<p>Note: look in the Developer Console for debug logs</p>
You can wrap remaining xhr methods or attributes in the proxy handler as per your requirement.
This may not be as good as service workers. But service workers have following drawbacks:
A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is non-blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and Web Storage can't be used inside a service worker.
Service workers only run over HTTPS, for security reasons. Having modified network requests, wide open to man in the middle attacks would be really bad. In Firefox, Service Worker APIs are also hidden and cannot be used when the user is in private browsing mode.ref

Tracking completion of a specific XMLHTTPRequest

Would it be possible to determine when a particular XMLHttpRequest has completed using pure JavaScript?. Say I know the URL of a resource that will be requested with an XMLHttpRequest, for example: http://www.mywebsite.com/test.json, could I track the completion of this request using JavaScript?
This is the code I have so far:
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", function() {
if(realXHR.readyState==4 && realXHR.status==200){
console.log('request was made');
}
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
however, this tracks every single HTTP request made on a website and isn't very useful. I want to pinpoint the exact request and determine when it has completed. How could this be done?
You need to "hijack" (override, practically) the open() method instead of the constructor.
XMLHttpRequest.prototype.open = (function(realOpen) {
return function(method, url) {
if (url === 'http://www.mywebsite.com/test.json') {
this.addEventListener('readystatechange', function() {
// ...do what you have to do
});
}
realOpen.apply(this, arguments);
};
})(XMLHttpRequest.prototype.open);

Getting AJAX to Work With JavaScript

Just to point out, I know how to do this with jQuery and AngularJS. The project I am currently working on requires me to use plain JavaScript.
I'm trying to get AJAX to work with just plain JavaScript. I am using Java/Spring for backend programming. Here is my JavaScript code:
/** AJAX Function */
ajaxFunction = function(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.status == 200) {
var JSONResponse = JSON.parse(xhttp.responseText);
return JSONResponse;
}
}
xhttp.open('GET', url, true);
xhttp.send();
}
/** Call Function */
searchResults = function() {
var test = ajaxFunction('http://123.456.78.90:8080/my/working/url');
console.log(test);
}
/** When the page loads. */
window.onload = function() {
searchResults();
}
It's worth noting that when I go directly to the URL in my browser's address bar (example, if I go directly to the link http://123.456.78.90:8080/my/working/url), I get a JSON response in the browser.
When I hover over xhttp.status, the status is saying 0, not 200, even though I know that the link I am calling works. Is this something that you have to set in Spring's controllers? I didn't think that was the case because when I inspect this JS URL call in the Network tab, it states that the status is 200.
All in all, this response is coming back as undefined. I can't figure out why. What am I doing wrong?
An XMLHttpRequest is made asynchronously meaning that the request is fired off and the rest of the code continues to run. A callback is provided and when the asynchronous operation completes the callback function is called. The onreadystatechange function is called upon completion of an AJAX request. In your example the ajaxFunction will return immediately after the xhttp.send() line executes, so your var test won't have the JSON in it as I assume you expect.
In order to do something when an AJAX request completes you need to use a callback function. If you wanted to log the result to the console as above you could try something like the following:
var xhttp;
var handler = function() {
if(xhttp.readyState === XMLHttpRequest.DONE) {
if (xhttp.status == 200) {
var JSONResponse = JSON.parse(xhttp.responseText);
console.log(JSONResponse);
}
}
};
/** AJAX Function */
var ajaxFunction = function(url) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = handler;
xhttp.open('GET', url, true);
xhttp.send();
};
/** Call Function */
var searchResults = function() {
ajaxFunction('http://123.456.78.90:8080/my/working/url');
};
/** When the page loads. */
window.onload = function() {
searchResults();
};
If you want to learn more about how XMLHttpRequest works then MDN is a much better teacher than I am :)

Maximum call stack size exceeded error when using ajax multiple times

I am writing a piece of code that should catch all ajax responses on a page. I managed to do this by overriding XMLHttpRequest.onreadystatechange for javascript direct ajax or by using ajaxComplete() for jQuery ajax.
My problem happens when I try to use ajax multiple times without creating a new XMLHttpObject, for example:
var xhr = new XMLHttpRequest();
xhr.open("GET", '/echo/json/', true);
xhr.send();
xhr.open("GET", '/echo/json/', true);
xhr.send()
This makes my code go haywire and I get the maximum stack error.
Here is my testing code on JSFiddle: http://jsfiddle.net/zxCfW/
var s_ajaxListener = {};
s_ajaxListener.tmpSend = XMLHttpRequest.prototype.send;
s_ajaxListener.callback = function () {
console.log('additional state change');
};
XMLHttpRequest.prototype.send = function() {
s_ajaxListener.tmpOnReadyStateChange = this.onreadystatechange;
this.onreadystatechange = function() {
if (s_ajaxListener.tmpOnReadyStateChange){
s_ajaxListener.tmpOnReadyStateChange.apply(this, arguments);
}
if(this.readyState == 4 && this.status == 200) {
s_ajaxListener.callback();
this.onreadystatechange = s_ajaxListener.tmpOnReadyStateChange;
}
};
s_ajaxListener.tmpSend.apply(this, arguments);
};
$(document).ajaxComplete(s_ajaxListener.callback);
I believe this happens because the ajax calls are asynchronous so the original onreadystatechange doesn't reset to its default value, but I don't know how to solve this.

PubSub.js multiple subscriptions, or a different way to handle awaiting on multiple callbacks

I am trying to figure out the best way to handle this scenario. Basically I want the flow to work like this:
1.) Get configuration data from server (async)
2.) Run doStuff() after configuration data is received (async)
3.) Run postResults after doStuff() completes
Currently I seem to have this flow working using PubSub.js, however I am trying to figure out how I can provide the results from config data (#1) to postResults (#3). While I seem to have the flow working with PubSub, I'm not sure how to access the configuration (#1) callback data from postResults (#3)
Here is a code summary:
PubSub.subscribe('config', doStuff());
fetchConfigurations();
function fetchConfigurations () {
var req = new XMLHttpRequest();
var url = CONFIGURATION_SERVER_URL;
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
var configObject = eval('(' + req.responseText + ')');
PubSub.publish('config', configObject);
} else {
console.log("Requesting config from server: " + url);
}
}
req.open("GET", url, true);
req.send(null);
}
function doStuff() {
PubSub.subscribe('results', postResults);
var results = {};
// do some async work...
results['test1'] = "some message";
results['test2'] = "another message";
PubSub.publish('doStuff', results);
}
function postResults (doStuffId, doStuffData) {
var req = new XMLHttpRequest();
var url = TEST_RESULTS_URL; // I want to get this from the configObject is get in fetchConfigurations
req.open("POST",url,true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send(doStuffData['test1'] + doStuffData['test2']);
}
Using promise seemed like the a better fit for this problem instead of pub/sub, here is the implementation I ended up using:
https://github.com/hemanshubhojak/PromiseJS

Categories