Accessing the web page's HTTP Headers in JavaScript
Solution 1
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 the fetchSimilarHeaders()
function below. Note that this is a work-around to the problem that won't be reliable for some applications.
myXMLHttpRequest.getAllResponseHeaders();
-
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()
method -
The 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.
function fetchSimilarHeaders (callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
//
// The following headers may often be similar
// to those of the original page request...
//
if (callback && typeof callback === 'function') {
callback(request.getAllResponseHeaders());
}
}
};
//
// Re-request the same page (document.location)
// We hope to get the same or similar response headers to those which
// came with the current page, but we have no guarantee.
// Since we are only after the headers, a HEAD request may be sufficient.
//
request.open('HEAD', document.location, true);
request.send(null);
}
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 HTTP User-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.
Solution 2
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:
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
Solution 3
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.
Solution 4
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:
- Add a service worker on your website.
- Watch every request that's being sent.
- Make the service worker
fetch
the request with therespondWith
function. - When the response arrives, read the headers.
- Send the headers from the service worker to the page with the
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:
- the website needs to be on HTTPS
- the browser needs to support the Service Workers API
- the same-domain/cross-domain policies are in action, just like on XMLHttpRequest
Solution 5
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.
Comments
-
linkleonard over 2 years
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? -
user121196 almost 15 yearsyou will not be able to modify request header in mozilla for security reasons. mxr.mozilla.org/mozilla1.8.0/source/extensions/xmlextras/base/…
-
asgeo1 about 13 yearsgetAllResponseHeaders() and getResponseHeader() are methods of the the XMLHttpRequest object. I.e. for ajax requests. You can't use those methods to view headers of the initial page - which is what I think the original question was really asking.
-
mykhal almost 13 yearsSaeed, maybe not best for the question author.. I guess it's because it does not access the headers of loaded resource, but makes a new request.. obviously he knows the best, what the best answer is, and made it himself
-
XP1 almost 13 yearsYou must call open() before using the setRequestHeader() method. developer.mozilla.org/en/…
-
kamaci almost 13 yearsHow Google detect it as like I explained here: stackoverflow.com/questions/7191242/…
-
thesmart over 12 yearsI would consider flagging this so that a moderator can mark correctly. Answers the problem, as stated.
-
BlueRaja - Danny Pflughoeft over 12 yearsRE update: ajax requests were a standard part of web development way back in 2008 as well -_-
-
scottrudy over 12 yearsDepending on what header you are after you may want to use the 'HEAD' verb.
-
Myrne Stol about 11 yearsBOM stands for "Browser Object Model", for those wondering. See stackoverflow.com/questions/2213594/… for some background.
-
Olivier Lalonde about 11 yearsI believe cookies headers are omitted.
-
Muhammad Umer almost 11 yearscan you change response header to make browser act in certain way
-
linkleonard almost 11 yearsMaking a new request will only work if the response values you need are guaranteed to be identical from one request to the next. It will depend on your application, so your mileage with an approach like this will vary.
-
claymation over 9 yearsThis hack might work in some scenarios, but it won't work at all if the page containing the script was generated in response to a POST request, and it doesn't help if you're trying to determine whether the server encountered an error (HTTP 5XX) while processing the original request.
-
skibulk over 9 years3) you could stash them in the http cookie header, too. Then you wouldn't need to change the document markup.
-
BlueRaja - Danny Pflughoeft over 9 yearsThere's also
GetResponseHeader('headerName')
if you're only interested in the value of a single header, which I think is the more common use-case. -
Huluvu424242 about 9 yearsThere is a simple way to access the response header elements such as the link element: use document example here: gist.github.com/FunThomas424242/…
-
Jan almost 9 yearsThis answer is horribly wrong. The correct answer is "it's not possible". Or to fit this answer "It's not possible, but here's a hack to attempt to simulate it which may or may not work at all for you".
-
Timo Tijhof over 8 yearsAccess, in the original question, is about getting headers, not setting headers.
-
intotecho over 8 yearsIf your page is rendered using html templates and you control the server code, you can stash the variables into a hidden div that javascript could read into a variable. <div id='myvar' class='hide'>{{ myvar}}</div>
-
MST almost 8 yearsThis approach still requires that you control the server for your JS. No matter how you communicate that info, your code has suddenly been made uncacheable. Why not just make an API for that specific request to avoid corrupting the request for the original asset?
-
dstelow about 6 yearsI've seen people asking for clarification on this and related questions...*why* can't the browser access the current page headers? Is there some browser spec somewhere that says "no", and maybe explains reasoning?
-
Quentin over 5 yearsThe question is asking about reading the response headers. It mentions the request headers only in the context of the possibly related question.
-
Quentin over 5 yearsThe question is asking about response headers, not request headers.
-
Kumar almost 4 years@Huluvu424242's URL throws 404
-
Huluvu424242 almost 4 years@Kumar - thanks for the hint. I have changed my user for deployments. So the link is now: gist.github.com/Huluvu424242/…
-
sproketboy over 3 yearsJust add to this. You can do this now with the fetch() function - supported in chrome, edge and firefox. stevemiller.dev/2019/…
-
FooBar over 3 yearsExactly what I thought of
-
mesqueeb about 3 yearsThis always gives me "access has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." How can I know if the headers allow iframe or not?
-
Ray Foss almost 3 yearsTwo major downsides... WKWebView does not support it on safari 14, the latest. The other issue is there is a bright blue button on Chrome Incognito that also disables Service Workers as most people use them to Store things... not to do critical work. I'm switching to just workers for now... but I seem to be missing headers 9v1li.csb.app
-
Ray Foss almost 3 years@MST in my case I have full control of the proxy's but the files are entirely statically deployed. Nginx makes changing headers trivial.
-
Ray Foss almost 3 yearsThat's odd... I wasn't missing headers in the Service Worker. I guess that may have been because I was in a similar origin. I just had to add another header on the server
res.set('Access-Control-Expose-Headers', 'page-size')
stackoverflow.com/a/45608476/370238