簡體   English   中英

基於域名的JavaScript重定向

[英]JavaScript redirect based on domain name

我不是在尋找簡單的重定向。

我想做的就是這個。

人物A加載網站BOB.com,然后單擊指向頁面X的鏈接。
人物B加載站點TIM.com,然后單擊指向同一頁面X的鏈接。

X頁面上有一個javascript命令,上面寫着:如果用戶來自站點Bob.com,則重定向到Bob.com/hello。
如果用戶來自TIM.com,則重定向到Tim.com/hello。
如果用戶不是來自以太坊,則重定向到Frank.com/opps。

該頁面X將處理多個域的404錯誤,因此僅需查看域名最多為“ .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> 

使用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 正則表達式更強大。

document.referrer是要去的地方

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

工作示例 (顯示消息而不是重定向)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM