How to get the current URL with JavaScript?
I need to retrieve the full, current website URL using JavaScript, not a URL from a link. When the page loads, I want to capture the complete URL and store it in a variable for further processing.
To get the current URL in JavaScript, the most straightforward method is using window.location.href, which returns the complete URL of the current page including protocol, domain, path, query parameters, and hash. You can also access individual components of the URL through properties like window.location.protocol, window.location.host, window.location.pathname, window.location.search, and window.location.hash. These methods are supported across all modern browsers and work immediately when the page loads.
Contents
- Getting the Full Current URL
- Accessing URL Components
- Browser Compatibility
- Practical Examples
- Alternative Methods
- Common Use Cases
Getting the Full Current URL
The most common and reliable way to get the complete current URL in JavaScript is by accessing the window.location.href property. This method returns the entire URL as a string, including all components from the protocol to any hash fragments.
// Get the complete current URL
let currentUrl = window.location.href;
// Example output: "https://example.com/path/to/page?param=value#section"
console.log(currentUrl);
According to Mozilla Developer Network, the window.location property returns a Location object with information about the current document’s location, and the href property specifically provides the complete URL.
You can also use the location object directly as a string in most modern browsers, as noted in the MDN documentation: “you can work with location as if it were a string in most cases”. This means location = 'new-url' works the same as location.href = 'new-url'.
Accessing URL Components
Sometimes you need specific parts of the URL rather than the complete string. The window.location object provides several properties that give you access to different URL components:
// Extract individual URL components
const protocol = window.location.protocol; // e.g., "https:"
const host = window.location.host; // e.g., "example.com:8080"
const hostname = window.location.hostname; // e.g., "example.com"
const port = window.location.port; // e.g., "8080"
const pathname = window.location.pathname; // e.g., "/path/to/page"
const search = window.location.search; // e.g., "?param=value&key=data"
const hash = window.location.hash; // e.g., "#section"
As CSS-Tricks explains, you can construct the full URL by combining these components: "var newURL = window.location.protocol + "//" + window.location.host + window.location.pathname". This approach gives you fine-grained control over which parts of the URL you want to use.
The freeCodeCamp guide provides a clear example of extracting multiple URL components at once for easy processing.
Browser Compatibility
The window.location methods are supported across all modern browsers with excellent compatibility:
- Chrome: Full support since early versions
- Firefox: Full support since early versions
- Safari: Full support since early versions
- Edge: Full support since the browser’s inception
- Internet Explorer: Has some quirks but works in IE10+
For cross-browser safety, it’s recommended to use window.location rather than document.location, as noted by GeeksforGeeks: “All modern browsers map document.location to the window.location but you can prefer window.location for cross-browser safety.”
If you need to support very old browsers, you can add a simple check as shown in the Stack Overflow discussion:
if (window.location) {
let currentUrl = window.location.href;
} else {
// Fallback for very old browsers
let currentUrl = document.URL;
}
However, such cases are extremely rare in modern web development.
Practical Examples
Here are several practical examples of getting and working with the current URL:
Basic URL Capture
// Store the current URL in a variable when the page loads
document.addEventListener('DOMContentLoaded', function() {
const currentUrl = window.location.href;
console.log('Current URL:', currentUrl);
// Store it for later use
window.myApp = {
currentPageUrl: currentUrl
};
});
URL Validation and Processing
function getCurrentUrlInfo() {
const url = window.location.href;
const urlObject = new URL(url);
return {
fullUrl: url,
protocol: urlObject.protocol,
domain: urlObject.hostname,
path: urlObject.pathname,
queryParams: urlObject.searchParams,
hash: urlObject.hash
};
}
// Usage
const urlInfo = getCurrentUrlInfo();
console.log('Domain:', urlInfo.domain);
console.log('Query parameters:', urlInfo.queryParams.toString());
Dynamic URL Construction
// Build a new URL based on current location with modifications
function buildNewUrl(path, params = {}) {
const baseUrl = window.location.origin;
const url = new URL(path, baseUrl);
// Add or update parameters
Object.keys(params).forEach(key => {
url.searchParams.set(key, params[key]);
});
return url.toString();
}
// Example usage
const newUrl = buildNewUrl('/search', {
q: 'javascript',
page: '2',
sort: 'relevance'
});
These examples demonstrate how to capture, process, and manipulate URLs effectively in your JavaScript applications.
Alternative Methods
While window.location.href is the most common method, there are several alternatives for getting the current URL:
document.location.href
const currentUrl = document.location.href;
This works identically to window.location.href in most cases, but window.location is preferred for cross-browser consistency.
document.URL
const currentUrl = document.URL;
As mentioned in Stack Overflow, "document.URL, which should contain the same value as window.location.href" and is a read-only string. This is useful when you want to ensure the URL cannot be modified accidentally.
URL() Constructor
For more advanced URL manipulation, you can use the modern URL() constructor:
const url = new URL(window.location.href);
console.log(url.hostname); // Domain name
console.log(url.pathname); // Path
console.log(url.searchParams.get('param')); // Get specific parameter
The CSS-Tricks article mentions this as “A bit of a more modern way of working with URLs”.
location.toString()
const currentUrl = location.toString();
As noted by SamanthaMing.com, this works but "href seems more explicit then toString(). It is very obvious that href will provide the URL whereas toString seems like something it being converted to a string".
Common Use Cases
Getting the current URL has many practical applications in web development:
Analytics and Tracking
// Track page views with URL information
function trackPageView() {
const url = window.location.href;
const path = window.location.pathname;
analytics.track('Page View', {
url: url,
path: path,
title: document.title,
timestamp: new Date().toISOString()
});
}
Dynamic Content Loading
// Load content based on URL parameters
function loadContentBasedOnUrl() {
const urlParams = new URLSearchParams(window.location.search);
const articleId = urlParams.get('article');
if (articleId) {
fetchArticleContent(articleId);
} else {
loadDefaultContent();
}
}
Navigation and Routing
// Client-side routing based on URL changes
function handleRouting() {
const path = window.location.pathname;
if (path === '/dashboard') {
loadDashboard();
} else if (path === '/profile') {
loadProfile();
} else {
loadHomePage();
}
}
// Listen for URL changes
window.addEventListener('popstate', handleRouting);
Bookmark and Share Functionality
// Create shareable links with current URL
function createShareLink() {
const currentUrl = window.location.href;
const shareUrl = `${currentUrl}?share=true`;
// Copy to clipboard or share
navigator.clipboard.writeText(shareUrl)
.then(() => showShareSuccess())
.catch(() => showShareError());
}
Form Pre-filling
// Pre-fill forms with URL parameters
function prefillForm() {
const urlParams = new URLSearchParams(window.location.search);
const name = urlParams.get('name');
const email = urlParams.get('email');
if (name) document.getElementById('name').value = name;
if (email) document.getElementById('email').value = email;
}
These examples show how capturing the current URL enables powerful functionality for modern web applications, from basic analytics to complex routing systems.
Conclusion
Getting the current URL in JavaScript is straightforward using the window.location.href property, which provides the complete URL as a string. For more granular control, you can access individual URL components like window.location.protocol, window.location.host, window.location.pathname, window.location.search, and window.location.hash. These methods are supported across all modern browsers with excellent compatibility, making them reliable choices for any web development project.
When implementing URL handling in your applications, consider these key recommendations:
- Always use
window.locationinstead ofdocument.locationfor better cross-browser compatibility - Extract URL components when you need specific parts rather than parsing the full URL string
- Use the
URL()constructor for advanced URL manipulation and parameter handling - Handle edge cases like very old browsers if your application needs to support them
- Consider security implications when working with URL parameters, especially from user input
By understanding these URL methods and their applications, you can build more robust and feature-rich web applications that effectively handle navigation, analytics, and dynamic content loading based on the current page URL.
Sources
- JavaScript Window Location - W3Schools
- Get URL and URL Parts in JavaScript - CSS-Tricks
- Get the current URL with JavaScript - Stack Overflow
- How to Get the Current URL with JavaScript – freeCodeCamp
- How To Get The Current URL With JavaScript - W3Schools
- Get the Current URL with JavaScript - Sentry
- Window: location property - MDN
- Location: href property - MDN
- JavaScript window.location and document.location Objects - GeeksforGeeks
- window.location Cheatsheet - SamanthaMing.com