How do I access the HTTP request header fields via

2019-01-03 16:09发布

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

6条回答
The star\"
2楼-- · 2019-01-03 16:53

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.

查看更多
\"骚年 ilove
3楼-- · 2019-01-03 16:54

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.

查看更多
别忘想泡老子
4楼-- · 2019-01-03 17:00

This can be accessed through Javascript because it's a property of the loaded document, not of its parent.

Here's a quick example:

<script type="text/javascript">
document.write(document.referrer);
</script>

The same thing in PHP would be:

<?php echo $_SERVER["HTTP_REFERER"]; ?>
查看更多
ら.Afraid
5楼-- · 2019-01-03 17:03

Referer and user-agent are request header, not response header.

That means they are sent by browser, or your ajax call (which you can modify the value), and they are decided before you get HTTP response.

So basically you are not asking for a HTTP header, but a browser setting.

The value you get from document.referer and navigator.userAgent may not be the actual header, but a setting of browser.

查看更多
仙女界的扛把子
6楼-- · 2019-01-03 17:05
var ref = Request.ServerVariables("HTTP_REFERER");

Type within the quotes any other server variable name you want.

查看更多
叼着烟拽天下
7楼-- · 2019-01-03 17:14

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.

查看更多
登录 后发表回答