'Problems with document.referrer
I'm having some trouble using document.referrer on some sites, even the reference site using HTTP protocol.
In what circumstances document.referrer may be empty (except HTTPS to HTTP)?
What is the best way to get the url reference only document.referrer?
In my site, document.referrer is empty, but when I look in Analytics website of references appears.
Solution 1:[1]
document.referrer
is not empty
if your site URL was clicked from other website, like from google search, from facebook, twitter, etc...
So, If someone opens your site from bookmark o directly types your site URL, document.referrer
is empty
.
Let's see these examples:
Click this link http://www.w3schools.com/jsref/prop_doc_referrer.asp you can see that document.referrer is http://stackoverflow.com/questions/28646433/problems-with-document-referrer
If you search in google HTML DOM referrer Property
, document.referrer will be http://google.es/...
And if you copy http://www.w3schools.com/jsref/prop_doc_referrer.asp
opens new tab in your browser and paste it, document.referrer
will be empty
.
Solution 2:[2]
const referrerPage = document.referrer;
if ((referrerPage.indexOf(window.location.href) > -1) !== true) { // If referral is same page then page will not redirect.
if (referrerPage.indexOf('viewplans') <= -1) {
window.location.href = '/';
return false;
}
}
viewplans is the page name.
Solution 3:[3]
To answer your second question, this simple script returns the URL of the site you arrived from:
<SCRIPT>
document.write ( document.referrer )
</SCRIPT>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | clemp6r |
Solution 2 | marc_s |
Solution 3 | Art |