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


当前回答

您可以通过location.href获取当前页面的完整链接要获取当前控制器的链接,请使用:

location.href.substring(0, location.href.lastIndexOf('/'));

其他回答

使用JavaScript获取当前URL:

window.location.toString();窗口.location.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"

let url=新url(window.location.href);console.log(url.href);

使用以上代码获取网站的当前URL。

或者试试这个https://bbbootstrap.com/code/get-current-url-javascript-54628697

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

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

使用window.location对与当前帧关联的位置对象进行读写访问。如果您只想以只读字符串形式获取地址,可以使用document.URL,它应该包含与window.location.href相同的值。