JavaScript redirect based on domain name

10,186

Solution 1

Use document.referrer

if(/http:\/\/(www\.)?bob\.com/.test(document.referrer)) {
   window.location = "http://bob.com/hello";
}

else if(/http:\/\/(www\.)?tim\.com/.test(document.referrer)) {
   window.location = "http://tim.com/hello";
}

else {
   window.location = "http://frank.com/oops";
}

Instead of the regex, you can use indexOf like you did initially, but that would also match thisisthewrongbob.com and thisisthewrongtim.com; the regex is more robust.

Solution 2

document.referrer is the place to be

Solution 3

Use document.referrer to find where the user came from.

The updated code is

<script type='text/javascript'>
  var ref = document.referrer,
      host = ref.split('/')[2],
      regexp = /(www\.)?(bob|tim).com$/,
      match = host.match(regexp);

  if(ref && !regexp.test(location.host)) { 
  /* Redirect only if the user landed on this page clicking on a link and 
    if the user is not visiting from bob.com/tim.com */
    if (match) {
      ref = ref.replace("http://" + match.shift() +"/hello");
    } else {
      ref = 'http://frank.com/oops';
    }

    window.location = ref;
  }
</script>

working example (it displays a message rather than redirecting)

Share:
10,186
webmaster alex l
Author by

webmaster alex l

Webmaster

Updated on September 07, 2022

Comments

  • webmaster alex l
    webmaster alex l over 1 year

    I am not looking for a simple redirect.

    What I am trying to do is this.

    Person A loads site BOB.com and clicks a link to page X.
    Person B loads site TIM.com and clicks a link to the same page X.

    Page X has a javascript command on it that says, If user came from site Bob.com then redirect to Bob.com/hello.
    If user came from TIM.com then redirect to Tim.com/hello.
    If user didnt come from ether then redirect to Frank.com/opps.

    This page X is going to handle 404 errors for multiple domains so it will need to ONLY look at the domain name upto ".com". It should ignore everything past the ".com".

    This is the script I started with.

    <script type='text/javascript'>
    var d = new String(window.location.host);
    var p = new String(window.location.pathname);
    var u = "http://" + d + p;
    if ((u.indexOf("bob.com") == -1) && (u.indexOf("tim.com") == -1))
    {
    u = u.replace(location.host,"bob.com/hello");
    window.location = u;
    }
    </script> 
    
  • webmaster alex l
    webmaster alex l about 13 years
    Ok, i should mention I am not much of a JavaScript coder. :) It looks like it would be the answer but im not sure how to tie it into my code or if this means I need to start from scratch.
  • Mahesh Velaga
    Mahesh Velaga about 13 years
    It has the url from which the user came to this page from, essentially the info that you need, Tim.com or bob.com etc