I'm using code from stackoverflow[1] to replace XMLHTTPRequest. I'm using the stateful ajax code [2], which injects its own implementation of the onreadystatechange handler. There's a page window object that is used to collect the response, and I believe I should be able to access the data with an evaluate call [2].
Instead, a Type Error is thrown, and I'm not quite sure how to debug further. My JS is not the best, and I feel like I'm making a simple mistake. I am declaring most of these functions using a page object pattern, and separate modules. The complete code is in the gist below. Any thoughts appreciated!
Here's where I call the XHRwrapper and attempt to get data from the window object:
this.getResponse = function() {
casper.then(function() {
casper.evaluate(XHRRequest.replaceXHR);
});
casper.then(function() {
casper.evaluate(XHRequest.replaceXHR);
function getMyHttpResponse() {
return this.evaluate(function() {
return window.myHttpResponse;
});
}
casper.waitFor(getMyHttpResponse, function then() {
var data = JSON.parse(getMyHttpResponse());
console.log(data);
});
});
Here's the definition for the XHR Wrapper function. It's long so I will cut some of it out. The gist below has the full code.
function XHRequest() {
this.replaceXHR = function() {
function replaceXHR() {
(function(window, debug) {
function args(a) {
var s = "";
for (var i = 0; i < a.length; i++) {
s += "\t\n[" + i + "] =>>" + a[i];
}
return s;
}
var _XMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
this.xhr = new _XMLHttpRequest();
};
// proxy ALL methods/properties
var methods = [
"open",
"abort",
"setRequestHeader",
"send",
"addEventListener",
"removeEventListener",
"getAllResponseHeaders",
"dispatchEvent",
"overrideMimeType"
];
// if argument 'debug' print arguments, if method open apply arguments to this.xhr
methods.forEach(function(method) {
window.XMLHttpRequest.prototype[method] = function() {
if (debug) {
console.log("ARGUMENTS", method, args(arguments));
}
if (method == "open") {
this._url = arguments[1];
}
return this.xhr[method].apply(this.xhr, arguments);
}
});
[..snip]
otherscalars.forEach(function(scalar){
Object.defineProperty(window.XMLHTTPRequest.prototype, scalar, {
get: function(){
return this.xhr[scalar];
},
set: function(obj){
this.xhr[scalar] = obj;
}
});
});
// call window and set second arg to 'false' vs debug
})(window, debug);
}
}
}