How to Get Current URL in JavaScript

JavaScript suggests a bunch of methods that help to get the current URL displayed at the address bar. All of the methods use the Location object (contains information about the current URL), which is a property of the Window object (provides current page address (URL) and redirects the browser to a new page).

You can use the window.location.href property to get the entire URL of the current page including all the components:

<!DOCTYPE html>
    <title>Title of the Document</title>
    <p id="href"></p>
      document.getElementById("href").innerHTML ="The full URL of this page is:<br>" + window.location.href;

Let’s have a look at a basic URL structure:

  • protocol - the name of the protocol used to access the resource on the Internet. (HTTP, HTTPS, FTP, etc).
  • hostname - the host that owns the resource.
  • port - the port number used to recognize a process to which an Internet/other network message is forwarded when it arrives at a server (most HTTP URLs omit the port number).
  • pathname - the specific resource in the host that the web client wants to access.
  • query - presents a string of information that the resource utilizes for some purpose.
  • hash - represents the anchor portion of a URL, including the hash sign (#).


The Window.location is a read-only property that returns a Location object with a piece of information about the document's current location. The following Location object properties are used to access the entire URL or its components:

  • window.location.href - gets the whole URL.
  • - gets the hostname and URL's port.
  • window.location.hostname - gets the URL's hostname.
  • window.location.protocol - gets the URL's protocol in the address bar.
  • window.location.pathname- gets the current page's path and filename.
  • - gets the URL's query portion.
  • window.location.hash- gets the URL's anchor portion.