Search code examples
javascripthttp-headershttp-referer

How does javascript's referrer property work under the hood


How does javascript's referrer property work? Does it simply checks the http header data and outputs what it found there?

The referer property is accessed in the following way:

var ref = document.referrer;
console.log(ref);

Also, I noticed that the http referer (Chrome Dev Tools->Network->Top HTTP Request->Referer) is often stripped to only domain name without any subdomains. For example if an user has come from www.facebook.com/stackoverflow, his referer is always just www.facebook.com. Why is that so?


Solution

  • Remember to always read the documentation.

    The document.referrer property literally returns a string from the Request Header.

    Here's an example of me visiting this page from google:

    GET /questions/36609134/how-does-javascripts-referrer-property-work-under-the-hood HTTP/1.1
    Host: stackoverflow.com
    Connection: keep-alive
    Pragma: no-cache
    Cache-Control: no-cache
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36
    DNT: 1
    Referer: https://www.google.co.uk/
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-GB,en;q=0.8,en-US;q=0.6
    

    For more information on the request header referer visit Wikipedia.