Get the current URL with JavaScript?

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

    Nikhil Agrawal's answer is great, just adding a little example here you can do in the console to see the different components in action:

    If you want the base URL without path or query parameter (for example to do AJAX requests against to work on both development/staging AND production servers), window.location.origin is best as it keeps the protocol as well as optional port (in Django development, you sometimes have a non-standard port which breaks it if you just use hostname etc.)

    0 讨论(0)
  • 2020-11-21 07:59
    location.origin+location.pathname+location.search+location.hash;
    

    and

    location.href
    

    does the same.

    0 讨论(0)
  • 2020-11-21 08:02

    Open Developer Tools, type in the following in the console and press Enter.

    window.location
    

    Ex: Below is the screenshot of the result on the current page.

    Grab what you need from here. :)

    0 讨论(0)
  • 2020-11-21 08:03

    Gets the current page URL:

    window.location.href
    
    0 讨论(0)
  • 2020-11-21 08:03

    To get the path, you can use:

    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

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