使用javascript获得域名,包括子域名

Use javascript to get domain name including subdomains

本文关键字:域名 包括 javascript 使用      更新时间:2023-09-26

我只是想知道是否有一种方法可以得到一些未来的证明,因为我们可能会创建新的子域名,并希望人们知道他们正在使用的网站是正确的(因为我们有一些人重新托管我们的网站)

if(window.location.href != "example.com" || "*.example.com"){
document.getElementById('alert').innerHTML = "This is site is not recognized as an official site";}

其中"*"是任何子域的通配符,ID"alert"是我们用来显示重要消息的div。

使用location.hostname并检查它是否以您的域名结尾,例如:

if(!location.hostname.match(/example.com$/)){
     alert(...);
}

这将匹配域example.com以及www.example.com和任何subdomain.example.com。但它也会匹配像otherexample.com这样的东西。为了防止这种情况,使用以下regex:

if(!location.hostname.match(/(^|'.)example.com$/)){
     alert(...);
}

这个regex匹配任何只有example.com或者以点开头以example.com结尾的内容,所以www.example.comsubdomain.example.com,但是不匹配otherexample.com因为前面没有点example.com

我宁愿考虑使用元标题X-Frame-Options和content - security - policies来解决您的重新托管问题。

X-Frame-Options: https://stackoverflow.com/a/19843216/634264

Content-Security-Policys: http://www.html5rocks.com/en/tutorials/security/content-security-policy/