Each time a page is requested I get the referrer of the page it came from. I need to track just referrer from other sites, I don't want to track going from one page to another within my site. How can I do that?
问题:
回答1:
document.referrer.indexOf(location.protocol + "//" + location.host) === 0;
回答2:
Originally posted at JavaScript - Am I the Referrer?
When someone comes to our website for the first time, we store the referrer in a cookie. This way, if they download our demo, we can get the original referrer from the cookie and we learn what sites are effective in driving leads to us.
Of course, every subsequent page a visitor hits on our website will show the referrer as our website. We don't want those. What we first did to avoid this was look for the text "windward" in the referrer and if so, assume that was from our site. The problem with this is we found a lot of referrer urls now have windward in them, either as a search term or part of a url that talks about Windward. (This is good news, it means we are now a well known product.)
So that brought me to our most recent approach. This should work for any site and should only reject referrers from the same site.
function IsReferredFromMe()
{
var ref = document.referrer;
if ((ref == null) || (ref.length == 0)) {
return false;
}
if (ref.indexOf("http://") == 0) {
ref = ref.substring(7);
}
ref = ref.toLowerCase();
var myDomain = document.domain;
if ((myDomain == null) || (myDomain.length == 0)) {
return false;
}
if (myDomain.indexOf("http://") == 0) {
myDomain = myDomain.substring(7);
}
myDomain = myDomain.toLowerCase();
return ref.indexOf(myDomain) == 0;
}
回答3:
Solutions presented works in case of no sub domain in website in case of sub domain is there then we have to check just before the domain itself if any sub domains presented:
document.referrer.replace("http://", '').replace("https://", '').split('/')[0].match(new RegExp(".*" +location.host.replace("www.", '')))
this solution will add .* before the domain to detect that sub domain is from same domain.
回答4:
document.referrer.includes(location.host);