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:
xxxxxxxxxx
1
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.
Possible document.referrer
values may look like:
xxxxxxxxxx
1
https://google.com
2
3
https://dirask.com
4
https://dirask.com/posts
5
https://dirask.com/posts?page=10
6
https://dirask.com/posts?page=10#details
7
8
etc.
Note: copy source code and paste it to your website to see correct effect.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element"></div>
5
<script>
6
7
var element = document.querySelector('#element');
8
9
element.innerText = 'Source URL: ' + document.referrer;
10
11
</script>
12
</body>
13
</html>