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


当前回答

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

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

其他回答

获取当前页面URL:

window.location.href

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

document.location.toString()

对于主机URL:

window.location

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

JavaScript:

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

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

jQuery:

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

添加结果以供快速参考

窗口位置;

 Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
 ancestorOrigins: DOMStringList,
 origin: "https://stackoverflow.com",
 replace: ƒ, assign: ƒ, …}

文档位置

  Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript", 
ancestorOrigins: DOMStringList,
 origin: "https://stackoverflow.com",
 replace: ƒ, assign: ƒ
, …}

窗口位置路径名

"/questions/1034621/get-the-current-url-with-javascript"

窗口.location.href

"https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"

位置主机名

"stackoverflow.com"

Use:

window.location.href

正如评论中所指出的,下面这行行是有效的,但它对Firefox来说是错误的。

document.URL

请参阅DOMString类型的URL,只读。