EN
JavaScript - get source page URL (source: referral)
6
points
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 possiblerel="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>