如何在 Javascript 中获取完整的主机名,包括 HTTP?
How to get the full host name in Javascript including HTTP?
我在 Javascript 中获取主机名时遇到问题,我使用了以下代码:
document.location.replace("http://"+ document.location.host + "/another-page")
代码工作正常,它获取主机名并将文档 URL 替换为新文档。
问题出在 document.location.host
,它只是 returns 像这样的主机:www.xxx.com 而没有 http 部分。这不是一种可扩展的方式,因为站点在本地运行在 http 上,而在服务器上运行在 https 上。我不想手动更改 http 部分。
那么有没有更好的解决方案来自动获取包含http(s)的主机全名?
这是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);
我在 Javascript 中获取主机名时遇到问题,我使用了以下代码:
document.location.replace("http://"+ document.location.host + "/another-page")
代码工作正常,它获取主机名并将文档 URL 替换为新文档。
问题出在 document.location.host
,它只是 returns 像这样的主机:www.xxx.com 而没有 http 部分。这不是一种可扩展的方式,因为站点在本地运行在 http 上,而在服务器上运行在 https 上。我不想手动更改 http 部分。
那么有没有更好的解决方案来自动获取包含http(s)的主机全名?
这是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);