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


当前回答

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

其他回答

URL信息访问

JavaScript为您提供了许多方法来检索和更改显示在浏览器地址栏中的当前URL。所有这些方法都使用Location对象,这是Window对象的属性。您可以通过读取window.Location来读取当前Location对象:

var currentLocation = window.location;

基本URL结构

<protocol>//<hostname>:<port>/<pathname><search><hash>

protocol:指定用于访问Internet上资源的协议名称。(HTTP(不带SSL)或HTTPS(带SSL))hostname:主机名指定拥有资源的主机。例如,www.stackeoverflow.com。服务器使用主机名提供服务。端口:用于识别Internet或其他网络消息到达服务器时要转发到的特定进程的端口号。路径名:路径提供有关Web客户端希望访问的主机内特定资源的信息。例如,/index.html。搜索:路径组件后面有一个查询字符串,它提供了资源可以用于某些目的的信息字符串(例如,作为搜索的参数或作为要处理的数据)。hash:URL的锚定部分,包括哈希符号(#)。

使用这些Location对象财产,您可以访问所有这些URL组件以及它们可以设置或返回的内容:

href-整个URLprotocol-URL的协议host—URL的主机名和端口hostname—URL的主机名port-服务器用于URL的端口号pathname—URL的路径名search-URL的查询部分hash-URL的锚定部分origin-window.location.protocol+'//'+window.location.host

我希望你得到了答案。。

添加结果以供快速参考

窗口位置;

 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"

要获取路径,可以使用:

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

使用:window.location.href。

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

获取当前位置对象的方法是window.location。

将其与document.location进行比较,后者最初仅以字符串形式返回当前URL。可能是为了避免混淆,document.location被document.URL替换。

而且,所有现代浏览器都会将document.location映射到window.location。

实际上,为了跨浏览器安全,应该使用window.location而不是document.location。