Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the HTTP request header fields via JavaScript?

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.

Related:
Accessing the web page's HTTP Headers in JavaScript

like image 489
dacracot Avatar asked Oct 20 '08 22:10

dacracot


People also ask

Can Javascript access HTTP headers?

You can't access the http headers, but some of the information provided in them is available in the DOM. For example, if you want to see the http referer (sic), use document. referrer.


2 Answers

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.

like image 32
bmb Avatar answered Oct 06 '22 01:10

bmb


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

To retrieve the referrer, use document.referrer.
To access the user-agent, use navigator.userAgent.

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.

like image 197
Grant Wagner Avatar answered Oct 06 '22 03:10

Grant Wagner