Quick Javascript: How to get the URL of the current page

Johnny Simpson - Nov 27 '21 - - Dev Community

In Javascript, it is sometimes necessary to get the URL of the current web page you are on. There are a few ways to do this.

How to get the current URL with Javascript

If we want to get the full URL of the current web page, we simply have to use window.location.href.

// Shows us the current URL
let currentUrl = window.location.href;
Enter fullscreen mode Exit fullscreen mode

How to get the current domain URL with Javascript

If you only want to get the current domain, excluding any pages, you can run the following in Javascript:

let currentDomain = window.location.origin;
Enter fullscreen mode Exit fullscreen mode

For instance, if you were on https://google.com/page/search/go/, the above would simply return https://google.com.

How to get the path after the domain with Javascript

If you want to get only the path after the domain, then run the following:

let currentPath = window.location.pathname;
Enter fullscreen mode Exit fullscreen mode

Although these are the most common uses for window.location, there are also a number of other useful properties, such as:

  1. window.location.port - the current port
  2. window.location.protocol - the current protocol, i.e. https:
  3. window.location.hash - anything after a hash at the end of the URL
  4. window.location.hostname - the domain without any ports or protocols

๐Ÿ™‡โ€โ™‚๏ธ If you like this, consider supporting me on Patreon

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .