Reputation: 4212
I'm logging xhr request using this code:
(function(open) {
XMLHttpRequest.prototype.open = function(method, url, async) {
if (..something..)
{
...
open.call(this, method, url, async);
...
}
};
})(XMLHttpRequest.prototype.open);
So now I would like to get the response headers eg console.log(getAllResponseHeaders())
I tried implementing it everywhere in the code but I get nothing out of it, meaning nothing is logged. Where or how do I get the response headers?
Upvotes: 1
Views: 488
Reputation: 66334
Remember that the headers only exist once they've arrived, not before. This means you have to use an event listener to catch them. By state 4
they definately exist.
(function(open, headers) {
var headhandle = function () {
if (this.readyState === 4) console.log(headers.call(this));
};
XMLHttpRequest.prototype.open = function(method, url, async) {
this.addEventListener('readystatechange', headhandle);
open.call(this, method, url, async);
};
}(XMLHttpRequest.prototype.open, XMLHttpRequest.prototype.getAllResponseHeaders));
var x = new XMLHttpRequest();
x.open();
x.send();
/*
Date: Tue, 31 Dec 2013 13:43:42 GMT
Content-Encoding: gzip
Vary: *
Last-Modified: Tue, 31 Dec 2013 13:43:43 GMT
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8
Cache-Control: public, max-age=60
Content-Length: 14317
Expires: Tue, 31 Dec 2013 13:44:43 GMT
*/
Tested with readyState === 3
and it does not give a result so you'll definitely need to wait for 4
.
Upvotes: 1