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.
Related:
How do I access the HTTP request header fields via JavaScript?
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.
Related:
How do I access the HTTP request header fields via JavaScript?
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.If we’re talking about Request headers, you can create your own headers when doing XmlHttpRequests.
It’s not possible to read the current headers. You could make another request to the same URL and read its headers, but there is no guarantee that the headers are exactly equal to the current.
Use the following JavaScript code to get all the HTTP headers by performing a
get
request: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.
Unfortunately, there isn’t an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been repeatedly asked, too, because some people would like to get the actual response headers of the original page request without issuing another one.
For AJAX Requests:
If an HTTP request is made over AJAX, it is possible to get the response headers with the
getAllResponseHeaders()
method. It’s part of the XMLHttpRequest API. To see how this can be applied, check out thefetchSimilarHeaders()
function below. Note that this is a work-around to the problem that won’t be reliable for some applications.The API was specified in the following candidate recommendation for XMLHttpRequest: XMLHttpRequest – W3C Candidate Recommendation 3 August 2010
Specifically, the
getAllResponseHeaders()
method was specified in the following section: w3.org:XMLHttpRequest
: thegetallresponseheaders()
methodThe MDN documentation is good, too: developer.mozilla.org:
XMLHttpRequest
.This will not give you information about the original page request’s HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.
Getting header values from the Initial Page Request:
This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the current page (i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren’t readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.
The following are a few suggestions for getting around that problem.
1. Requests on Resources which are largely static
If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you’re currently on and assume that they’re they are the same values which were part of the page’s HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.
This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can’t fully guarantee that they are the same. It’s going to depend on your specific application and whether you know that the value you need is something that won’t be changing from one request to the next.
2. Make Inferences
There are some BOM properties (Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g.
navigator.userAgent
is set to the value of the HTTPUser-Agent
header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.3. Stash them
If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. 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 send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.
This is an old question. Not sure when support became more broad, but
getAllResponseHeaders()
andgetResponseHeader()
appear to now be fairly standard: http://www.w3schools.com/xml/dom_http.aspYou can’t access the http headers, but some of the information provided in them is available in the DOM. For example, if you want to see the http referer (sic), use document.referrer. There may be others like this for other http headers. Try googling the specific thing you want, like “http referer javascript”.
I know this should be obvious, but I kept searching for stuff like “http headers javascript” when all I really wanted was the referer, and didn’t get any useful results. I don’t know how I didn’t realize I could make a more specific query.
Using mootools, you can use this.xhr.getAllResponseHeaders()
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 functionparseHttpHeaders
:Like many people I’ve been digging the net with no real answer 🙁
I’ve nevertheless find out a bypass that could help others. In my case I fully control my web server. In fact it is part of my application (see end reference). It is easy for me to add a script to my http response. I modified my httpd server to inject a small script within every html pages. I only push a extra ‘js script’ line right after my header construction, that set an existing variable from my document within my browser [I choose location], but any other option is possible. While my server is written in nodejs, I’ve no doubt that the same technique can be use from PHP or others.
Now every html pages loaded from my server, have this script executed by the browser at reception. I can then easily check from JavaScript if the variable exist or not. In my usecase I need to know if I should use JSON or JSON-P profile to avoid CORS issue, but the same technique can be used for other purposes [ie: choose in between development/production server, get from server a REST/API key, etc ….]
On the browser you just need to check variable directly from JavaScript as in my example, where I use it to select my Json/JQuery profile
For who ever would like to check my code:
https://www.npmjs.org/package/gpsdtracking
As has already been mentioned, if you control the server side then it should be possible to send the initial request headers back to the client in the initial response.
In Express, for example, the following works:
app.get('/somepage', (req, res) => {
res.render('somepage.hbs', {headers: req.headers});
})
The headers are then available within the template, so could be hidden visually but included in the markup and read by clientside javascript.
A solution with Service Workers
Service workers are able to access network information, which includes headers. The good part is that it works on any kind of request, not just XMLHttpRequest.
How it works:
fetch
the request with therespondWith
function.postMessage
function.Working example:
Service workers are a bit complicated to understand, so I’ve built a small library that does all this. It is available on github: https://github.com/gmetais/sw-get-headers.
Limitations:
I think the question went in the wrong way,
If you want to take the Request header from JQuery/JavaScript the answer is simply No. The other solutions is create a aspx page or jsp page then we can easily access the request header.
Take all the request in aspx page and put into a session/cookies then you can access the cookies in JavaScript page..
I’ve just tested, and this works for me using Chrome Version 28.0.1500.95.
I was needing to download a file and read the file name. The file name is in the header so I did the following:
Output:
To get the headers as an object which is handier (improvement of Raja’s answer):
While it’s not possible in general to read arbitrary HTTP response headers of the top-level HTML navigation, if you control the server (or middleboxes on the way) and want to expose some info to JavaScript that can’t be exposed easily in any other way than via a header:
You may use
Server-Timing
header to expose arbitrary key-value data, and it will be readable by JavaScript.(*in supported browsers: Firefox 61, Chrome 65, Edge 79; no Safari yet as of 2021.02; no IE)
Example of how Wikipedia uses this header to expose info about cache hit/miss:
Code example (need to account for lack of browser support in Safari and IE):
This logs
cache = hit-front
in supported browsers.Notes:
Server-Timing
headers support alsodur
(header) field, readable asduration
on JS side, but it’s optional and defaults to0
in JS if not passedPerformanceObserver
API instead. See the blog post for details.This is my script to get all the response headers:
Having as a result the response headers.
This is a comparison test using Hurl.it:
Allain Lalonde’s link made my day.
Just adding some simple working html code here.
Works with any reasonable browser since ages plus IE9+ and Presto-Opera 12.
Note: You get headers of a second request, the result may differ from the initial request.
Another way
is the more modern
fetch()
APIhttps://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
Per caniuse.com it’s supported by Firefox 40, Chrome 42, Edge 14, Safari 11
Working example code: