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

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

例如,当使用

document.write(document.location)

在JSFiddle上返回

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

也就是实际的路径。


当前回答

结合上面的一些答案,以下是我销毁cookie的有效方法:

  /**
   * Utility method to obtain the domain URI:
   */
  fetchDomainURI() {
    if (window.location.port.length > 0) {
      return window.location.hostname;
    }
    return `.${window.location.hostname.match(/\w*\.\w*$/gi)[0]}`;
  }

适用于具有端口的IP地址,例如,0.0.0.0:8000等,以及复杂的域,如app.staging.example.com返回。example.com =>允许跨域Cookie设置和销毁。

其他回答

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

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

因为这个问题问的是域名,而不是主机名,所以正确答案应该是

window.location.hostname.split('.').slice(-2).join('.')

这也适用于像www.example.com这样的主机名。

我觉得应该这么简单:

url.split("/")[2]

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

例子:

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

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

输出:

domain.com

or

www.domain.com

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

你可以很容易地从Javascript中的location object中获得它:

例如,这个页面的URL是:

http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc

然后我们可以通过location对象的以下属性获得准确的域:

location.host = "www.stackoverflow.com"
location.protocol= "http:"

您可以使用以下方法创建完整的域:

location.protocol + "//" + location.host

在这个例子中,哪个返回http://www.stackoverflow.com

我添加这个,我们可以得到完整的URL和路径与location对象的其他属性:

location.href= "http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"    
location.pathname= "questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"