如何使用Javascript(包括HTTP)获取完整的主机名?

时间:2018-11-29 14:50:53

标签: javascript url hostname

我在使用Javascript获取主机名时遇到问题,我使用了以下代码:

document.location.replace("http://"+ document.location.host + "/another-page")

该代码可以正常工作,它获取主机名并将文档URL替换为新的URL。

问题出在document.location.host上,它仅返回如下主机: www.xxx.com ,而没有 http 部分。这不是可扩展的方法,因为该站点在本地运行在http上,而在服务器运行在https上。我不想手动更改http部分。

那么,有没有更好的解决方案来自动获得包括http(s)在内的主机的全名?

1 个答案:

答案 0 :(得分:3)

您要寻找的是这个location.origin吗?

或者您只能使用此location.protocol

获得协议

在此处查看更多-https://developer.mozilla.org/en-US/docs/Web/API/Location

console.log('location.protocol -', location.protocol);
console.log('location.origin -', location.origin);

相关问题