我计划为同一个网站购买两个域名。根据所使用的域,我计划在页面上提供稍微不同的数据。是否有一种方法可以让我检测页面正在加载的实际域名,以便我知道要将我的内容更改为什么?

我到处找过这样的东西,但大多数都不是我想要的方式。

例如,当使用

document.write(document.location)

在JSFiddle上返回

http://fiddle.jshell.net/_display/

也就是实际的路径。


当前回答

对于我的情况,最好的匹配是window.location.origin

其他回答

https://publicsuffix.org/list/

(https://github.com/publicsuffix/list/blob/master/public_suffix_list.dat)

需要正确地解析出所有没有后缀的域,在上面的答案中使用点永远不会完全正确。可以对公共后缀dat文件运行上面的代码样例来实现这一点。

您可以基于此编写自己的代码,或者使用https://www.npmjs.com/package/tldts这样的包

getDomainWithoutSuffix('google.com');        // returns `google`
getDomainWithoutSuffix('fr.google.com');     // returns `google`
getDomainWithoutSuffix('fr.google.google');  // returns `google`
getDomainWithoutSuffix('foo.google.co.uk');  // returns `google`
getDomainWithoutSuffix('t.co');              // returns `t`
getDomainWithoutSuffix('fr.t.co');           // returns `t`
getDomainWithoutSuffix('https://user:password@example.co.uk:8080/some/path?and&query#hash'); // returns `example`

Use

document.write(document.location.hostname)​

窗口。Location有很多属性。请看这里的列表。

我是JavaScript的新手,但你不能只使用:文档。域?

例子:

<p id="ourdomain"></p>

<script>
var domainstring = document.domain;
document.getElementById("ourdomain").innerHTML = (domainstring);
</script>

输出:

domain.com

or

www.domain.com

这取决于你在你的网站上使用什么。

即使问题是关于域名,接受的解决方案包括子域名(如。调用location.hostname)得到blog.example.com。 为了将来的参考,我建议使用一行程序来只提取域(例如。https://blog.example.com/index.html -> example.com)作为Micheal。

location.hostname.split('.').filter(( _, i) => i < 2).join('.')

小心!当TLD由两部分组成时(例如.co.uk),它可能会崩溃。如果是这样的话,在上面的代码中修改2和3。

您可以使用它来删除端口号。

var 主机名 = 窗口.位置.主机; var urlWithoutPort = 'https://${hostname}'; console.log(urlWithoutPort);