How do I access a page\'s HTTP response headers via JavaScript?
Related to this question, which was modified to ask about accessing two specific HTTP headers.
<
For those looking for a way to parse all HTTP headers into an object that can be accessed as a dictionary headers["content-type"]
, I've created a function parseHttpHeaders
:
function parseHttpHeaders(httpHeaders) {
return httpHeaders.split("\n")
.map(x=>x.split(/: */,2))
.filter(x=>x[0])
.reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
}
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = parseHttpHeaders(req.getAllResponseHeaders());
// Now we can do: headers["content-type"]