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


当前回答

您可以使用以下方法获取带有哈希标记的当前URL位置:

JavaScript:

 // Using href
 var URL = window.location.href;

 // Using path
 var URL = window.location.pathname;

jQuery:

$(location).attr('href');

其他回答

使用:window.location.href。

如上所述,更新window.location时,document.URL不会更新。请参阅MDN。

Nikhil Agrawal的回答很好,只是在这里添加了一个小示例,您可以在控制台中看到不同的组件:

如果您想要不带路径或查询参数的基本URL(例如,对其执行AJAX请求以在开发/登台和生产服务器上运行),window.location.origin是最好的,因为它保留了协议和可选端口(在Django开发中,有时会有一个非标准端口,如果您只使用主机名等,就会中断它)

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

以上代码也可以帮助某人

使用此项:

var url=window.location.href;console.log(url);

对于带有查询字符串的完整URL:

document.location.toString()

对于主机URL:

window.location