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


当前回答


// http://127.0.0.1:8000/projects/page/2?name=jake&age=34
let url = new URL(window.location.href);
/*
hash: ""

host: "127.0.0.1:8000"

hostname: "127.0.0.1"

href: "http://127.0.0.1:8000/projects/page/2?username=jake&age=34"

origin: "http://127.0.0.1:8000"

password: ""

pathname: "/projects/page/2"

port: "8000"

protocol: "http:"

search: "?name=jake&age=34"

username: ""
*/

url.searchParams.get('name')
// jake

url.searchParams.get('age')
// 34

url.searchParams.get('gender')
// null

其他回答

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

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

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

添加结果以供快速参考

窗口位置;

 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"

要获取路径,可以使用:

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

获取当前页面URL:

window.location.href

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

JavaScript:

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

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

jQuery:

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