Get the current URL with JavaScript?

后端 未结 23 1964
梦谈多话
梦谈多话 2020-11-21 07:08

All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a va

相关标签:
23条回答
  • 2020-11-21 07:52

    In jstl we can access the current URL path using pageContext.request.contextPath. If you want to do an Ajax call, use the following URL.

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

    Example: For the page http://stackoverflow.com/posts/36577223 this will give http://stackoverflow.com/controller/path.

    0 讨论(0)
  • 2020-11-21 07:53

    You can get the current URL location with a hash tag by using:

    JavaScript:

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

    jQuery:

    $(location).attr('href');
    
    0 讨论(0)
  • 2020-11-21 07:54
    • Use window.location.href to get the complete URL.
    • Use window.location.pathname to get URL leaving the host.
    0 讨论(0)
  • 2020-11-21 07:57

    Use: window.location.href.

    As noted above, document.URL doesn't update when updating window.location. See MDN.

    0 讨论(0)
  • 2020-11-21 07:57

    Adding result for quick reference

    window.location;

     Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
     ancestorOrigins: DOMStringList,
     origin: "https://stackoverflow.com",
     replace: ƒ, assign: ƒ, …}
    

    document.location

      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"
    

    location.hostname

    "stackoverflow.com"
    
    0 讨论(0)
  • 2020-11-21 07:58

    Use window.location for read and write access to the location object associated with the current frame. If you just want to get the address as a read-only string, you may use document.URL, which should contain the same value as window.location.href.

    0 讨论(0)
提交回复
热议问题