How to Get the Referrer in JavaScript

  • |
  • 28 March 2022
Image not Found

Whether it’s for analytics purposes or for any other reason, you sometimes need to know where a visitor to your site comes from. Did they click on a bookmark or type the URL? Or did they click on a link somewhere?

The referrer is the website that sent the web visitor to your site. In JavaScript, you can get it with a single line of code using the document.referrer property:

1
let site_referrer = document.referrer;

That’s it! It’s nice and simple.

The referrer is the website that sent the web visitor to your site.

How to Show a Different Version of Your Site Depending on Where Your Visitor Came From

You can use the referrer for many purposes, such as showing a slightly different version of your site to different users.

Let’s take a look at how to do this.

1
2
3
4
5
6
let site_referrer = document.referrer; 
if (site_referrer.includes("google.com")) {
	console.log("Welcome Google user!");
} else {
	console.log("Hello!");
}

The above code reads the referrer first. Then, depending on whether the address contains the stringgoogle.com”, we’ll get a different message on the console.

You May Also Like