Set the request header in JavaScript.

It seems that I cannot change most of the request headers from JavaScript when calling AJAX using XMLHttpRequest. Note that when request.setRequestHeader needs to be called after request.open() in Gecko browsers (see http://ajaxpatterns.org/Talk:XMLHttpRequest_Call ). When I install Referer, it does not install (I looked at the request headers sent using Firebug and Tamper Data). When I install the User-Agent, it completely confused the AJAX call. However, setting Accept and Content-Type works. Is setting up Referer and User-Agent preventable in Firefox 3?

 var request = new XMLHttpRequest(); var path="http://www.yahoo.com"; request.onreadystatechange=state_change; request.open("GET", path, true); request.setRequestHeader("Referer", "http://www.google.com"); //request.setRequestHeader("User-Agent", "Mozilla/5.0"); request.setRequestHeader("Accept","text/plain"); request.setRequestHeader("Content-Type","text/plain"); request.send(null); function state_change() { if (request.readyState==4) {// 4 = "loaded" if (request.status==200) {// 200 = OK // ...our code here... alert('ok'); } else { alert("Problem retrieving XML data"); } } } 
+55
javascript ajax
Aug 12 '09 at 20:52
source share
3 answers

W3C Spec on setrequestheader .

Brief points:

If the request header has already been set, then the new value MUST be combined with the existing value using COMMA U + 002C followed by a space U + 0020 for separation.

UAs may indicate the initial value of the User-Agent header, but MUST allow authors to add values ​​to it.

However, after searching the XHR framework in jQuery, they do not allow you to change the headers of the User-Agent or Referer. Nearest:

 // Set header so the called script knows that it an XMLHttpRequest xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 

I am inclined to believe that what you want to do is denied by the security policy in FF - if you want to pass some kind of custom header like Referer that you can always do:

 xhr.setRequestHeader('X-Alt-Referer', 'http://www.google.com'); 
+64
Aug 12 '09 at 22:24
source share

@gnarf answer is correct. wanted to add more information.

Mozilla Bug Help: https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Complete these steps if the header is a case insensitive match for one of the following headers:

 Accept-Charset Accept-Encoding Access-Control-Request-Headers Access-Control-Request-Method Connection Content-Length Cookie Cookie2 Date DNT Expect Host Keep-Alive Origin Referer TE Trailer Transfer-Encoding Upgrade User-Agent Via 

Source: https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

+3
Dec 11 '13 at 21:16
source share

For people who are watching this now.

This header now seems to be resolved with Firefox 43. See https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name for the current list of prohibited headers.

+1
Apr 09 '16 at 11:22
source share



All Articles