Get Current URL in JavaScript: A Practical Guide for Web Apps
Learn how to obtain the current URL in JavaScript using window.location, the URL API, and URLSearchParams. This guide covers syntax, parsing, SPA navigation, and practical examples for robust client-side code.

According to JavaScripting, getting the current URL in JavaScript is straightforward with the browser’s URL APIs. Read the full URL using window.location.href or construct a URL object from window.location to access components like protocol, host, pathname, and search. This quick answer covers common patterns for client-side code, debugging, and SPA scenarios.
Understanding the current URL in the browser
In modern web applications you often need to know the exact URL the user is viewing. This is essential for routing decisions, analytics, and building dynamic pages. The phrase get current url javascript is common in tutorials because browsers expose a small, well-defined surface for URL access. In the browser, the primary global for this task is the window object. You can read the full URL with window.location.href, or prefer the newer URL API when you need structured parts. For example, using new URL(window.location.href) gives you an object with properties like protocol, host, pathname, search, and hash. If you only need the string form, window.location.href is perfectly fine. For reference, the old document.URL is generally equivalent to location.href, but URL provides richer parsing capabilities. This section uses the keyword get current url javascript naturally to illustrate real-world usage.
// Read the full URL as a string
const fullUrl = window.location.href;
console.log('Full URL:', fullUrl);
// Parse it into a URL object for components
const parsed = new URL(window.location.href);
console.log(parsed.origin, parsed.pathname);// Alternative: read the string form from location
console.log(location.toString()); // alias of location.hrefNotes:
window.locationis widely supported across browsers.document.URLmirrorslocation.hrefin many cases.- The URL constructor helps when you need individual parts.
Accessing URL components with the URL API
The URL API is the recommended way to dissect and rebuild URLs in modern JavaScript. By creating a URL object, you can read and mutate individual parts without manual string parsing. The properties you’ll commonly use are protocol, host, hostname, port, pathname, search, and hash. This enables precise routing logic, query extraction, and dynamic navigation. In this section we’ll experiment with a few core properties and demonstrate a small transformation: keeping the origin but replacing the path. The first step is to create the URL object from the current location:
const current = new URL(window.location.href);
console.log(current.protocol, current.host, current.pathname);// Modify path and reflect in the URL string
current.pathname = '/new-path';
console.log(current.toString()); // e.g., https://example.com/new-pathUnderstanding the URL object helps you safely compose, compare, and route users without brittle string manipulation.
Reading query strings with URLSearchParams
Query parameters are a common source of dynamic behavior. The URLSearchParams API makes it easy to read and iterate over keys like ?q=search&sort=asc. Create it from a URL’s search portion and loop or fetch values with get/getAll:
const params = new URLSearchParams(window.location.search);
for (const [key, value] of params) {
console.log(key, value);
}// Get a specific value gracefully
const q = params.get('q') ?? '';
console.log('Query:', q);Tip: You can use params.has('foo') to check presence before reading values. If your app needs to support multiple values per key, use getAll.
SPA routing and URL changes without reload
Single-page applications switch views or routes by manipulating the browser URL without performing a full page reload. The History API provides pushState and replaceState for this, while reading changes with the popstate event. This lets you reflect navigation state in the URL and still preserve your app’s performance. Here’s a simple pattern to push a new URL state and listen for changes:
// Move to a new URL path without reloading
history.pushState({ page: 2 }, '', '/page2');
console.log(window.location.pathname);// Respond to back/forward navigation
window.addEventListener('popstate', (event) => {
console.log('URL changed to', window.location.pathname);
});This approach is central to robust SPA routing and back/forward behavior.
Practical patterns and edge cases
When writing code that relies on the current URL, prefer the URL API to avoid brittle string manipulation. If your app runs in a subframe, accessing window.location is subject to the same-origin policy—cross-origin frames may block access. Use new URL(window.location.href) to safely parse anyway, and consider defensive checks. If you’re testing in node environments, use the WHATWG URL class from Node.js to parse strings there as well. A common pattern is to extract a few important parts (origin, path, params) and recompose URLs for navigation tasks. Remember to debounce listeners if you’re updating URLs on rapid events (scroll, resize), and test across browsers for compatibility. This block demonstrates a practical function to return a compact summary of the current URL:
function currentUrlParts() {
const u = new URL(window.location.href);
return {
href: u.href,
protocol: u.protocol,
host: u.host,
hostname: u.hostname,
port: u.port,
path: u.pathname + u.search + u.hash
};
}
console.log(currentUrlParts());Edge-case note: in embedded frames, access might be blocked; ensure to check permissions and document security considerations.
Debugging and tooling tips
DevTools makes it easy to inspect the current URL and related properties. Use the Console to print URL parts and verify behavior in different routes. You can also set breakpoints in code that updates the URL and watch how location changes. In practice, you’ll often run quick checks like location.href or new URL(location.href) directly in the console. These checks help you validate assumptions during development and debugging sessions. The following snippet demonstrates quick verifications you can copy into your console:
// Quick checks in console
console.log('Full URL:', location.href);
console.log('Parsed host:', new URL(location.href).host);If you’re building tests, consider writing small unit tests that validate URL parsing logic using Jest or Vitest with mocked window.location values. This reduces surprises when your code runs in production.
Common patterns and best practices
To maximize reliability, capture the URL in a single, well-tested function and reuse it across your modules. Prefer the URL API for parsing and the URLSearchParams API for query strings. Document the parts you rely on so future you (or teammates) can adjust quickly. When writing cross-browser code, feature-detect URL constructors or fall back to location properties if necessary. For SPA apps, integrate with your router’s API to keep URL state in sync with the UI. Finally, avoid logging sensitive query parameters in production to protect user privacy; consider redacting or summarizing the URL where appropriate. The core pattern is: read URL -> parse with URL -> extract only what you need -> update/history without full reloads.
Steps
Estimated time: 60-90 minutes
- 1
Create a simple HTML page
Set up a minimal page with a script tag to access the current URL via window.location. This gives you a baseline for reading the URL string.
Tip: Test across at least two browsers. - 2
Read the full URL
Log window.location.href to confirm you can access the complete URL string.
Tip: Use location.href for quick reads. - 3
Parse with the URL API
Create a URL object from the current URL and inspect properties like protocol, host, and pathname.
Tip: Prefer new URL(location.href) for structured access. - 4
Extract query parameters
Use URLSearchParams to iterate over or fetch specific values from the query string.
Tip: Check for missing keys before reading values. - 5
Handle routing changes in SPA
Use history.pushState or replaceState to update the URL without full reload and listen to popstate.
Tip: Debounce updates if URL changes are frequent. - 6
Test in devtools and unit tests
Verify URL parsing logic with console checks and unit tests using mocked window.location.
Tip: Automate tests to avoid drift in production.
Prerequisites
Required
- Required
- Basic knowledge of window, location, and URLRequired
- Code editor and a simple HTML page to run snippetsRequired
- Required
Optional
- Optional
- Familiarity with SPA routing concepts (history.pushState, popstate)Optional
Keyboard Shortcuts
| Action | Shortcut |
|---|---|
| Open DevToolsIn any tab | Ctrl+⇧+I |
| Open ConsoleDevTools Console | Ctrl+⇧+J |
| Refresh page (hard reload)Reload with cache bypassed | Ctrl+⇧+R |
| Toggle DevTools dockChange docking position | Ctrl+⇧+D |
Questions & Answers
What is the difference between window.location and document.URL?
window.location provides a live Location object with properties you can read and mutate. document.URL is a string that mirrors the current URL in many browsers. For most tasks, the URL object and its properties offer safer, richer access.
Use window.location or the URL object for dynamic access; document.URL is mainly a string.
Can I read the current URL inside an iframe from another origin?
Access to location properties inside a cross-origin iframe is restricted by the same-origin policy. You can read the URL of the top window, but inner frames may block access depending on origin. Always honor SOP.
Cross-origin frames limit access; you may only read from the top window.
How can I modify the URL without reloading the page?
Use history.pushState or history.replaceState to update the URL and state without triggering a full page reload. Listen for popstate events to respond to back/forward navigation.
Push or replace the URL with History API and listen for popstate.
How do I extract query parameters from the current URL?
Create a URLSearchParams object from location.search and call get, getAll, or has to read values. It's the standard way to handle ?key=value pairs.
Grab query values with URLSearchParams.
Is there a difference between location.href and location.toString()?
location.href and location.toString() both yield the full URL string in most environments. Using the URL API is preferred when you need parts, not the entire string.
Both return the full URL, but URL helps you access parts.
Can I parse URL strings in Node.js too?
Yes. Node.js exposes the WHATWG URL class to parse and resolve URLs in server-side code, similar to the browser URL API.
Node has a URL class for parsing URLs.
What to Remember
- Read the URL with window.location.href
- Parse with URL and URLSearchParams
- Use History API for SPA URL changes
- Avoid logging sensitive URL parts in production