JavaScript:我可以得到完整的url,包括域名、文件名和协议吗



我相信这应该是可能的,但当我查看谷歌时,它告诉我的只是如何获得文件名和其他东西,我不想要这样。

我正在寻找这个,因为我使用Weebly作为我的网络主机,它只允许.html文件-当你点击"主页"时,你会被带到/index.html,当你打开网站时,没有/index.html。

如果我可以添加(当然使用if语句)JS,如果网站的url==http://kingdomofmuqtasid.weebly.com/index.html并将身体指向:http://kingdomofmuqtasid.weebly.com.

PS:代码可以放在身体内部吗?

window.location.href

是当前页面的完整URL。有关更多信息,请参阅window.location的MDN文档页面。

您可以将此代码放在页面的<head>部分或<body>部分中进行重定向。

<script>
if (window.location.href == "http://kingdomofmuqtasid.weebly.com/index.html") {
    window.location = "http://kingdomofmuqtasid.weebly.com/";
}
</script>

附言:当查看器转到"http://kingdomofmuqtasid.weebly.com/index.html".

您可以使用window.location来获取这些数据。使用上面的代码,您可以在window.location上进行迭代,并获得所需的数据。

var location = window.location;
for ( var i in location ) {
    console.log( i + " " + location[i] );
}

最新更新