2014-06-21 39 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());' –

相关问题