Accessing HTTP Headers in JavaScript
JavaScript offers limited options for accessing HTTP response headers of the current web page. Unlike accessing request headers, which can be retrieved through properties like XMLHttpRequest.getAllResponseHeaders(), there is no direct way to acquire these headers purely through JavaScript.
Note: A previous question on accessing specific HTTP headers via JavaScript has been modified.
Possible Solution: Indirect Header Retrieval
While obtaining the real-time headers is not feasible, you can simulate a GET request to the same URL using XMLHttpRequest. This simulated response will provide you with the headers, offering a close approximation to the actual headers.
Sample Code:
To retrieve all HTTP headers via this workaround, use the following JavaScript code:
var req = new XMLHttpRequest(); req.open('GET', document.location, true); req.send(null); req.onload = function() { var headers = req.getAllResponseHeaders().toLowerCase(); console.log(headers); };
By leveraging this approach, you can gain insights into the web page's HTTP headers. However, keep in mind that this simulated request may not guarantee absolute accuracy compared to the original headers.
The above is the detailed content of How Can I Access HTTP Response Headers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!