How can I read the current headers without making a new request with JS? [duplicate]
Asked Answered
D

1

32

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!

Domeniga answered 4/9, 2012 at 7:31 Comment(4)
You can find the answer here: #220731Dulla
i don't want make a new requestDomeniga
If by "current headers" you mean headers of the page currently loaded the answer is you can't.Understate
Here is a very pertinent answer to your question: #220731Betthezel
U
25

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

Understate answered 4/9, 2012 at 7:41 Comment(4)
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.Centerboard
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.Understate
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.Wehrmacht
> "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)Beckwith

© 2022 - 2024 — McMap. All rights reserved.