31

Possible Duplicate:
Accessing HTTP Headers in Javascript?

The only way what i know to read with javascript the current headers is:

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();

But i don't want make a new request, i want read the current headers.

Is this posible? Thanks!

Community
  • 1
  • 1
fj123x
  • 6,904
  • 12
  • 46
  • 58

1 Answers1

23

It's not possible to access page headers via Javascript, without sending ajax request.

WTK
  • 16,583
  • 6
  • 35
  • 45
  • 5
    Can you put link that explains why? … obviously the question is about the response headers. They are available to the browser and they should de readable in JS. – sorin Aug 25 '13 at 19:22
  • 4
    Well, they're not. Response headers for regular requests (not the ones made using xmlhttp (ajax)), are handled by browser, and they aren't exposed to Javascript. While using ajax on the other hand, you have full access to both, request and response headers. – WTK Aug 26 '13 at 05:31
  • 11
    I understand that they are not as well, but I too am curious why. I can't think of any valid reason why it would be bad for Javascript to be able to read the headers of the current request. Especially if you can get them with an Ajax Request to the same page.... It's a wasted request to have to make a second request to get them. I would love to be able to have API config data in headers and initiate my API in the initial request, without having to do something hacky, like using hidden fields or dynamic javascript. – Ryan Mann Aug 31 '16 at 15:21
  • > "I can't think of any valid reason" Here's one: you could read the expected nonce of the current CSP and use it to inline XSS, that wouldn't otherwise be possible. (Because if you AJAX request to the same page, you _can't_ get that value, it's a nonce that changes on every page load specifically for that reason) – Dominic Scheirlinck Jan 25 '22 at 21:42