2014-06-21 12 views
0

某些領域禁止訪問,我不希望顯示一些內容,如果訪客來自domain1.com domain2.com或domain3.com與document.referrer

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

這個代碼不工作的到來,另一個問題是document.referrer不抓取子域或www。必須完全按照請求的domain1.com,如果它包含www將不會被檢測到。

我對這個新......請不要提出任何htaccess的重寫規則

感謝

+1

不要相信引薦,有的人禁用或覆蓋它因涉及隱私。並注意JavaScript不是阻止網站的好方法,它運行客戶端和不允許的客戶端可以禁用它。 – Oriol

+0

你好,我試過用PHP http://stackoverflow.com/questions/24322570/http-referer-not-working-on-javascript-src但是我所有的網頁都寫在html格式 –

+0

PHP代碼是如此容易放置在HTML文檔中。只需將該文檔重命名爲.php,並將php代碼放在'<?php/* PHP here * /?>' – Oriol

回答

0

之前我解決您的問題,我必須說明這一點:

使用document.referrer很不好的選擇來解決這個問題。技能最小的人將能夠擊中view source按鈕並查看所有內容。這隻會是最基本的用戶。

document.referrer是非常不可靠的,即使用戶從您網站上的其他頁面訪問時,它仍然是空白的原因很多。

出於學習的目的,這是可以的,但這是在任何真實世界的應用程序或程序中不可接受的做法!

這就是說....

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()); 
+0

謝謝你的幫助。我想阻止不好的域名,但我不想列出好的域名。 –

+0

然後使用'alert(!isReferrerGood());' –

相關問題