Question

How to Get the Current URL in JavaScript

Question

I want to get the full current page URL in JavaScript. I do not mean the URL from a link element. When the page loads, I need to capture the complete current website URL and store it in a variable so I can use it later in my code.

Short Answer

By the end of this page, you will understand how to read the current page URL in JavaScript, when to use window.location.href, how the location object is structured, and how developers use URL data in real applications.

Concept

JavaScript in the browser provides information about the current page through the window.location object. This object contains details about the URL of the page that is currently open.

If you want the full URL as a string, the most common choice is:

window.location.href

This includes everything in the current address, such as:

  • protocol (https:)
  • hostname (example.com)
  • path (/products)
  • query string (?page=2)
  • hash (#details)

For example, if the browser is currently on:

https://example.com/products?page=2#details

then window.location.href returns exactly that full string.

This matters because many web applications need to know where the user currently is. Common tasks include:

  • redirecting users after login
  • reading query parameters
  • tracking page visits
  • building share links
  • checking whether the user is on a specific route

The important idea is that window.location is not just a string. It is an object with several useful properties. href is the property that gives you the full URL.

Mental Model

Think of window.location as the browser's address card for the current page.

  • The whole card is the location object.
  • Each field on the card is a different part of the address.
  • href is the complete address written in one line.

So if you need the full address, ask for the full line:

window.location.href

If you only need one part, such as the domain or pathname, you can read just that field instead.

Take Quiz

Syntax and Examples

Basic syntax

const currentUrl = window.location.href;

This stores the full current page URL in a variable.

Shorter version

Because location is a property of window, this also works in browsers:

const currentUrl = location.href;

Example

const currentUrl = window.location.href;
console.log(currentUrl);

If the user is on:

https://example.com/about?ref=home#team

the output will be:

https://example.com/about?ref=home#team

Other useful URL parts

console.log(window.location.protocol); // "https:"
console.log(window.location.hostname); // "example.com"
console.log(window.location.pathname); // "/about"
console.log(window.location.search);   // "?ref=home"
console.log(window.location.hash);     // "#team"

Use these when you do not need the full URL, only a specific piece.

Step by Step Execution

Consider this code:

const currentUrl = window.location.href;
console.log(currentUrl);

Assume the browser is currently at:

https://mysite.com/shop/items?id=10#reviews

Step by step

  1. The browser loads the page.
  2. JavaScript runs window.location.href.
  3. The browser looks at the current page address.
  4. It returns the full URL as a string:
    "https://mysite.com/shop/items?id=10#reviews"
    
  5. That string is stored in currentUrl.
  6. console.log(currentUrl) prints the value to the console.

Result

currentUrl === "https://mysite.com/shop/items?id=10#reviews"

This means you can now:

  • save it
  • compare it
  • send it to an API
  • display it in the page
  • use it in conditional logic

Real World Use Cases

Common uses of the current URL

Analytics and tracking

A site may record which page a user visited:

const currentUrl = window.location.href;
console.log(`Tracking visit to ${currentUrl}`);

Redirect after login

A page can save the current URL so the user returns to it later:

const returnTo = window.location.href;
sessionStorage.setItem("returnTo", returnTo);

Conditional page logic

Run code only on certain pages:

if (window.location.pathname === "/checkout") {
  console.log("Initialize checkout logic");
}

Share links

Use the current page URL in a share button:

const shareUrl = window.location.href;
console.log(`Share this page: ${shareUrl}`);

Reading query parameters

A page may need values from the URL:

const params = new URLSearchParams(window.location.search);
console.log(params.get("id"));
Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just read the full URL once. They often combine URL access with application logic.

Common patterns

Guard clauses

Only run code when a URL matches a specific route:

if (window.location.pathname !== "/dashboard") {
  return;
}

console.log("Dashboard code runs here");

Validation

Check that required query parameters exist:

const params = new URLSearchParams(window.location.search);
const productId = params.get("id");

if (!productId) {
  console.error("Missing product id in URL");
}

Configuration by route

Applications sometimes enable features based on the current path:

const isAdminPage = window.location.pathname.startsWith("/admin");

Error handling

When debugging, developers log the current URL to understand where an issue happened:

try {
  // some code
} catch (error) {
  console.error("Error on page:", window.location.href, error);
}

SPA routing awareness

In single-page applications, developers often read URL parts to decide which view to render. Even when frameworks manage routing, the underlying idea is still based on URL information.

Common Mistakes

1. Using window.location when a string is expected

window.location is an object, not just a plain URL string.

Less clear

const url = window.location;

This may work in some contexts because it can be converted to a string, but it is better to be explicit.

Better

const url = window.location.href;

2. Confusing the current page URL with a link's URL

This gets the URL from an anchor element, not the current page:

const linkUrl = document.querySelector("a").href;

If you want the current page URL, use:

const currentUrl = window.location.href;

3. Using the wrong property

Beginners sometimes use pathname when they actually need the full URL.

console.log(window.location.pathname);

This returns only something like:

/products

It does not include the protocol, domain, query string, or hash.

4. Forgetting that query strings and hashes are included in href

If you only want the base path, href may include more than expected.

For example:

https://example.com/page?sort=asc#top

If you need only the pathname:

console.log(window.location.pathname);

5. Trying to use browser-only code outside the browser

This works in browser JavaScript:

window.location.href

But it will fail in environments that do not have window, such as some server-side contexts.

Comparisons

OptionWhat it gives youExample outputWhen to use
window.location.hrefFull current URLhttps://example.com/page?x=1#topWhen you need the complete address
window.location.pathnamePath only/pageWhen checking the route or page path
window.location.hostnameDomain onlyexample.comWhen checking which host the user is on
window.location.searchQuery string only?x=1When reading URL parameters
window.location.hashHash only#topWhen working with page fragments

window.location vs document.URL

Both can give the current URL in many browser cases.

OptionTypeTypical use
window.location.hrefProperty on the location objectMost common and explicit choice
document.URLProperty on the documentLess commonly used for this purpose

For beginner code, window.location.href is usually the clearest choice.

Take Quiz

Cheat Sheet

// Full current URL
const url = window.location.href;

// Short form
const url2 = location.href;

// Other useful parts
const protocol = window.location.protocol;
const hostname = window.location.hostname;
const pathname = window.location.pathname;
const search = window.location.search;
const hash = window.location.hash;

Quick rules

  • Use window.location.href for the full URL.
  • Use pathname for only the path.
  • Use search for query parameters.
  • Use hash for the fragment after #.
  • window.location is an object.
  • href is the full URL string.

Example

If the page is:

https://example.com/blog/post?id=5#comments

Then:

window.location.href      // "https://example.com/blog/post?id=5#comments"
window.location.protocol  // "https:"
window.location.hostname  // "example.com"
window.location.pathname  // "/blog/post"
window.location.search    // "?id=5"
window.location.hash      // "#comments"

FAQ

How do I get the current page URL in JavaScript?

Use:

const url = window.location.href;

How do I get only the path of the current URL?

Use:

const path = window.location.pathname;

Does window.location.href include query parameters?

Yes. It includes the full URL, including the query string and hash if they exist.

Can I use location.href instead of window.location.href?

Yes. In browser JavaScript, location.href is a shorter equivalent.

What is the difference between href and pathname?

href is the full URL. pathname is only the path part, such as /products.

Can I store the current URL in a variable when the page loads?

Yes.

const currentUrl = window.location.href;

Is window.location a string?

No. It is an object with properties like href, pathname, hostname, and search.

Take Quiz

Mini Project

Description

Build a small page inspector script that reads the current URL and displays its parts. This helps you practice getting the full URL and breaking it into useful sections such as hostname, pathname, query string, and hash.

Goal

Create a script that stores the current page URL in a variable and prints both the full URL and its individual parts.

Requirements

  1. Store the full current URL in a variable.
  2. Display the full URL in the console.
  3. Display the protocol, hostname, pathname, search, and hash.
  4. Show a custom message when the page contains a query string.
  5. Show a custom message when the URL contains a hash fragment.
Take Quiz

Keep learning

Related questions

View more