0

I don't want to display some content if visitors are coming from domain1.com domain2.com or domain3.com

<script>
var refers = document.referrer;

if(refers!="domain1.com") {
// bye bye content will not be displayed if domain1.com is the refer
} else if (refers!="domain2.com"){
// bye bye content will not be displayed if domain2.com is the refer
} else if (refers!="domain3.com") {
// bye bye content will not be displayed if domain3.com is the refer
} 
else {
// All other domains referrers are allowed to see the content
}
</script>

This code don't work, the another problem is that document.referrer do not grab sub-domains or www. Must be exactly as requested domain1.com if it contains www will not be detected.

I am new on this... Please do not suggest any htaccess rewrite rule

Thanks

Red Acid
  • 217
  • 1
  • 3
  • 14
  • 1
    Don't trust referrer, some people disable or override it because of privacy. And note javascript isn't a good way to block the site, it runs client-side and not-allowed clients can just disable it. – Oriol Jun 21 '14 at 01:46
  • hello, I've tried with php http://stackoverflow.com/questions/24322570/http-referer-not-working-on-javascript-src But all of my pages are written in .html format – Red Acid Jun 21 '14 at 01:50
  • PHP code is so easy to place inside HTML documents. Just rename the document to .php and place the php code in `` – Oriol Jun 21 '14 at 01:54

1 Answers1

0

Before I address your question, I have to state this:

Using document.referrer is very bad choice to solve this problem. Anyone with the smallest about of skill will be able to hit the view source button and see everything. This will only the most basic of users.

document.referrer is horribly unreliable and there are many reasons why it will be blank, even when the user is visiting from another page on your site.

For learning purposes this is OK, but this is an unacceptable practice in any real-world application or program!

That said....

function isReferrerGood() {

  function strEndsWith(str, suffix) {
    var reguex = new RegExp(suffix + '$');

    if (str.match(reguex) != null)
      return true;

    return false;
  }

  var i;
  var domain;
  var goodDomains = [
    "example.com",
    "example2.com"
  ];

  var ref = document.referrer;
  // For testing purposes, we'll set our own value
  // Note that this is a sub-domain of one of our good domains.
  ref = "abc.example.com";

  // Loop through the domains
  for (i = 0; i < goodDomains.length; i++) {
    domain = goodDomains[i];
    if (strEndsWith(ref, domain)) {
      return true;
    }
  }
  return false;

}
alert(isReferrerGood());
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74