How to Get Current URL in JavaScript

In JavaScript there are several methods to get current URL displayed at the address bar. All 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).

The Window.location read-only property returns a Location object with information about the current location of the document.

Before understanding how to access the entire URL or its components, let’s have a look at a basic URL structure:

  • protocol - the name of protocol used to access the resource on the Internet. (HTTP, HTTPS, FTP, etc)
  • hostname - the host that owns the resource.
  • port - a port number used to recognize a specific process to which an Internet or other network message is to be 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 - provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
  • hash - the anchor portion of a URL, includes the hash sign (#).

Use the following Location object properties to access the entire URL or its components.

  1. window.location.href - to get the entire URL
  2. - to get the hostname and port of the URL
  3. window.location.hostname - to get the hostname of the URL
  4. window.location.protocol - to get the protocol of the URL in address bar
  5. window.location.pathname- to get the path and filename of the current page
  6. - to get the query portion of the URL
  7. window.location.hash- to get the anchor portion of the URL

Use window.location.href property to get the entire URL of the current page:


<!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;

Do you find this helpful?

Related articles