36

If I search for something on google and click on a result (mytestsite.com), the referer to that site will be URL of the google search.

Now on that site, there is a JS file include that is used for tracking purposes..however the referrer to that JS file request is mytestsite.com...is there no way for the server handling the JS request to know that it originated from a google search?

puffpio
  • 3,402
  • 6
  • 36
  • 41

2 Answers2

97

I'm a little unclear on what you are trying to do, but you can grab the referrer with JavaScript using:

document.referrer

...and pass it along to the server in your request for the JS file. Several ways to do this...here's one:

<script>
 var e = document.createElement("script");
 e.src = 'someJSfile.js?referrer='+document.referrer;
 e.type="text/javascript";
 document.getElementsByTagName("head")[0].appendChild(e);
</script>
droo
  • 1,059
  • 6
  • 5
7

A script tag will always refer to the document that is sourcing it. If you're doing something special on the server you might want to consider using a session or cookies.

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 1
    the referrer is available per the other answer on here. – Brady Moritz Aug 26 '13 at 22:33
  • 3
    @boomhauer: The solutions are virtually the same, the difference being that I didn't mention `document.referrer`. My point was that the server cannot know the previous site's referrer when the JS is requested (only when the HTML is requested), which is what the question was asking. The only difference in the solution is that the other answer is passing the referrer as a query string instead of as a request header. I've updated my answer to clarify the intent and solution, but generally I think people are misreading the question. – Andy E Aug 29 '13 at 11:49
  • The second part of this answer is wrong and the example can't work. `referer` is among the [forbidden header names](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) which "cannot be modified programmatically". – Reinstate Monica -- notmaynard Jun 24 '16 at 18:03
  • @iamnotmaynard: Good spot. Back when I wrote this answer, most of my work was targeted specifically at IE 7, which doesn't throw for those forbidden header names. – Andy E Jun 27 '16 at 11:25