我只想获取网站URL。不是从链接获取的URL。在页面加载时,我需要能够获取网站的完整、当前URL,并将其设置为一个变量,以便根据需要进行处理。


当前回答

要获取路径,可以使用:

http://www.example.com:8082/index.php#tab2?foo=789

Property                    Result
------------------------------------------
window.location.host        www.example.com:8082
window.location.hostname    www.example.com
window.location.port        8082
window.location.protocol    http:
window.location.pathname    index.php
window.location.href        http://www.example.com:8082/index.php#tab2
window.location.hash        #tab2
window.location.search      ?foo=789
window.location.origin      https://example.com

其他回答

location.origin+location.pathname+location.search+location.hash;

and

location.href

也一样。

要获取路径,可以使用:

console.log('document.location',document.location.href);console.log('location.pathname',window.location.pathname);//仅返回路径console.log('location.href',window.location.href);//返回完整URL

短的

location+''

let url=location+'';console.log(url);

对于那些想要一个实际的URL对象的人,可能是一个以URL为参数的实用程序:

const url = new URL(window.location.href)

https://developer.mozilla.org/en-US/docs/Web/API/URL

var currentPageUrlIs = "";
if (typeof this.href != "undefined") {
       currentPageUrlIs = this.href.toString().toLowerCase(); 
}else{ 
       currentPageUrlIs = document.location.toString().toLowerCase();
}

以上代码也可以帮助某人