Accessing the web page's HTTP Headers in JavaScript

前端 未结 17 2527
日久生厌
日久生厌 2020-11-21 04:53

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.

<
相关标签:
17条回答
  • 2020-11-21 05:27

    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.

    0 讨论(0)
  • 2020-11-21 05:28

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

    0 讨论(0)
  • 2020-11-21 05:33

    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.

    0 讨论(0)
  • 2020-11-21 05:33

    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.

    <!DOCTYPE html>
    <title>(XHR) Show all response headers</title>
    
    <h1>All Response Headers with XHR</h1>
    <script>
     var X= new XMLHttpRequest();
     X.open("HEAD", location);
     X.send();
     X.onload= function() { 
       document.body.appendChild(document.createElement("pre")).textContent= X.getAllResponseHeaders();
     }
    </script>
    

    Note: You get headers of a second request, the result may differ from the initial request.


    Another way
    is the more modern fetch() API
    https://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:

    <!DOCTYPE html>
    <title>fetch() all Response Headers</title>
    
    <h1>All Response Headers with fetch()</h1>
    <script>
     var x= "";
     if(window.fetch)
        fetch(location, {method:'HEAD'})
        .then(function(r) {
           r.headers.forEach(
              function(Value, Header) { x= x + Header + "\n" + Value + "\n\n"; }
           );
        })
        .then(function() {
           document.body.appendChild(document.createElement("pre")).textContent= x;
        });
     else
       document.write("This does not work in your browser - no support for fetch API");
    </script>
    
    0 讨论(0)
  • 2020-11-21 05:35

    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 function parseHttpHeaders:

    function parseHttpHeaders(httpHeaders) {
        return httpHeaders.split("\n")
         .map(x=>x.split(/: */,2))
         .filter(x=>x[0])
         .reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
    }
    
    var req = new XMLHttpRequest();
    req.open('GET', document.location, false);
    req.send(null);
    var headers = parseHttpHeaders(req.getAllResponseHeaders());
    // Now we can do:  headers["content-type"]
    
    0 讨论(0)
  • 2020-11-21 05:37

    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:

    var xhr = new XMLHttpRequest(); 
    xhr.open('POST', url, true); 
    xhr.responseType = "blob";
    xhr.onreadystatechange = function () { 
        if (xhr.readyState == 4) {
            success(xhr.response); // the function to proccess the response
    
            console.log("++++++ reading headers ++++++++");
            var headers = xhr.getAllResponseHeaders();
            console.log(headers);
            console.log("++++++ reading headers end ++++++++");
    
        }
    };
    

    Output:

    Date: Fri, 16 Aug 2013 16:21:33 GMT
    Content-Disposition: attachment;filename=testFileName.doc
    Content-Length: 20
    Server: Apache-Coyote/1.1
    Content-Type: application/octet-stream
    
    0 讨论(0)
提交回复
热议问题