【问题标题】:Get the current URL with JavaScript?使用 JavaScript 获取当前 URL?
【发布时间】:2010-11-05 07:09:35
【问题描述】:

我想要的只是获取网站 URL。不是从链接中获取的 URL。在页面加载时,我需要能够获取网站的完整当前 URL,并将其设置为变量以随意使用。

【问题讨论】:

标签: javascript url


【解决方案1】:

用途:

window.location.href

正如 cmets 中所述,下面的行有效,但它在 Firefox 中存在错误。

document.URL

URL of type DOMString, readonly

【讨论】:

  • 在 Firefox 12 中,document.URL 属性不会在 window.location 之后更新为锚点 (#),而 window.location.href 会。我没有测试任何其他版本的 Firefox。在 Chrome 20 和 IE9 中未发现使用 document.URL 的问题。
  • 您也可以获得主机和清除位置:window.location.hostwindow.location.href.toString().split(window.location.host)[1]
  • 然后document.baseURI 是什么。基本上有 3 种方式获取 url document.baseURI, document.URL, & location.
  • -1:如果您有一个带有name="URL" 的框架、图像或表​​单,那么此属性将在document 对象上被遮蔽,您的代码将中断。在这种情况下,document.URL 将改为引用 DOM 节点。最好使用window.location.href 中的全局对象的属性。
  • "window.location.href" 获胜
【解决方案2】:

网址信息访问

JavaScript 为您提供了许多检索和更改当前 URL 的方法,该 URL 显示在浏览器的地址栏中。所有这些方法都使用Location 对象,它是Window 对象的一个​​属性。您可以创建一个具有当前 URL 的新 Location 对象,如下所示:

var currentLocation = window.location;

基本网址结构

<protocol>//<hostname>:<port>/<pathname><search><hash>
  • 协议: 指定用于访问 Internet 上的资源的协议名称。 (HTTP(无 SSL)或 HTTPS(有 SSL))

  • 主机名: 主机名指定拥有资源的主机。例如,www.stackoverflow.com。服务器使用主机名提供服务。

  • 端口:一个端口号,用于识别 Internet 或其他网络消息到达服务器时要转发到的特定进程。

  • 路径名: 路径提供有关 Web 客户端想要访问的主机内特定资源的信息。例如,/index.html

  • 搜索: 查询字符串跟随路径组件,并提供资源可用于某些目的的信息字符串(例如,作为搜索参数或作为数据进行处理)。

  • 哈希: URL 的锚部分,包括井号 (#)。

通过这些Location 对象属性,您可以访问所有这些 URL 组件以及它们可以设置或返回的内容:

  • href - 整个网址
  • protocol - URL 的协议
  • host - URL 的主机名和端口
  • 主机名 - URL 的主机名
  • port - 服务器用于 URL 的端口号
  • 路径名 - URL 的路径名
  • 搜索 - 网址的查询部分
  • hash - 网址的锚点部分

希望你能得到答案..

【讨论】:

  • 它们不是window.location的“方法”,而是属性,而here we have an examplevar stringPathName = window.location.pathname
  • @FabioC。您可以通过substring 将其删除。但是,当您想使用重定向 document.location = "/page.html"; 将重定向到根页面时,它可能很有用 page.html
  • 这不仅回答了上述问题。事实上,大约一个月前,我搜索了一种从 URL 字符串中获取一个或多个特定部分的好方法(我认为这可能是我试图获取的当前页面),即使其他问题更多-target,他们的答案不如这个有用和直接。
  • 一个快速的建议:在上面描述的基本 URL 结构中,有一个 search 的位置,但在下面的描述列表中,它被称为 query。也许他们可以调和,或者可以添加进一步的解释。
  • 这叫“搜索”而不是“查询”
【解决方案3】:

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

【解决方案4】:

获取当前页面网址:

window.location.href

【讨论】:

  • 请注意,这是窗口的位置,而不是文档的位置。
  • 是一样的。完整的当前 URL 是指文档路径(外部地址)。
  • 是否像document.url一样标准化了? (我的意思是类似 w3c 文档)
  • document 是规范定义的文档树的根。 window 通常是等价的,但在某些奇怪的情况下可能不会。
【解决方案5】:

好的,使用纯 JavaScript 可以轻松获取当前页面的完整 URL。例如,在此页面上尝试以下代码:

window.location.href;
// use it in the console of this page will return
// http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser"

window.location.href 属性返回当前页面的 URL。

document.getElementById("root").innerHTML = "The full URL of this page is:&lt;br&gt;" + window.location.href;
<!DOCTYPE html>
<html>

<body>
  <h2>JavaScript</h2>
  <h3>The window.location.href</h3>
  <p id="root"></p>
</body>

</html>

顺便提一下这些也不错:

  • 如果需要相对路径,只需使用window.location.pathname

  • 如果要获取主机名,可以使用window.location.hostname

  • 如果需要单独获取协议,请使用window.location.protocol

    • 另外,如果你的页面有hash标签,你可以得到它:window.location.hash

所以window.location.href 一次性处理所有...基本上:

window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
    //true

如果已经在窗口范围内,也不需要使用window...

因此,在这种情况下,您可以使用:

location.protocol

location.hostname

location.pathname

location.hash

location.href

【讨论】:

    【解决方案6】:

    要获取路径,可以使用:

    console.log('document.location', document.location.href);
    console.log('location.pathname',  window.location.pathname); // Returns path only
    console.log('location.href', window.location.href); // Returns full URL

    【讨论】:

      【解决方案7】:

      打开开发者工具,在控制台中输入以下内容,然后按Enter

      window.location
      

      例如:下面是当前页面的结果截图。

      从这里获取您需要的东西。 :)

      【讨论】:

        【解决方案8】:

        使用:window.location.href

        如上所述,document.URL 在更新window.location 时不会更新。见MDN

        【讨论】:

          【解决方案9】:
          • 使用window.location.href 获取完整的URL。
          • 使用window.location.pathname 获取离开主机的URL。

          【讨论】:

          • window.location.pathname 不包括查询和哈希片段
          【解决方案10】:

          您可以使用get the current URL location with a hash tag

          JavaScript:

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

          jQuery

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

          【讨论】:

            【解决方案11】:

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

            document.location.toString()
            

            对于主机 URL:

            window.location
            

            【讨论】:

              【解决方案12】:
              var currentPageUrlIs = "";
              if (typeof this.href != "undefined") {
                     currentPageUrlIs = this.href.toString().toLowerCase(); 
              }else{ 
                     currentPageUrlIs = document.location.toString().toLowerCase();
              }
              

              上面的代码也可以帮助别人

              【讨论】:

                【解决方案13】:

                添加结果以供快速参考

                window.location;

                 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: ƒ
                , …}
                

                window.location.pathname

                "/questions/1034621/get-the-current-url-with-javascript"
                

                window.location.href

                "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"
                

                位置.主机名

                "stackoverflow.com"
                

                【讨论】:

                  【解决方案14】:

                  对于那些想要一个实际 URL 对象的人,可能是一个将 URL 作为参数的实用程序:

                  const url = new URL(window.location.href)
                  

                  https://developer.mozilla.org/en-US/docs/Web/API/URL

                  【讨论】:

                    【解决方案15】:

                    Nikhil Agrawal 的回答很棒,只需在此处添加一个小示例,您就可以在控制台中查看不同组件的运行情况:

                    如果您希望基本 URL 没有路径或查询参数(例如,针对 AJAX 请求在开发/登台和生产服务器上工作),window.location.origin 是最好的,因为它保留了协议以及可选端口(在 Django 开发中,有时你有一个非标准端口,如果你只使用主机名等会破坏它。)

                    【讨论】:

                      【解决方案16】:

                      在 jstl 中,我们可以使用 pageContext.request.contextPath 访问当前 URL 路径。如果要进行 Ajax 调用,请使用以下 URL。

                      url = "${pageContext.request.contextPath}" + "/controller/path"
                      

                      例如:对于页面http://stackoverflow.com/posts/36577223,这将给出http://stackoverflow.com/controller/path

                      【讨论】:

                        【解决方案17】:

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

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

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

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

                        【讨论】:

                          【解决方案18】:

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

                          1:

                          location.href;
                          

                          2:

                          document.URL;
                          

                          3:

                          document.documentURI;
                          

                          【讨论】:

                            【解决方案19】:
                            location.origin+location.pathname+location.search+location.hash;
                            

                            location.href
                            

                            做同样的事情。

                            【讨论】:

                              【解决方案20】:

                              使用这个:

                              var url = window.location.href;
                              
                              console.log(url);

                              【讨论】:

                                【解决方案21】:

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

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

                                【讨论】:

                                  【解决方案22】:
                                  let url = new URL(window.location.href);
                                  // http://127.0.0.1:8000/projects/page/member/assign/2/
                                  
                                  /*
                                  hash: ""
                                  
                                  host: "127.0.0.1:8000"
                                  
                                  hostname: "127.0.0.1"
                                  
                                  href: "http://127.0.0.1:8000/projects/page/member/assign/2/"
                                  
                                  origin: "http://127.0.0.1:8000"
                                  
                                  password: ""
                                  
                                  pathname: "/projects/page/member/assign/2/"
                                  
                                  port: "8000"
                                  
                                  protocol: "http:"
                                  
                                  search: ""
                                  */
                                  

                                  【讨论】:

                                    【解决方案23】:

                                    使用 JavaScript 获取当前 URL:

                                    • window.location.toString();

                                    • window.location.href

                                    【讨论】:

                                      【解决方案24】:

                                      试试

                                      location+''
                                      

                                      let url = location+'';
                                      
                                      console.log(url);

                                      【讨论】:

                                        【解决方案25】:

                                        如果您指的是具有 id 的特定链接,此代码可以帮助您。

                                        $(".disapprove").click(function(){
                                            var id = $(this).attr("id");
                                        
                                            $.ajax({
                                                url: "<?php echo base_url('index.php/sample/page/"+id+"')?>",
                                                type: "post",
                                                success:function()
                                                {
                                                    alert("The Request has been Disapproved");
                                                    window.location.replace("http://localhost/sample/page/"+id+"");
                                                }
                                            });
                                        });
                                        

                                        我在这里使用 ajax 提交 id 并使用 window.location.replace 重定向页面。只需按照说明添加属性id=""

                                        【讨论】:

                                          【解决方案26】:

                                          首先检查页面是否完全加载

                                          browser,window.location.toString();
                                          
                                          window.location.href
                                          

                                          然后调用一个函数,该函数接受 url、URL 变量并在控制台上打印,

                                          $(window).load(function(){
                                             var url = window.location.href.toString();
                                             var URL = document.URL;
                                             var wayThreeUsingJQuery = $(location).attr('href');
                                             console.log(url);
                                             console.log(URL);
                                             console.log(wayThreeUsingJQuery );
                                          });
                                          

                                          【讨论】:

                                            猜你喜欢
                                            • 1970-01-01
                                            • 2022-01-03
                                            • 2011-05-26
                                            • 1970-01-01
                                            相关资源
                                            最近更新 更多