Accessing the web page's HTTP Headers in JavaScript

前端 未结 17 2617
日久生厌
日久生厌 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: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
    

提交回复
热议问题