Get the current URL with JavaScript?

后端 未结 23 2409
梦谈多话
梦谈多话 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:37

    OK, getting the full URL of the current page is easy using pure JavaScript. For example, try this code on this page:

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

    The window.location.href property returns the URL of the current page.

    document.getElementById("root").innerHTML = "The full URL of this page is:
    " + window.location.href;
    
    
    
    
      

    JavaScript

    The window.location.href

    Just not bad to mention these as well:

    • if you need a relative path, simply use window.location.pathname;

    • if you'd like to get the host name, you can use window.location.hostname;

    • and if you need to get the protocol separately, use window.location.protocol

      • also, if your page has hash tag, you can get it like: window.location.hash.

    So window.location.href handles all in once... basically:

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

    Also using window is not needed if already in window scope...

    So, in that case, you can use:

    location.protocol
    
    location.hostname
    
    location.pathname
    
    location.hash
    
    location.href
    

提交回复
热议问题