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?

0

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

it's a bit funny that not you answer marked as correct. document.referrer - it's the best
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.

4 Comments

the referrer is available per the other answer on here.
@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.
The second part of this answer is wrong and the example can't work. referer is among the forbidden header names which "cannot be modified programmatically".
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.