- Accessing the web page’s HTTP Headers in JavaScript
- 18 Answers 18
- For AJAX Requests:
- Getting header values from the Initial Page Request:
- 1. Requests on Resources which are largely static
- 2. Make Inferences
- 3. Stash them
- Headers
- Constructor
- Instance methods
- Examples
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
Accessing the web page’s HTTP Headers in 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.
While you can’t ready any headers of HTML response in JS, you can read Server-Timing header, and you can pass arbitrary key-value data through it. See my answer.
I know this does not answer the question, but could help someone nonetheless. In some situations, where you control the page content and have access to the header data on a server, you could add hidden elements with the desired information.
18 Answers 18
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);
Saeed, 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
Making 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.
This 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.
This 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».
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 : the getallresponseheaders() 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.
Headers
The Headers interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request’s headers.
A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence.
For security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names.
A Headers object also has an associated guard, which takes a value of immutable , request , request-no-cors , response , or none . This affects whether the set() , delete() , and append() methods will mutate the header. For more information see Guard.
You can retrieve a Headers object via the Request.headers and Response.headers properties, and create a new Headers object using the Headers() constructor.
An object implementing Headers can directly be used in a for. of structure, instead of entries() : for (const p of myHeaders) is equivalent to for (const p of myHeaders.entries()) .
Note: you can find out more about the available headers by reading our HTTP headers reference.
Constructor
Creates a new Headers object.
Instance methods
Appends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist.
Deletes a header from a Headers object.
Returns an iterator allowing to go through all key/value pairs contained in this object.
Executes a provided function once for each key/value pair in this Headers object.
Returns a String sequence of all the values of a header within a Headers object with a given name.
Returns an array containing the values of all Set-Cookie headers associated with a response.
Returns a boolean stating whether a Headers object contains a certain header.
Returns an iterator allowing you to go through all keys of the key/value pairs contained in this object.
Sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist.
Returns an iterator allowing you to go through all values of the key/value pairs contained in this object.
Note: To be clear, the difference between Headers.set() and Headers.append() is that if the specified header does already exist and does accept multiple values, Headers.set() will overwrite the existing value with the new one, whereas Headers.append() will append the new value onto the end of the set of values. See their dedicated pages for example code.
Note: All of the Headers methods will throw a TypeError if you try to pass in a reference to a name that isn’t a valid HTTP Header name. The mutation operations will throw a TypeError if the header has an immutable Guard. In any other failure case they fail silently.
Note: When Header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicate header names are combined.
Examples
In the following snippet, we create a new header using the Headers() constructor, add a new header to it using append() , then return that header value using get() :
const myHeaders = new Headers(); myHeaders.append("Content-Type", "text/xml"); myHeaders.get("Content-Type"); // should return 'text/xml'
The same can be achieved by passing an array of arrays or an object literal to the constructor:
let myHeaders = new Headers( "Content-Type": "text/xml", >); // or, using an array of arrays: myHeaders = new Headers([["Content-Type", "text/xml"]]); myHeaders.get("Content-Type"); // should return 'text/xml'
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 26, 2023 by MDN contributors.
Your blueprint for a better internet.