2011-02-07 92 views
1

我不是在寻找一个简单的重定向。基于域名的JavaScript重定向

我想要做的是这样的。

某甲负荷网站BOB.com和点击一个链接到页面X.
某乙负荷网站TIM.com和点击一个链接到同一页面X.

第X页上有一个JavaScript命令说,如果用户来自站点Bob.com,然后重定向到Bob.com/hello。
如果用户来自TIM.com,则重定向到Tim.com/hello。
如果用户did not来自ether然后重定向到Frank.com/opps。

此页面X将处理多个域名的404错误,因此它只需要查看域名upto“.com”。它应该忽略“.com”之后的所有内容。

这是我开始的脚本。

<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> 
+0

好吧,我要提到我倒没一个JavaScript编码器。 :) 除了告诉我使用document.referrer之外的任何帮助将是一个很大的帮助大声笑 – 2011-02-07 19:33:47

回答

6

使用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"; 
} 

取而代之的是正则表达式,你可以使用indexOf像你这样开始,但也将匹配thisisthewrongbob.comthisisthewrongtim.com;正则表达式更加健壮。

+0

好吧,我应该提到我没有太多的JavaScript编码器。 :)看起来这将是答案,但我不知道如何将其绑定到我的代码或如果这意味着我需要从头开始。 – 2011-02-07 19:32:12

0

使用document.referrer寻找到用户来自的地方。

更新的代码是

<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> 

工作example(它显示一条消息,而不是重定向)