views:

9240

answers:

4

I want to capture the HTTP request header fields, primarily the Referer and User-Agent, within my client-side JavaScript. How may I access them?


Google Analytics manages to get the data via JavaScript that they have you embed in you pages, so it is definitely possible.

+1  A: 

Related to this question.

keparo
+4  A: 

If you want to access referer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.

To retrieve the referer, it is document.referer, to access the user-agent, use navigator.userAgent.

EDIT: My apologies, it is document.referrer.

EDIT 2: Adding links requested:

document object: http://www.w3schools.com/htmldom/dom_obj_document.asp

navigator object: http://www.w3schools.com/htmldom/dom_obj_navigator.asp

As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.

Grant Wagner
Do you have a reference where I could find all the available values?
dacracot
I don't care if it is indirectly available, so don't read too much into my ignorant phrasing of the question.
dacracot
A: 

Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to embed those values in the JavaScript you produce.

It gets a little tricky to have server-side code generate client side code, so be sure that is what you need. For instance, if you want the User-agent information, you might find it sufficient to get the various values that JavaScript provides for browser detection. Start with navigator.appName and navigator.appVersion.

--
bmb

bmb
+1  A: 

I would imagine Google grabs some data server-side - remember, when a page loads into your browser that has Google Analytics code within it, your browser makes a request to Google's servers; Google can obtain data in that way as well as through the JavaScript embedded in the page.

Jason Bunting
No, Google's code is JavaScript embedded in my static html, in my case on sourceforge.net. There is zero possibility of server-side execution.
dacracot
Or do you mean on _their_ server?
dacracot
I mean _their_ server - your browser makes a request to their server when the page loads.
Jason Bunting
This request leaves your browser and hits their servers, sending data, baby:http://www.google-analytics.com/urchin.js
Jason Bunting
I just re-read my response - I *said* Google's server right there, why would you think I meant something else?
Jason Bunting
Yeah, I understand now... thank you.
dacracot