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


当前回答

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

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

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

其他回答

要获取路径,可以使用:

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

使用window.location.href获取完整的URL。使用window.location.pathname获取离开主机的URL。

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

document.location.toString()

对于主机URL:

window.location

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

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

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

使用:window.location.href。

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