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


当前回答

你有多种方法可以做到这一点。

1:

location.href;

2:

document.URL;

3:

document.documentURI;

其他回答

打开开发人员工具,在控制台中键入以下内容,然后按Enter键。

window.location

下面是当前页面上的结果截图。

从这里获取您需要的信息。:)

Use:

window.location.href

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

document.URL

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

使用window.location.href获取完整的URL。使用window.location.pathname获取离开主机的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

要获取路径,可以使用:

http://www.example.com:8082/index.php#tab2?foo=789

Property                    Result
------------------------------------------
window.location.host        www.example.com:8082
window.location.hostname    www.example.com
window.location.port        8082
window.location.protocol    http:
window.location.pathname    index.php
window.location.href        http://www.example.com:8082/index.php#tab2
window.location.hash        #tab2
window.location.search      ?foo=789
window.location.origin      https://example.com