Languages
[Edit]
EN

JavaScript - get source page URL (source: referral)

6 points
Created by:
Wiktor-Sribiew
860

In this short article, we would like to show you how get website URL from which the user came using JavaScript in web browser.

Quick solution:

const url = document.referrer;

 

Note: sometimes document.referrer can be empty depending on possible rel="noreferrer" attribute used in the source link.

Hint: it is good to consider using UTM links to detect source if it is possible.

 

Example results

Possible document.referrer values may look like:

https://google.com

https://dirask.com
https://dirask.com/posts
https://dirask.com/posts?page=10
https://dirask.com/posts?page=10#details

etc.

 

Practical example

Note: copy source code and paste it to your website to see correct effect.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="element"></div>
  <script>

    var element = document.querySelector('#element');

    element.innerText = 'Source URL: ' + document.referrer;

  </script>
</body>
</html>

 

See also

  1. JavaScript - detect if user entered webpage directly (source: direct)

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join