views:

16003

answers:

6

How do I access the HTTP response headers via JavaScript?

Related to this question, which was modified to ask about specifically accessing browser information.

+7  A: 

You don't. Unfortunately, they aren't available.

There are some BOM properties which the browser determines by looking at the headers, but there isn't an over-arching HTTP Headers object that will contain all of the headers.

You can access any header you like on the server-side, and pass values to the client with the page, just as you might with any other datum. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to expose every header, but you could certainly do it for the specific value you need.

keparo
A: 

Another way to send header information to JavaScript would be through cookies. The server can extract whatever data it needs from the request headers and send them back inside a Set-Cookie response header — and cookies can be read in JavaScript. As keparo says, though, it's best to do this for just one or two headers, rather than for all of them.

savetheclocktower
+1  A: 

How do I access the HTTP request header fields via JavaScript?

If we're talking about Request headers, you can create your own headers when doing XmlHttpRequests.

var request = new XMLHttpRequest();
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.open("GET", path, true);
request.send(null);
Leo
you will not be able to modify request header in mozilla for security reasons. http://mxr.mozilla.org/mozilla1.8.0/source/extensions/xmlextras/base/src/nsXMLHttpRequest.cpp#1637
+6  A: 

Using XmlHttpRequest you can pull up the current page and then examine the http headers of the response.

Best case is to just do a HEAD request and then examine the headers.

For some examples of doing this have a look at http://www.jibbering.com/2002/4/httprequest.html

Just my 2 cents.

Allain Lalonde
+1  A: 

Using mootools, you can use this.xhr.getAllResponseHeaders()

Nice, I'll have to examine their code.
Allain Lalonde
A: 

window.location.href

Will